Programs & Examples On #Msgfmt

How do I escape reserved words used as column names? MySQL/Create Table

You should use back tick character (`) eg:

create table if not exists misc_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL)ENGINE=INNODB;

Stacked bar chart

Building on Roland's answer, using tidyr to reshape the data from wide to long:

library(tidyr)
library(ggplot2)

df <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

df %>% 
  gather(variable, value, F1:F3) %>% 
  ggplot(aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

Can't create project on Netbeans 8.2

As the other people said, NetBeans is always going to use the latest version of JDK installed (currently JDK9) which is not working with NetBeans 8.2 and is causing problems as you guys mentioned.

You can solve this problem by forcing NetBeans to use JDK8 instead of deleting JDK9!
You just have to edit netbeans.conf file:
MacOS /Applications/NetBeans/NetBeans8.2.app/Contents/Resources/NetBeans/etc
Windows C:\Program Files\NetBeans 8.2\etc\

Open netbeans.conf with your favourite editor and find this line: netbeans_jdkhome="/path/to/jdk" Remove # sign in front of it and modify it by typing your desired JDK version (JDK8) home location.

Im not sure why is JDK9 not working with NetBeans8.2, but if I found out I will write it here...


Default JDK locations:

Mac OS ?

/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

Windows ?

C:\Program Files\Java\jdk1.8.0_152

I've used jdk1.8.0_152 as example

How to disable Home and other system buttons in Android?

You can't disable Home button from ICS onwords but can disable other buttons as follows

@Override
public boolean dispatchKeyEvent(KeyEvent keyEvent){
   return true;
}

Default port for SQL Server

The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.

Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg (SQL Server Client Network Utility) on each client machine.

For more information see SQL Server Browser Service on MSDN.

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How to secure phpMyAdmin

Another solution is to use the config file without any settings. The first time you might have to include your mysql root login/password so it can install all its stuff but then remove it.

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

$cfg['Servers'][$i]['host'] = 'localhost';

$cfg['Servers'][$i]['connect_type'] = 'tcp';

$cfg['Servers'][$i]['compress'] = false;

$cfg['Servers'][$i]['extension'] = 'mysql';

Leaving it like that without any apache/lighhtpd aliases will just present to you a log in screen. enter image description here

You can log in with root but it is advised to create other users and only allow root for local access. Also remember to use string passwords, even if short but with a capital, and number of special character. for example !34sy2rmbr! aka "easy 2 remember"

-EDIT: A good password now a days is actually something like words that make no grammatical sense but you can remember because they funny. Or use keepass to generate strong randoms an have easy access to them

Setting focus on an HTML input box on page load

And you can use HTML5's autofocus attribute (works in all current browsers except IE9 and below). Only call your script if it's IE9 or earlier, or an older version of other browsers.

<input type="text" name="fname" autofocus>

Iterate through a C++ Vector using a 'for' loop

The right way to do that is:

for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
    it->doSomething();
 }

Where T is the type of the class inside the vector. For example if the class was CActivity, just write CActivity instead of T.

This type of method will work on every STL (Not only vectors, which is a bit better).

If you still want to use indexes, the way is:

for(std::vector<T>::size_type i = 0; i != v.size(); i++) {
    v[i].doSomething();
}

lexical or preprocessor issue file not found occurs while archiving?

For what it's worth, my problem was completely unrelated to the error Xcode was giving. I stumbled onto a solution by deleting the .h reference, compiling, adding the reference back and compiling again. The actual error then became evident.

Getting the array length of a 2D array in Java

It was really hard to remember that

    int numberOfColumns = arr.length;
    int numberOfRows = arr[0].length;

Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:

    int[][] arr = { {1, 1, 1, 1}, 

                    {2, 2, 2, 2}, 

                    {3, 3, 3, 3} };

arr has multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of columns. To get the number of rows, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of rows by accessing the first array then its length. The other one (arr.length) is for the columns.

console.log showing contents of array object

Seems like Firebug or whatever Debugger you are using, is not initialized properly. Are you sure Firebug is fully initialized when you try to access the console.log()-method? Check the Console-Tab (if it's set to activated).

Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.

Difference between git pull and git pull --rebase

In the very most simple case of no collisions

  • with rebase: rebases your local commits ontop of remote HEAD and does not create a merge/merge commit
  • without/normal: merges and creates a merge commit

See also:

man git-pull

More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With --rebase, it runs git rebase instead of git merge.

See also:
When should I use git pull --rebase?
http://git-scm.com/book/en/Git-Branching-Rebasing

Java: Finding the highest value in an array

You are just Compare zeroth element with rest of the elements so it will print the value last largest value which it will contain, in you case, same problem is happening. To compare each and every elements we have to swap the values like:

double max = decMax[0];
    for (int counter = 1; counter < decMax.length; counter++){
        if(max<decMax[i]){
            max=decMax[i]; //swapping
            decMax[i]=decMax[0];
        }
    }
    System.out.println("The max value is "+ max);

Hope this will help you

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

Thought I would throw in my resolution to this since font-awesome is now installed differently according to their documentation.

npm install --save-dev @fortawesome/fontawesome-free

Why it is fortawesome now escapes me but thought I would stick with the most recent version rather than falling back to the old font-awesome.

Then I imported it into my scss

$fa-font-path: "../node_modules/@fortawesome/fontawesome-free/webfonts";
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/brands";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/v4-shims";

Hope this helps

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I catch the next case about cors. Maybe it will be useful to somebody. If you add feature 'WebDav Redirector' to your server, PUT and DELETE requests are failed.

So, you will need to remove 'WebDAVModule' from your IIS server:

  • "In the IIS modules Configuration, loop up the WebDAVModule, if your web server has it, then remove it".

Or add to your config:

<system.webServer>
<modules>
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="WebDAV" />
  ...
</handlers>

Richtextbox wpf binding

 <RichTextBox>
     <FlowDocument PageHeight="180">
         <Paragraph>
             <Run Text="{Binding Text, Mode=TwoWay}"/>
          </Paragraph>
     </FlowDocument>
 </RichTextBox>

This seems to be the easiest way by far and isn't displayed in any of these answers.

In the view model just have the Text variable.

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

How to remove class from all elements jquery

You need to select the li tags contained within the .edgetoedge class. .edgetoedge only matches the one ul tag:

$(".edgetoedge li").removeClass("highlight");

How to increase application heap size in Eclipse?

Open eclipse.ini

Search for -Xmx512m or maybe more size it is.

Just change it to a required size such as I changed it to -Xmx1024m

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I think you will understand it through these examples below.

Source code structure:

/src/main/webapp/subdir/sample.jsp
/src/main/webapp/sample.jsp

Context is: TestApp
So the entry point: http://yourhostname-and-port/TestApp


Forward to RELATIVE path:

Using servletRequest.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> \subdir\sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
http://yourhostname-and-port/TestApp/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character


Forward to ABSOLUTE path:

Using servletRequest.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

How to jump to top of browser page

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("myBtn").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("myBtn").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#myBtn {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#myBtn:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_

HTML5 Pre-resize images before uploading

Correction to above:

<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
<script>

function handleFiles()
{
    var filesToUpload = document.getElementById('input').files;
    var file = filesToUpload[0];

    // Create an image
    var img = document.createElement("img");
    // Create a file reader
    var reader = new FileReader();
    // Set the image once loaded into file reader
    reader.onload = function(e)
    {
        img.src = e.target.result;

        var canvas = document.createElement("canvas");
        //var canvas = $("<canvas>", {"id":"testing"})[0];
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        var dataurl = canvas.toDataURL("image/png");
        document.getElementById('image').src = dataurl;     
    }
    // Load files into file reader
    reader.readAsDataURL(file);


    // Post the data
    /*
    var fd = new FormData();
    fd.append("name", "some_filename.jpg");
    fd.append("image", dataurl);
    fd.append("info", "lah_de_dah");
    */
}</script>

orderBy multiple fields in Angular

Make sure that the sorting is not to complicated for the end user. I always thought sorting on group and sub group is a little bit complicated to understand. If its a technical end user it might be OK.

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

String concatenation with Groovy

I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.

Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:

@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*

def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

That gives me the following output on my machine:

Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
    * JRE: 1.6.0_31
    * Total Memory: 81.0625 MB
    * Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64) 

Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

String adder               539
GString template           245
Readable GString template  244
StringBuilder              318
StringBuffer               370

So with readability and speed in it's favour, I'd recommend templating ;-)

NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion

Adding these tests (as it has been asked in the comments)

  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }

Now we get the results:

String adder                        514
GString template                    267
Readable GString template           269
GString template toString           478
Readable GString template toString  480
StringBuilder                       321
StringBuffer                        369

So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...

But still lots more readable.

Edit after comment by ruralcoder below

Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:

@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )

def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
  'StringBuffer with Allocation' {
    new StringBuffer( 512 ).append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

gives

Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
    * JRE: 1.7.0_21
    * Total Memory: 467.375 MB
    * Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         630       0  630   647
GString template                      29       0   29    31
Readable GString template             32       0   32    33
GString template toString            429       0  429   443
Readable GString template toString   428       1  429   441
StringBuilder                        383       1  384   396
StringBuffer                         395       1  396   409
StringBuffer with Allocation         277       0  277   286

Extract file name from path, no matter what the os/path format

Actually, there's a function that returns exactly what you want

import os
print(os.path.basename(your_path))

WARNING: When os.path.basename() is used on a POSIX system to get the base name from a Windows styled path (e.g. "C:\\my\\file.txt"), the entire path will be returned.

Example below from interactive python shell running on a Linux host:

Python 3.8.2 (default, Mar 13 2020, 10:14:16)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.
>>> os.path.basename(filepath)
'C:\\my\\path\\to\\file.txt'

How to print a dictionary line by line in Python?

I prefer the clean formatting of yaml:

import yaml
print(yaml.dump(cars))

output:

A:
  color: 2
  speed: 70
B:
  color: 3
  speed: 60

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

How do I check whether a checkbox is checked in jQuery?

This worked for me:

$get("isAgeSelected ").checked == true

Where isAgeSelected is the id of the control.

Also, @karim79's answer works fine. I am not sure what I missed at the time I tested it.

Note, this is answer uses Microsoft Ajax, not jQuery

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

Converting Java objects to JSON with Jackson

Well, even the accepted answer does not exactly output what op has asked for. It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:

StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

I am using ASP.NET with IIS and it turns out I just needed to add the MIME-type to IIS: '.woff2' / 'application/font-woff'

remote rejected master -> master (pre-receive hook declined)

I got the same error when I ran git status :

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
nothing to commit, working directory clean

To fix it I can run:

$ git push and run 
$ git push heroku master

Android: How to create a Dialog without a title?

Set the title to empty string using builder.

    Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("");
...
    builder.show();

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/ directory, or Scripts\ on Windows).

The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.

strdup() - what does it do in C?

The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)

Fetch frame count with ffmpeg

try this:

ffmpeg -i "path to file" -f null /dev/null 2>&1 | grep 'frame=' | cut -f 2 -d ' '

How do I get the file name from a String containing the Absolute file path?

Considering the String you're asking about is

C:\Hello\AnotherFolder\The File Name.PDF

we need to extract everything after the last separator, ie. \. That is what we are interested in.

You can do

String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);

This will retrieve the index of the last \ in your String and extract everything that comes after it into fileName.

If you have a String with a different separator, adjust the lastIndexOf to use that separator. (There's even an overload that accepts an entire String as a separator.)

I've omitted it in the example above, but if you're unsure where the String comes from or what it might contain, you'll want to validate that the lastIndexOf returns a non-negative value because the Javadoc states it'll return

-1 if there is no such occurrence

Import XXX cannot be resolved for Java SE standard classes

This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.

from:

 <configuration>
        <source>1.8</source>
        <target>1.8</target>
</configuration>

to:

 <configuration>
        <source>1.7</source>
        <target>1.7</target>
</configuration>

Screenshot showing problem in JRE: enter image description here

How to execute an oracle stored procedure?

Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...

create or replace procedure temp_proc is
begin
  DBMS_OUTPUT.ENABLE(1000000);
  DBMS_OUTPUT.PUT_LINE('Test');
end;

...and call it in a PLSQL block...

begin
  temp_proc;
end;

...as SQL is non-procedural.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

You have to put your main queue dispatching in the block that runs the computation. For example (here I create a dispatch queue and don't use a global one):

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

Of course, if you create a queue don't forget to dispatch_release if you're targeting an iOS version before 6.0.

How can I initialize a String array with length 0 in Java?

Ok I actually found the answer but thought I would 'import' the question into SO anyway

String[] files = new String[0];
or
int[] files = new int[0];

Passing data between controllers in Angular JS?

An even simpler way to share the data between controllers is using nested data structures. Instead of, for example

$scope.customer = {};

we can use

$scope.data = { customer: {} };

The data property will be inherited from parent scope so we can overwrite its fields, keeping the access from other controllers.

SQL Server : Columns to Rows

Just because I did not see it mentioned.

If 2016+, here is yet another option to dynamically unpivot data without actually using Dynamic SQL.

Example

Declare @YourTable Table ([ID] varchar(50),[Col1] varchar(50),[Col2] varchar(50))
Insert Into @YourTable Values 
 (1,'A','B')
,(2,'R','C')
,(3,'X','D')

Select A.[ID]
      ,Item  = B.[Key]
      ,Value = B.[Value]
 From  @YourTable A
 Cross Apply ( Select * 
                From  OpenJson((Select A.* For JSON Path,Without_Array_Wrapper )) 
                Where [Key] not in ('ID','Other','Columns','ToExclude')
             ) B

Returns

ID  Item    Value
1   Col1    A
1   Col2    B
2   Col1    R
2   Col2    C
3   Col1    X
3   Col2    D

java.io.IOException: Broken pipe

I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080 to forward the appropiate requests to tomcat.

There is a default value for the nginx variable proxy_read_timeout of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.

NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Thanks to Andrey Egorov, in my case with python setAttribute not working, but I found I can set the property directly,

Try this code:

driver.execute_script("document.getElementById('q').value='value here'")

Arrays.fill with multidimensional array in Java

As an extension to the answer, I found this post but was looking to fill a 4 dimensional array. The original example is only a two dimensional array, but the question says "multidimensional". I didn't want to post a new question for this...

You can use the same method, but you have to nest them so that you eventually get to a single dimensional array.

fourDArray = new float[10][10][10][1];
// Fill each row with null
for (float[][][] row: fourDArray)
{
    for (float[][] innerRow: row)
    {
        for (float[] innerInnerRow: innerRow)
        {
        Arrays.fill(innerInnerRow, -1000);
        }
    }
};

Operation must use an updatable query. (Error 3073) Microsoft Access

In essence, while your SQL looks perfectly reasonable, Jet has never supported the SQL standard syntax for UPDATE. Instead, it uses its own proprietary syntax (different again from SQL Server's proprietary UPDATE syntax) which is very limited. Often, the only workarounds "Operation must use an updatable query" are very painful. Seriously consider switching to a more capable SQL product.

For some more details about your specific problems and some possible workarounds, see Update Query Based on Totals Query Fails.

Using Pip to install packages to Anaconda Environment

If you didn't add pip when creating conda environment

conda create -n env_name pip

and also didn't install pip inside the environment

source activate env_name
conda install pip

then the only pip you got is the system pip, which will install packages globally.

Bus as you can see in this issue, even if you did either of the procedure mentioned above, the behavior of pip inside conda environment is still kind of undefined.

To ensure using the pip installed inside conda environment without having to type the lengthy /home/username/anaconda/envs/env_name/bin/pip, I wrote a shell function:

# Using pip to install packages inside conda environments.
cpip() {
    ERROR_MSG="Not in a conda environment."
    ERROR_MSG="$ERROR_MSG\nUse \`source activate ENV\`"
    ERROR_MSG="$ERROR_MSG to enter a conda environment."

    [ -z "$CONDA_DEFAULT_ENV" ] && echo "$ERROR_MSG" && return 1

    ERROR_MSG='Pip not installed in current conda environment.'
    ERROR_MSG="$ERROR_MSG\nUse \`conda install pip\`"
    ERROR_MSG="$ERROR_MSG to install pip in current conda environment."

    [ -e "$CONDA_PREFIX/bin/pip" ] || (echo "$ERROR_MSG" && return 2)

    PIP="$CONDA_PREFIX/bin/pip"
    "$PIP" "$@"
}

Hope this is helpful to you.

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

How to get document height and width without using jquery

How to find out the document width and height very easily?

in HTML
<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>

in javascript

     var c=document.querySelector('#hidden_placer');

     var r=c.getBoundingClientRect();
     r.right=document width
     r.bottom=document height`

You may update this on every window resize event, if needed.

What causes javac to issue the "uses unchecked or unsafe operations" warning

for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.

for a function

List<String> getNames()


List names = obj.getNames();

will generate this error.

To solve it you would just add the parameters

List<String> names = obj.getNames();

Grouping switch statement cases together?

AFAIK all you can do is omit the returns to make things more compact in C++:

switch(Answer)
{
    case 1: case 2: case 3: case 4:
        cout << "You need more cars.";
        break;
    ...
}

(You could remove the other returns as well, of course.)

Looping through all rows in a table column, Excel-VBA

If you know the header name, you can find the column based on that:

Option Explicit

Public Sub changeData()
    Application.ScreenUpdating = False ' faster for modifying values on sheet

    Dim header As String
    Dim numRows As Long
    Dim col As Long
    Dim c As Excel.Range

    header = "this one" ' header name to find

    Set c = ActiveSheet.Range("1:1").Find(header, LookIn:=xlValues)
    If Not c Is Nothing Then
        col = c.Column
    Else
        ' can't work with it
        Exit Sub
    End If

    numRows = 50 ' (whatever this is in your code)

    With ActiveSheet
        .Range(.Cells(2, col), .Cells(numRows, col)).Value = "PHEV"
    End With

    Application.ScreenUpdating = True ' reset
End Sub

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

What is the Oracle equivalent of SQL Server's IsNull() function?

coalesce is supported in both Oracle and SQL Server and serves essentially the same function as nvl and isnull. (There are some important differences, coalesce can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull matches the type of the first argument, that is not true for coalesce, at least on SQL Server.)

Eclipse: How do I add the javax.servlet package to a project?

To expound on darioo's answer with a concrete example. Tomcat 7 installed using homebrew on OS X, using Eclipse:

  1. Right click your project folder, select Properties at the bottom of the context menu.
  2. Select "Java Build Path"
  3. Click Libraries" tab
  4. Click "Add Library..." button on right (about halfway down)
  5. Select "Server Runtime" click "Next"
  6. Select your Tomcat version from the list
  7. Click Finish

What? No Tomcat version is listed even though you have it installed via homebrew??

  1. Switch to the Java EE perspective (top right)
  2. In the "Window" menu select "Show View" -> "Servers"
  3. In the Servers tab (typically at bottom) right click and select "New > Server"
  4. Add the path to the homebrew tomcat installation in the dialog/wizard (something like: /usr/local/Cellar/tomcat/7.0.14/libexec)

Hope that helps someone who is just getting started out a little.

How does the SQL injection from the "Bobby Tables" XKCD comic work?

The ' character in SQL is used for string constants. In this case it is used for ending the string constant and not for comment.

How do I view 'git diff' output with my preferred diff tool/ viewer?

The following can be gleaned from the other answers here, but for me it's difficult, (too much information), so here's the 'just type it in' answer for tkdiff:

git difftool --tool=tkdiff <path to the file to be diffed>

You can substitute the executable name of your favorite diffing tool for tkdiff. As long as (e.g. tkdiff), (or your favorite diffing tool) is in your PATH, it will be launched.

How to split the name string in mysql?

DELIMITER $$

DROP FUNCTION IF EXISTS `split_name`$$

CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
    READS SQL DATA
BEGIN
    DECLARE v_words INT UNSIGNED;
    DECLARE v_name TEXT;

    SET p_fullname=RTRIM(LTRIM(p_fullname));

    SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));

    IF v_words=1 THEN 
        IF p_part=1 THEN
            SET v_name=p_fullname;
        ELSEIF p_part=2 THEN
            SET v_name=NULL;
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=2 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words>3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
            SET v_name=REVERSE(p_fullname);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF;
    ELSE
        SET v_name=NULL;
    END IF;
 RETURN v_name; 
END;

SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

Upgrading pip in windows with -

python -m pip install --upgrade pip

and then running pip install with --user option -

pip install --user package_name

solved my problem.

How to format date in angularjs

If you are not having an input field, rather just want to display a string date with a proper formatting, you can simply go for:

<label ng-bind="formatDate(date) |  date:'MM/dd/yyyy'"></label>

and in the js file use:

    // @Function
    // Description  : Triggered while displaying expiry date
    $scope.formatDate = function(date){
          var dateOut = new Date(date);
          return dateOut;
    };

This will convert the date in string to a new date object in javascript and will display the date in format MM/dd/yyyy.

Output: 12/15/2014

Edit
If you are using a string date of format "2014-12-19 20:00:00" string format (passed from a PHP backend), then you should modify the code to the one in: https://stackoverflow.com/a/27616348/1904479

Adding on further
From javascript you can set the code as:

$scope.eqpCustFields[i].Value = $filter('date')(new Date(dateValue),'yyyy-MM-dd');

that is in case you already have a date with you, else you can use the following code to get the current system date:

$scope.eqpCustFields[i].Value = $filter('date')(new Date(),'yyyy-MM-dd');

For more details on date Formats, refer : https://docs.angularjs.org/api/ng/filter/date

How can I read an input string of unknown length?

There is a new function in C standard for getting a line without specifying its size. getline function allocates string with required size automatically so there is no need to guess about string's size. The following code demonstrate usage:

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    while ((read = getline(&line, &len, stdin)) != -1) {
        printf("Retrieved line of length %zu :\n", read);
        printf("%s", line);
    }

    if (ferror(stdin)) {
        /* handle error */
    }

    free(line);
    return 0;
}

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

Android: Go back to previous activity

@Override
public void onBackPressed() {
    super.onBackPressed();
}

and if you want on button click go back then simply put

bbsubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});

Where can I get Google developer key

Recent Update July 2017:

  1. Go to Google Console
  2. Click on Left most top panel and click credentials. enter image description here
  3. In the API keys table, you will find the API key in the key column.

Format price in the current locale and currency

By this code for formating price in product list

echo Mage::helper('core')->currency($_product->getPrice());

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Is it possible to run one logrotate check manually?

You may want to run it in verbose + force mode.

logrotate -vf /etc/logrotate.conf

Catch Ctrl-C in C

With a signal handler.

Here is a simple example flipping a bool used in main():

#include <signal.h>

static volatile int keepRunning = 1;

void intHandler(int dummy) {
    keepRunning = 0;
}

// ...

int main(void) {

   signal(SIGINT, intHandler);

   while (keepRunning) { 
      // ...

Edit in June 2017: To whom it may concern, particularly those with an insatiable urge to edit this answer. Look, I wrote this answer seven years ago. Yes, language standards change. If you really must better the world, please add your new answer but leave mine as is. As the answer has my name on it, I'd prefer it to contain my words too. Thank you.

Oracle PL/SQL : remove "space characters" from a string

To remove any whitespaces you could use:

myValue := replace(replace(replace(replace(replace(replace(myValue, chr(32)), chr(9)),  chr(10)), chr(11)), chr(12)), chr(13));

Example: remove all whitespaces in a table:

update myTable t
    set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
    length(t.myValue) > length(replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13)));

or

update myTable t
    set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
    t.myValue like '% %'

How to run certain task every day at a particular time using ScheduledExecutorService?

What if your server goes down at 4:59AM and comes back at 5:01AM? I think it will just skip the run. I would recommend persistent scheduler like Quartz, that would store its schedule data somewhere. Then it will see that this run hasn't been performed yet and will do it at 5:01AM.

Using Selenium Web Driver to retrieve value of a HTML input

With selenium 2,

i usually write it like that :

WebElement element = driver.findElement(By.id("input_name"));
String elementval = element.getAttribute("value");

OR

String elementval = driver.findElement(By.id("input_name")).getAttribute("value");

How to update a menu item shown in the ActionBar?

Option #1: Try invalidateOptionsMenu(). I don't know if this will force an immediate redraw of the action bar or not.

Option #2: See if getActionView() returns anything for the affected MenuItem. It is possible that showAsAction simply automatically creates action views for you. If so, you can presumably enable/disable that View.

I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.

You can hang onto the Menu object you were handed in onCreateOptionsMenu(). Quoting the docs:

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

Change Text Color of Selected Option in a Select Box

You could do it like this.

jsFiddle

JS

var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}

CSS

.redText {
    background-color:#F00;
}
.greenText {
    background-color:#0F0;
}
.blueText {
    background-color:#00F;
}

You could use option { background-color: #FFF; } if you want the list to be white.

HTML

<select id="mySelect" class="greenText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

Since this is a select it doesn't really make sense to use .yellowText as none selected if that's what you were getting at as something must be selected.

How to build a JSON array from mysql database

The PDO solution, just for a better implementation then mysql_*:

$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url 
  FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);

Nice feature is also that it will leave integers as integers as opposed to strings.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

If your arrays aren't too big or you don't have too many of them, you might be able to get away with forcing the left hand side of == to be a string:

myRows = df[str(df['Unnamed: 5']) == 'Peter'].index.tolist()

But this is ~1.5 times slower if df['Unnamed: 5'] is a string, 25-30 times slower if df['Unnamed: 5'] is a small numpy array (length = 10), and 150-160 times slower if it's a numpy array with length 100 (times averaged over 500 trials).

a = linspace(0, 5, 10)
b = linspace(0, 50, 100)
n = 500
string1 = 'Peter'
string2 = 'blargh'
times_a = zeros(n)
times_str_a = zeros(n)
times_s = zeros(n)
times_str_s = zeros(n)
times_b = zeros(n)
times_str_b = zeros(n)
for i in range(n):
    t0 = time.time()
    tmp1 = a == string1
    t1 = time.time()
    tmp2 = str(a) == string1
    t2 = time.time()
    tmp3 = string2 == string1
    t3 = time.time()
    tmp4 = str(string2) == string1
    t4 = time.time()
    tmp5 = b == string1
    t5 = time.time()
    tmp6 = str(b) == string1
    t6 = time.time()
    times_a[i] = t1 - t0
    times_str_a[i] = t2 - t1
    times_s[i] = t3 - t2
    times_str_s[i] = t4 - t3
    times_b[i] = t5 - t4
    times_str_b[i] = t6 - t5
print('Small array:')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_a), mean(times_str_a)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_a)/mean(times_a)))

print('\nBig array')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_b), mean(times_str_b)))
print(mean(times_str_b)/mean(times_b))

print('\nString')
print('Time to compare without str conversion: {} s. With str conversion: {} s'.format(mean(times_s), mean(times_str_s)))
print('Ratio of time with/without string conversion: {}'.format(mean(times_str_s)/mean(times_s)))

Result:

Small array:
Time to compare without str conversion: 6.58464431763e-06 s. With str conversion: 0.000173756599426 s
Ratio of time with/without string conversion: 26.3881526541

Big array
Time to compare without str conversion: 5.44309616089e-06 s. With str conversion: 0.000870866775513 s
159.99474375821288

String
Time to compare without str conversion: 5.89370727539e-07 s. With str conversion: 8.30173492432e-07 s
Ratio of time with/without string conversion: 1.40857605178

remove first element from array and return the array minus the first element

Try this

    var myarray = ["item 1", "item 2", "item 3", "item 4"];

    //removes the first element of the array, and returns that element apart from item 1.
    myarray.shift(); 
    console.log(myarray); 

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

How to center canvas in html5

Just center the div in HTML:

  #test {
     width: 100px;
     height:100px;
     margin: 0px auto;
     border: 1px solid red;
   }


<div id="test">
   <canvas width="100" height="100"></canvas>
</div>

Just change the height and width to whatever and you've got a centered div

http://jsfiddle.net/BVghc/2/

Entity Framework Refresh context?

context.Reload() was not working for me in MVC 4, EF 5 so I did this.

context.Entry(entity).State = EntityState.Detached;
entity = context.Find(entity.ID);

and its working fine.

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

How to retrieve the hash for the current commit in Git?

For completeness, since no-one has suggested it yet. .git/refs/heads/master is a file that contains only one line: the hash of the latest commit on master. So you could just read it from there.

Or, as as command:

cat .git/refs/heads/master

Update:

Note that git now supports storing some head refs in the pack-ref file instead of as a file in the /refs/heads/ folder. https://www.kernel.org/pub/software/scm/git/docs/git-pack-refs.html

How do I terminate a thread in C++11?

I guess the thread that needs to be killed is either in any kind of waiting mode, or doing some heavy job. I would suggest using a "naive" way.

Define some global boolean:

std::atomic_bool stop_thread_1 = false;

Put the following code (or similar) in several key points, in a way that it will cause all functions in the call stack to return until the thread naturally ends:

if (stop_thread_1)
    return;

Then to stop the thread from another (main) thread:

stop_thread_1 = true;
thread1.join ();
stop_thread_1 = false; //(for next time. this can be when starting the thread instead)

How do I override nested NPM dependency versions?

The only solution that worked for me (node 12.x, npm 6.x) was using npm-force-resolutions developed by @Rogerio Chaves.

First, install it by:

npm install npm-force-resolutions --save-dev

You can add --ignore-scripts if some broken transitive dependency scripts are blocking you from installing anything.

Then in package.json define what dependency should be overridden (you must set exact version number):

"resolutions": {
  "your-dependency-name": "1.23.4"
}

and in "scripts" section add new preinstall entry:

"preinstall": "npx npm-force-resolutions",

Now, npm install will apply changes and force your-dependency-name to be at version 1.23.4 for all dependencies.

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

yourimg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}

and make sure there is no parent tags with position: relative in it

Hide scroll bar, but while still being able to scroll

Another sort of hacky approach is to do overflow-y: hidden and then manually scroll the element with something like this:

function detectMouseWheelDirection(e) {
  var delta = null, direction = false;
  if (!e) { // If the event is not provided, we get it from the window object
    e = window.event;
  }
  if (e.wheelDelta) { // Will work in most cases
    delta = e.wheelDelta / 60;
  } else if (e.detail) { // Fallback for Firefox
    delta = -e.detail / 2;
  }
  if (delta !== null) {
    direction = delta > 0 ? -200 : 200;
  }
  return direction;
}

if (element.addEventListener) {
  element.addEventListener('DOMMouseScroll', function(e) {
    element.scrollBy({
      top: detectMouseWheelDirection(e),
      left: 0,
      behavior: 'smooth'
    });
  });
}

There's a great article about how to detect and deal with onmousewheel events in deepmikoto's blog. This might work for you, but it is definitively not an elegant solution.

Find the line number where a specific word appears with "grep"

Use grep -n to get the line number of a match.

I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:

sed -n '10,$ { /regex/ { =; p; } }' file

To get only the line numbers, you could use

grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'

Or you could simply use sed:

sed -n '/regex/=' file

Combining the two sed commands, you get:

sed -n '10,$ { /regex/= }' file

Update select2 data without rebuilding the control

select2 v3.x

If you have local array with options (received by ajax call), i think you should use data parameter as function returning results for select box:

var pills = [{id:0, text: "red"}, {id:1, text: "blue"}]; 

$('#selectpill').select2({
    placeholder: "Select a pill",
    data: function() { return {results: pills}; }
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
});
$('#newresults').click(function() {
    pills = [{id:0, text: "white"}, {id:1, text: "black"}];
});

FIDDLE: http://jsfiddle.net/RVnfn/576/

In case if you customize select2 interface with buttons, just call updateResults (this method not allowed to call from outsite of select2 object but you can add it to allowedMethods array in select2 if you need to) method after updateting data array(pills in example).


select2 v4: custom data adapter

Custom data adapter with additional updateOptions (its unclear why original ArrayAdapter lacks this functionality) method can be used to dynamically update options list (all options in this example):

$.fn.select2.amd.define('select2/data/customAdapter',
    ['select2/data/array', 'select2/utils'],
    function (ArrayAdapter, Utils) {
        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);
        CustomDataAdapter.prototype.updateOptions = function (data) {
            this.$element.find('option').remove(); // remove all options
            this.addOptions(this.convertToOptions(data));
        }        
        return CustomDataAdapter;
    }
);

var customAdapter = $.fn.select2.amd.require('select2/data/customAdapter');

var sel = $('select').select2({
    dataAdapter: customAdapter,
    data: pills
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
    sel.data('select2').dataAdapter.updateOptions(pills);
});

FIDDLE: https://jsfiddle.net/xu48n36c/1/


select2 v4: ajax transport function

in v4 you can define custom transport method that can work with local data array (thx @Caleb_Kiage for example, i've played with it without succes)

docs: https://select2.github.io/options.html#can-an-ajax-plugin-other-than-jqueryajax-be-used

Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.

$('select').select2({
    ajax: {
        transport: function(params, success, failure) {
            var items = pills;
            // fitering if params.data.q available
            if (params.data && params.data.q) {
                items = items.filter(function(item) {
                    return new RegExp(params.data.q).test(item.text);
                });
            }
            var promise = new Promise(function(resolve, reject) {
                resolve({results: items});
            });
            promise.then(success);
            promise.catch(failure);
        }
    }
});

BUT with this method you need to change ids of options if text of option in array changes - internal select2 dom option element list did not modified. If id of option in array stay same - previous saved option will be displayed instead of updated from array! That is not problem if array modified only by adding new items to it - ok for most common cases.

FIDDLE: https://jsfiddle.net/xu48n36c/3/

how to fire event on file select

This is an older question that needs a newer answer that will address @Christopher Thomas's concern above in the accept answer's comments. If you don't navigate away from the page and then select the file a second time, you need to clear the value when you click or do a touchstart(for mobile). The below will work even when you navigate away from the page and uses jquery:

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page 
and choosing to upload the same file */ 

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});

Shell script to check if file exists

The following script will help u to go to a process if that script exist in a specified variable,

cat > waitfor.csh

    #!/bin/csh

    while !( -e $1 )

    sleep 10m

    end

ctrl+D

here -e is for working with files,

$1 is a shell variable,

sleep for 10 minutes

u can execute the script by ./waitfor.csh ./temp ; echo "the file exits"

List of Java class file format major version numbers?

These come from the class version. If you try to load something compiled for java 6 in a java 5 runtime you'll get the error, incompatible class version, got 50, expected 49. Or something like that.

See here in byte offset 7 for more info.

Additional info can also be found here.

How to add the text "ON" and "OFF" to toggle button

    .switch
    {
            width: 50px;
            height: 30px;
            position: relative;
            display:inline-block;
    }

    .switch input
    {
            display: none;
    }

    .slider
    {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
            cursor: pointer;
            background-color: gray;
            border-radius: 30px;

    }
    .slider:before
    {

        position: absolute;
        background-color: #fff;
        height: 20px;
        width: 20px;
        content: "";
        left: 5px;
        bottom: 5px;
        border-radius: 50%;
        transition: ease-in-out .5s;
    }

    .slider:after
    {
        content: "Off";

        color: white;
        display: block;
        position: absolute;
        transform: translate(-50%,-50%);
        top: 50%;
        left: 70%;
        transition: all .5s;
        font-size: 10px;
        font-family: Verdana,sans-serif;
    }

    input:checked + .slider:after
    {
        transition: all .5s;
        left: 30%;
        content: "On"

    }
    input:checked + .slider
    {
        background-color: blue;

    }

    input:checked + .slider:before
    {
        transform: translateX(20px);
    }



    **The HTML CODE**

    <label class="switch">

                <input type="checkbox"/>

                 <div class="slider">

                </div>
        </label>


If You want to add long text like activate or Deactivate

just make few changes 

.switch
{
        width:90px
}
.slider:after
{
     left: 60%; //as you want in percenatge
}
input:checked + .slider:after
{
       left:40%; //exactly opposite of .slider:after 
}

and last

input:checked + .slider:before
{
    transform: translateX(60px); //as per your choice but 60px is perfect
}

content as per your choice where you have witten "On" and "Off"

JavaScript is in array

IMHO most compatible with older browsers

Array.prototype.inArray = function( needle ){

    return Array(this).join(",").indexOf(needle) >-1;

}

var foods = ["Cheese","Onion","Pickle","Ham"];
test = foods.inArray("Lemon");
console.log( "Lemon is " + (test ? "" : "not ") + "in the list." );

By turning an Array copy in to a CSV string, you can test the string in older browsers.

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just add Attribute routing if it is not present in appconfig or webconfig

config.MapHttpAttributeRoutes()

Using Laravel Homestead: 'no input file specified'

Restart your homestead. Worked for me.

homestead destroy
homestead up

How to make connection to Postgres via Node.js

Slonik is an alternative to answers proposed by Kuberchaun and Vitaly.

Slonik implements safe connection handling; you create a connection pool and connection opening/handling is handled for you.

import {
  createPool,
  sql
} from 'slonik';

const pool = createPool('postgres://user:password@host:port/database');

return pool.connect((connection) => {
  // You are now connected to the database.
  return connection.query(sql`SELECT foo()`);
})
  .then(() => {
    // You are no longer connected to the database.
  });

postgres://user:password@host:port/database is your connection string (or more canonically a connection URI or DSN).

The benefit of this approach is that your script ensures that you never accidentally leave hanging connections.

Other benefits for using Slonik include:

Indent multiple lines quickly in vi

To indent every line in a file type, Esc and then G=gg.

Is there a vr (vertical rule) in html?

Try this.

You can set height and width on "div", like the scope for "hr".

The margin of "hr" is used to alignment.

_x000D_
_x000D_
<div style="display: inline-flex; width: 25px; height: 100px;">_x000D_
  <hr style="margin: 0px 0px 0px 12.5px;">_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP AES encrypt / decrypt

Please use an existing secure PHP encryption library

It's generally a bad idea to write your own cryptography unless you have experience breaking other peoples' cryptography implementations.

None of the examples here authenticate the ciphertext, which leaves them vulnerable to bit-rewriting attacks.

If you can install PECL extensions, libsodium is even better

<?php
// PECL libsodium 0.2.1 and newer

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = \Sodium\randombytes_buf(
        \Sodium\CRYPTO_SECRETBOX_NONCEBYTES
    );

    return base64_encode(
        $nonce.
        \Sodium\crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 */
function safeDecrypt($encrypted, $key)
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    return \Sodium\crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
}    

Then to test it out:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = \Sodium\randombytes_buf(\Sodium\CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

This can be used in any situation where you are passing data to the client (e.g. encrypted cookies for sessions without server-side storage, encrypted URL parameters, etc.) with a reasonably high degree of certainty that the end user cannot decipher or reliably tamper with it.

Since libsodium is cross-platform, this also makes it easier to communicate with PHP from, e.g. Java applets or native mobile apps.


Note: If you specifically need to add encrypted cookies powered by libsodium to your app, my employer Paragon Initiative Enterprises is developing a library called Halite that does all of this for you.

What function is to replace a substring from a string in C?

As strings in C can not dynamically grow inplace substitution will generally not work. Therefore you need to allocate space for a new string that has enough room for your substitution and then copy the parts from the original plus the substitution into the new string. To copy the parts you would use strncpy.

Why does JSHint throw a warning if I am using const?

If you are using Grunt configuration, You need to do the following steps

Warning message in Jshint:

enter image description here

Solution:

  1. Set the jshint options and map the .jshintrc.js file

enter image description here

  1. Create the .jshintrc.js file in that file add the following code
{  
  "esversion": 6  
} 

After configured this, Run again It will skip the warning,

enter image description here

How to make a back-to-top button using CSS and HTML only?

<a id="topbutton" href="#top">first page </a>

Basically what you have to do is replace the " #top" with the id of the first section or your page, or it could be the nav... Any id locate in the first part of the page and then try to set some style with css!

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

I know this is late to the game, but I wanted to share in case it helps someone.

Your exact situation may not apply, however I had a similar situation and setting the File attribute helped.

Try to set the File attribute to Normal:

var path = Server.MapPath("~/App_Data/file.txt");
File.SetAttributes(path, FileAttributes.Normal);
System.IO.File.WriteAllText(path, "Hello World");

I hope this helps someone.

Show default value in Spinner in android

Try below:

   <Spinner
    android:id="@+id/YourSpinnerId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:prompt="Gender" />

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):

C:\xampp\php\PEAR\initcontrols\header_myworks.php

providing the path you pasted in the subject is correct. Make sure your file is located there.

For more info you can get and set the include path programmatically.

How to run a makefile in Windows?

If you have Visual Studio, run the Visual Studio Command prompt from the Start menu, change to the directory containing Makefile.win and type this:

nmake -f Makefile.win

You can also use the normal command prompt and run vsvars32.bat (c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools for VS2008). This will set up the environment to run nmake and find the compiler tools.

MySQL Select Date Equal to Today

You can use the CONCAT with CURDATE() to the entire time of the day and then filter by using the BETWEEN in WHERE condition:

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
FROM users 
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

My issue was solved when I converted in IIS the physical folder that was containing the files to an application. Right click > convert to application.

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

How to list the certificates stored in a PKCS12 keystore with keytool?

You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.

keytool -list -v -keystore cert.p12 -storepass <password>

 Keystore type: PKCS12
 Keystore provider: SunJSSE

 Your keystore contains 1 entry
 Alias name: 1
 Creation date: Jul 11, 2020
 Entry type: PrivateKeyEntry
 Certificate chain length: 2

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

Bulk Insert Correctly Quoted CSV File in SQL Server

I know this is an old topic but this feature has now been implemented since SQL Server 2017. The parameter you're looking for is FIELDQUOTE= which defaults to '"'. See more on https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017

OSError - Errno 13 Permission denied

Another option is to ensure the file is not open anywhere else on your machine.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Switch statement fallthrough in C#?

The "why" is to avoid accidental fall-through, for which I'm grateful. This is a not uncommon source of bugs in C and Java.

The workaround is to use goto, e.g.

switch (number.ToString().Length)
{
    case 3:
        ans += string.Format("{0} hundred and ", numbers[number / 100]);
        goto case 2;
    case 2:
    // Etc
}

The general design of switch/case is a little bit unfortunate in my view. It stuck too close to C - there are some useful changes which could be made in terms of scoping etc. Arguably a smarter switch which could do pattern matching etc would be helpful, but that's really changing from switch to "check a sequence of conditions" - at which point a different name would perhaps be called for.

"cannot be used as a function error"

This line is the problem:

int estimatedPopulation (int currentPopulation,
                         float growthRate (birthRate, deathRate))

Make it:

int estimatedPopulation (int currentPopulation, float birthRate, float deathRate)

instead and invoke the function with three arguments like

estimatePopulation( currentPopulation, birthRate, deathRate );

OR declare it with two arguments like:

int estimatedPopulation (int currentPopulation, float growthrt ) { ... }

and call it as

estimatedPopulation( currentPopulation, growthRate (birthRate, deathRate));

Edit:

Probably more important here - C++ (and C) names have scope. You can have two things named the same but not at the same time. In your particular case your grouthRate variable in the main() hides the function with the same name. So within main() you can only access grouthRate as float. On the other hand, outside of the main() you can only access that name as a function, since that automatic variable is only visible within the scope of main().

Just hope I didn't confuse you further :)

Make .gitignore ignore everything except a few files

This is how I did it:

# Ignore everything
*

# Whitelist anything that's a directory
!*/

# Whitelist some files
!.gitignore

# Whitelist this folder and everything inside of it
!wordpress/wp-content/themes/my-theme/**

# Ignore this folder inside that folder
wordpress/wp-content/themes/my-theme/node_modules

# Ignore this file recursively
**/.DS_Store

Use gig status -u to view individual files in untracked directories recursively - with git status you'd only see folders, which could fool you into thinking that everything inside them was tracked

Passing data between view controllers

Use notification center to pass data from one view to another.

The observer listener pattern works the best. The other workaround can be create the same objects in both classes.

Create a class 2 object in class one. Access the data objects to be passed, set them, and then push the view controller.

How can I read the client's machine/computer name from the browser?

Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?

Page.Request.UserHostName

HttpRequest.UserHostName

The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...

Is there a link to the "latest" jQuery library on Google APIs?

No. There isn't..

But, for development there is such a link on the jQuery code site.

SQL ROWNUM how to return rows between a specific range

SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNum, * FROM maps006) AS DerivedTable
WHERE RowNum BETWEEN 49 AND 101

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I created a possibly faster implementation by using 0-1 range for RGBS and V and 0-6 range for Hue (avoiding the division), and grouping the cases into two categories:

#include <math.h>
#include <float.h>

void fromRGBtoHSV(float rgb[], float hsv[])
{
//    for(int i=0; i<3; ++i)
//        rgb[i] = max(0.0f, min(1.0f, rgb[i]));

     hsv[0] = 0.0f;
     hsv[2] = max(rgb[0], max(rgb[1], rgb[2]));
     const float delta = hsv[2] - min(rgb[0], min(rgb[1], rgb[2]));

     if (delta < FLT_MIN)
         hsv[1] = 0.0f;
     else
     {
         hsv[1] = delta / hsv[2];
         if (rgb[0] >= hsv[2])
         {
             hsv[0] = (rgb[1] - rgb[2]) / delta;
             if (hsv[0] < 0.0f)
                 hsv[0] += 6.0f;
         }
         else if (rgb[1] >= hsv[2])
             hsv[0] = 2.0f + (rgb[2] - rgb[0]) / delta;
         else
             hsv[0] = 4.0f + (rgb[0] - rgb[1]) / delta;
     }    
}

void fromHSVtoRGB(const float hsv[], float rgb[])
{
    if(hsv[1] < FLT_MIN)
        rgb[0] = rgb[1] = rgb[2] = hsv[2];
    else
    {
        const float h = hsv[0];
        const int i = (int)h;
        const float f = h - i;
        const float p = hsv[2] * (1.0f - hsv[1]);

        if (i & 1) {
            const float q = hsv[2] * (1.0f - (hsv[1] * f));
            switch(i) {
            case 1:
                rgb[0] = q;
                rgb[1] = hsv[2];
                rgb[2] = p;
                break;
            case 3:
                rgb[0] = p;
                rgb[1] = q;
                rgb[2] = hsv[2];
                break;
            default:
                rgb[0] = hsv[2];
                rgb[1] = p;
                rgb[2] = q;
                break;
            }
        }
        else
        {
            const float t = hsv[2] * (1.0f - (hsv[1] * (1.0f - f)));
            switch(i) {
            case 0:
                rgb[0] = hsv[2];
                rgb[1] = t;
                rgb[2] = p;
                break;
            case 2:
                rgb[0] = p;
                rgb[1] = hsv[2];
                rgb[2] = t;
                break;
            default:
                rgb[0] = t;
                rgb[1] = p;
                rgb[2] = hsv[2];
                break;
            }
        }
    }
}

For 0-255 range just * 255.0f + 0.5f and assign it to an unsigned char (or divide by 255.0 to get the opposite).

Changing datagridview cell color based on condition

Without looping it can be achived like below.

private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {

        FormatRow(dgEvents.Rows[e.RowIndex]);

    }

private void FormatRow(DataGridViewRow myrow)
    {
        try
        {
            if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
            {
                myrow.DefaultCellStyle.BackColor = Color.Red;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
            {
                myrow.DefaultCellStyle.BackColor = Color.Yellow;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
            {
                myrow.DefaultCellStyle.BackColor = Color.LightGreen;
            }
        }
        catch (Exception exception)
        {
            onLogs?.Invoke(exception.Message, EventArgs.Empty);
        }
    }

How to read/write arbitrary bits in C/C++

You need to shift and mask the value, so for example...

If you want to read the first two bits, you just need to mask them off like so:

int value = input & 0x3;

If you want to offset it you need to shift right N bits and then mask off the bits you want:

int value = (intput >> 1) & 0x3;

To read three bits like you asked in your question.

int value = (input >> 1) & 0x7;

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

Doesn't look like you got an answer but this problem can also creep up if you're passing null ID's into your JPA Predicate.

For instance.

If I did a query on Cats to get back a list. Which returns 3 results.

List catList;

I then iterate over that List of cats and store a foriegn key of cat perhaps leashTypeId in another list.

List<Integer> leashTypeIds= new ArrayList<>();

for(Cats c : catList){
    leashTypeIds.add(c.getLeashTypeId);
}

jpaController().findLeashes(leashTypeIds);

If any of the Cats in catList have a null leashTypeId it will throw this error when you try to query your DB.

(Just realized I am posting on a 5 year old thread, perhaps someone will find this useful)

Is calling destructor manually always a sign of bad design?

No, Depends on the situation, sometimes it is legitimate and good design.

To understand why and when you need to call destructors explicitly, let's look at what happening with "new" and "delete".

To created an object dynamically, T* t = new T; under the hood: 1. sizeof(T) memory is allocated. 2. T's constructor is called to initialize the allocated memory. The operator new does two things: allocation and initialization.

To destroy the object delete t; under the hood: 1. T's destructor is called. 2. memory allocated for that object is released. the operator delete also does two things: destruction and deallocation.

One writes the constructor to do initialization, and destructor to do destruction. When you explicitly call the destructor, only the destruction is done, but not the deallocation.

A legitimate use of explicitly calling destructor, therefore, could be, "I only want to destruct the object, but I don't (or can't) release the memory allocation (yet)."

A common example of this, is pre-allocating memory for a pool of certain objects which otherwise have to be allocated dynamically.

When creating a new object, you get the chunk of memory from the pre-allocated pool and do a "placement new". After done with the object, you may want to explicitly call the destructor to finish the cleanup work, if any. But you won't actually deallocate the memory, as the operator delete would have done. Instead, you return the chunk to the pool for reuse.

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

Query grants for a table in postgres

This query will list all of the tables in all of the databases and schemas (uncomment the line(s) in the WHERE clause to filter for specific databases, schemas, or tables), with the privileges shown in order so that it's easy to see if a specific privilege is granted or not:

SELECT grantee
      ,table_catalog
      ,table_schema
      ,table_name
      ,string_agg(privilege_type, ', ' ORDER BY privilege_type) AS privileges
FROM information_schema.role_table_grants 
WHERE grantee != 'postgres' 
--  and table_catalog = 'somedatabase' /* uncomment line to filter database */
--  and table_schema  = 'someschema'   /* uncomment line to filter schema  */
--  and table_name    = 'sometable'    /* uncomment line to filter table  */
GROUP BY 1, 2, 3, 4;

Sample output:

grantee |table_catalog   |table_schema  |table_name     |privileges     |
--------|----------------|--------------|---------------|---------------|
PUBLIC  |adventure_works |pg_catalog    |pg_sequence    |SELECT         |
PUBLIC  |adventure_works |pg_catalog    |pg_sequences   |SELECT         |
PUBLIC  |adventure_works |pg_catalog    |pg_settings    |SELECT, UPDATE |
...

Code coverage with Mocha

Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.

Setup

First, install it in your project with

npm i nyc --save-dev

Then, if you have a npm based project, just change the test script inside the scripts object of your package.json file to execute code coverage of your mocha tests:

{
  "scripts": {
    "test": "nyc --reporter=text mocha"
  }
}

Run

Now run your tests

npm test

and you will see a table like this in your console, just after your tests output:

Istanbul Nyc Mocha code coverage

Customization

Html report

Just use

nyc --reporter=html

instead of text. Now it will produce a report inside ./coverage/index.html.

Report formats

Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you. Just add a --reporter=REPORTER_NAME option for each format you want. For example, with

nyc --reporter=html --reporter=text

you will have both the console and the html report.

Don't run coverage with npm test

Just add another script in your package.json and leave the test script with only your test runner (e.g. mocha):

{
  "scripts": {
    "test": "mocha",
    "test-with-coverage": "nyc --reporter=text mocha"
  }
}

Now run this custom script

npm run test-with-coverage

to run tests with code coverage.

Force test failing if code coverage is low

Fail if the total code coverage is below 90%:

nyc --check-coverage --lines 90 

Fail if the code coverage of at least one file is below 90%:

nyc --check-coverage --lines 90 --per-file

How to fix a header on scroll

The chosen solution did not fit well in my page. So this is a more advanced version that works with bootstrap.

The javascript

var stickyOffset = $('.sticky-header').offset().top;

$(window).scroll(function () {
    var sticky = $('.sticky-header'),
        scroll = $(window).scrollTop(),
        header = $('.fixed-header-background');
    sticky.each(function() {
        var left = $(this).offset().left;
        $(this).data('left', left);//I store the left offset
    });

    if (scroll >= stickyOffset) {
        sticky.addClass('fixed');
        header.css('display', 'block');
        sticky.each(function() {
            $(this).css('left', $(this).data('left'));//I set the left offset
        });
    } else {
        sticky.removeClass('fixed');
        header.css('display', 'none');
        sticky.each(function () {
            $(this).css('left', '');//I remove the left offset
        });
    }
});

The CSS

.fixed-header-background {
    display: none;
     position: fixed;
    top: 50px;
    width: 100%;
    height: 30px;
    background-color: #fff;
    z-index: 5;
    border-bottom-style: solid;
    border-bottom-color: #dedede;
    border-bottom-width: 2px;
}

.fixed{
     position: fixed;
    top: 52px;
    z-index: 6;
}

And the HTML

    <div class="fixed-header-background"></div>
<table class="table table-hover table-condensed">
        <thead>
            <tr>
                <th></th>
                <th><span class="sticky-header">My header 1</span></th>
                <th><span class="sticky-header">My header 2</span></th>
            </tr>
        </thead>
        <tbody>
[....]

        </tbody>
    </table>

Convert or extract TTC font to TTF - how to?

This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack

The resulting TTFs work fine in Windows 7.

Cutting the videos based on start and end time using ffmpeg

Here's what I use and will only take a few seconds to run:

ffmpeg -i input.mp4 -ss 01:19:27 -to 02:18:51 -c:v copy -c:a copy output.mp4

Reference: https://www.arj.no/2018/05/18/trimvideo


Generated mp4 files could also be used in iMovie. More info related to get the full duration using get_duration(input_video) modele.


If you want to concatenate multiple cut scenes you can use following Python script:

#!/usr/bin/env python3

import subprocess


def get_duration(input_video):
    cmd = ["ffprobe", "-i", input_video, "-show_entries", "format=duration",
           "-v", "quiet", "-sexagesimal", "-of", "csv=p=0"]
    return subprocess.check_output(cmd).decode("utf-8").strip()


if __name__ == "__main__":
    name = "input.mkv"

    times = []
    times.append(["00:00:00", "00:00:10"])
    times.append(["00:06:00", "00:07:00"])

    # times = [["00:00:00", get_duration(name)]]

    if len(times) == 1:
        time = times[0]
        cmd = ["ffmpeg", "-i", name, "-ss", time[0], "-to", time[1], "-c:v", "copy", "-c:a", "copy", "output.mp4"]
        subprocess.check_output(cmd)
    else:
        open('concatenate.txt', 'w').close()
        for idx, time in enumerate(times):
            output_filename = f"output{idx}.mp4"
            cmd = ["ffmpeg", "-i", name, "-ss", time[0], "-to", time[1], "-c:v", "copy", "-c:a", "copy", output_filename]
            subprocess.check_output(cmd)

            with open("concatenate.txt", "a") as myfile:
                myfile.write(f"file {output_filename}\n")

        cmd = ["ffmpeg", "-f", "concat", "-i", "concatenate.txt", "-c", "copy", "output.mp4"]
        output = subprocess.check_output(cmd).decode("utf-8").strip()

Example script will cut and merge scenes in between 00:00:00 - 00:00:10 and 00:06:00 - 00:07:00.


If you want to cut the complete video (in case if you want to convert mkv format into mp4) just uncomment the following line:

# times = [["00:00:00", get_duration(name)]]

Root password inside a Docker container

You can log into the Docker container using the root user (ID = 0) instead of the provided default user when you use the -u option. E.g.

docker exec -u 0 -it mycontainer bash

root (id = 0) is the default user within a container. The image developer can create additional users. Those users are accessible by name. When passing a numeric ID, the user does not have to exist in the container.

from Docker documentation

Update: Of course you can also use the Docker management command for containers to run this:

docker container exec -u 0 -it mycontainer bash

How to filter Android logcat by application?

Yes now you will get it automatically....
Update to AVD 14, where the logcat will automatic session filter
where it filter log in you specific app (package)

Html.Textbox VS Html.TextboxFor

The TextBoxFor is a newer MVC input extension introduced in MVC2.

The main benefit of the newer strongly typed extensions is to show any errors / warnings at compile-time rather than runtime.

See this page.

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

The Role Manager feature has not been enabled

If you got here because you're using the new ASP.NET Identity UserManager, what you're actually looking for is the RoleManager:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

roleManager will give you access to see if the role exists, create, etc, plus it is created for the UserManager

Iterating through a string word by word

for word in string.split():
    print word

Error "initializer element is not constant" when trying to initialize variable with const

Just for illustration by compare and contrast The code is from http://www.geeksforgeeks.org/g-fact-80/ /The code fails in gcc and passes in g++/

#include<stdio.h>
int initializer(void)
{
    return 50;
}

int main()
{
    int j;
    for (j=0;j<10;j++)
    {
        static int i = initializer();
        /*The variable i is only initialized to one*/
        printf(" value of i = %d ", i);
        i++;
    }
    return 0;
}

setTimeout / clearTimeout problems

A way to use this in react:

class Timeout extends Component {
  constructor(props){
    super(props)

    this.state = {
      timeout: null
    }

  }

  userTimeout(){
    const { timeout } = this.state;
    clearTimeout(timeout);
    this.setState({
      timeout: setTimeout(() => {this.callAPI()}, 250)
    })

  }
}

Helpful if you'd like to only call an API after the user has stopped typing for instance. The userTimeout function could be bound via onKeyUp to an input.

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

A common practice is to put a @Transactional above your service class.

@Service
@Transactional
public class MyServiceImpl implements MyService{
...
}

How to link to a named anchor in Multimarkdown?

In mdcharm it is like this:

* [Descripción](#descripcion)
* [Funcionamiento](#funcionamiento)
* [Instalación](#instalacion)
* [Configuración](#configuracion)

### Descripción {#descripcion}
### Funcionamiento {#funcionamiento}
### Instalación {#instalacion}
### Configuración {#configuracion}

Default settings Raspberry Pi /etc/network/interfaces

These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:

auto lo

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Truncate a SQLite table if it exists?

I got it to work with:

SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, null, null);

python dictionary sorting in descending order based on values

A short example to sort dictionary is desending order for Python3.

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print(r, a1[r])

Following will be the output

e 30
b 13
d 4
c 2
a 1

IIS 7, HttpHandler and HTTP Error 500.21

One solution that I've found is that you should have to change the .Net Framework back to v2.0 by Right Clicking on the site that you have manager under the Application Pools from the Advance Settings.

Try reinstalling `node-sass` on node 0.12?

My issue was that I was on a machine with node version 0.12.2, but that had an old 1.x.x version of npm. Be sure to update your version of npm: sudo npm install -g npm Once that is done, remove any existing node-sass and reinstall it via npm.

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)

As here str(u'\u2013') is causing error so use isinstance(foo,basestring) to check for unicode/string, if not of type base string convert it into Unicode and then apply encode

if isinstance(foo,basestring):
    foo.encode('utf8')
else:
    unicode(foo).encode('utf8')

further read

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

How to create Toast in Flutter?

Import the lib

fluttertoast: 3.1.3

Use like below

Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,

);

@UniqueConstraint annotation in Java

You can use at class level with following syntax

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"username"})})
public class SomeEntity {
    @Column(name = "username")
    public String username;
}

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

What is the difference between primary, unique and foreign key constraints, and indexes?

  1. A primary key is a column or a set of columns that uniquely identify a row in a table. A primary key should be short, stable and simple. A foreign key is a column (or set of columns) in a second table whose value is required to match the value of the primary key in the original table. Usually a foreign key is in a table that is different from the table whose primary key is required to match. A table can have multiple foreign keys.
  2. The primary key cannot accept null values. Foreign keys can accept multiple.
  3. We can have only one primary key in a table. We can have more than one foreign key in a table.
  4. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. Foreign keys do not automatically create an index, clustered or non-clustered. You can manually create an index on a foreign key.

Composer: The requested PHP extension ext-intl * is missing from your system

Just uncomment this line (to find it, simply search this line in editor):

;extension=php_sockets.dll

(Remove semicolon to uncomment)

For me, no need to restart XAMPP (in your case, WAMP). But if didn't work, restart it.

Android RelativeLayout programmatically Set "centerInParent"

Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:

    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();

    if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
        // if true center text:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.txtGuestName.setLayoutParams(layoutParams);
    } else {
        // if false remove center:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        holder.txtGuestName.setLayoutParams(layoutParams);
    }

How to override !important?

I would like to add an answer to this that hasn't been mentioned, as I have tried all of the above to no avail. My specific situation is that I am using semantic-ui, which has built in !important attributes on elements (extremely annoying). I tried everything to override it, only in the end did one thing work (using jquery). It is as follows:

$('.active').css('cssText', 'border-radius: 0px !important');

force line break in html table cell

You could put the text into a div (or other container) with a width of 50%.

http://jsfiddle.net/6gjsd/

How to remove a TFS Workspace Mapping?

Finally deleted ALL workspaces and started from scratch. Fixed.

Why does an image captured using camera intent gets rotated on some devices on Android?

// Try this way,hope this will help you to solve your problem...

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center">
        <ImageView
            android:id="@+id/imgFromCameraOrGallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_launcher"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btnCamera"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="Camera"/>
        <Button
            android:id="@+id/btnGallery"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_marginLeft="5dp"
            android:layout_height="wrap_content"
            android:text="Gallery"/>

    </LinearLayout>
</LinearLayout>

MainActivity.java

    public class MainActivity extends Activity {

    private ImageView imgFromCameraOrGallery;
    private Button btnCamera;
    private Button btnGallery;

    private String imgPath;
    final private int PICK_IMAGE = 1;
    final private int CAPTURE_IMAGE = 2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgFromCameraOrGallery = (ImageView) findViewById(R.id.imgFromCameraOrGallery);
        btnCamera = (Button) findViewById(R.id.btnCamera);
        btnGallery = (Button) findViewById(R.id.btnGallery);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            }
        });

        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAPTURE_IMAGE) {
                setCapturedImage(getImagePath());
            } else if (requestCode == PICK_IMAGE) {
                imgFromCameraOrGallery.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
            }
        }

    }

    private String getRightAngleImage(String photoPath) {

        try {
            ExifInterface ei = new ExifInterface(photoPath);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            int degree = 0;

            switch (orientation) {
                case ExifInterface.ORIENTATION_NORMAL:
                    degree = 0;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                case ExifInterface.ORIENTATION_UNDEFINED:
                    degree = 0;
                    break;
                default:
                    degree = 90;
            }

            return rotateImage(degree,photoPath);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return photoPath;
    }

    private String rotateImage(int degree, String imagePath){

        if(degree<=0){
            return imagePath;
        }
        try{
            Bitmap b= BitmapFactory.decodeFile(imagePath);

            Matrix matrix = new Matrix();
            if(b.getWidth()>b.getHeight()){
                matrix.setRotate(degree);
                b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),
                        matrix, true);
            }

            FileOutputStream fOut = new FileOutputStream(imagePath);
            String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
            String imageType = imageName.substring(imageName.lastIndexOf(".") + 1);

            FileOutputStream out = new FileOutputStream(imagePath);
            if (imageType.equalsIgnoreCase("png")) {
                b.compress(Bitmap.CompressFormat.PNG, 100, out);
            }else if (imageType.equalsIgnoreCase("jpeg")|| imageType.equalsIgnoreCase("jpg")) {
                b.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }
            fOut.flush();
            fOut.close();

            b.recycle();
        }catch (Exception e){
            e.printStackTrace();
        }
        return imagePath;
    }

    private void setCapturedImage(final String imagePath){
        new AsyncTask<Void,Void,String>(){
            @Override
            protected String doInBackground(Void... params) {
                try {
                    return getRightAngleImage(imagePath);
                }catch (Throwable e){
                    e.printStackTrace();
                }
                return imagePath;
            }

            @Override
            protected void onPostExecute(String imagePath) {
                super.onPostExecute(imagePath);
                imgFromCameraOrGallery.setImageBitmap(decodeFile(imagePath));
            }
        }.execute();
    }

    public Bitmap decodeFile(String path) {
        try {
            // Decode deal_image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;
            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getAbsolutePath(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = "";
            if(uri.getLastPathSegment().split(":").length > 1)
                id = uri.getLastPathSegment().split(":")[1];
            else if(uri.getLastPathSegment().split(":").length > 0)
                id = uri.getLastPathSegment().split(":")[0];
            if(id.length() > 0){
                final String[] imageColumns = {MediaStore.Images.Media.DATA };
                final String imageOrderBy = null;
                Uri tempUri = getUri();
                Cursor imageCursor = getContentResolver().query(tempUri, imageColumns, MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
                if (imageCursor.moveToFirst()) {
                    return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }else{
                    return null;
                }
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

    }

    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }

    public Uri setImageUri() {
        Uri imgUri;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/",getString(R.string.app_name) + Calendar.getInstance().getTimeInMillis() + ".png");
            imgUri = Uri.fromFile(file);
            imgPath = file.getAbsolutePath();
        }else {
            File file = new File(getFilesDir() ,getString(R.string.app_name) + Calendar.getInstance().getTimeInMillis()+ ".png");
            imgUri = Uri.fromFile(file);
            this.imgPath = file.getAbsolutePath();
        }
        return imgUri;
    }

    public String getImagePath() {
        return imgPath;
    }
}

How can I see CakePHP's SQL dump in the controller?

In CakePHP 1.2 ..

$db =& ConnectionManager::getDataSource('default');
$db->showLog();

Adding an onclicklistener to listview (android)

list.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

How do you use the ? : (conditional) operator in JavaScript?

I want to add some to the given answers.

In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.


Instead of:

var welcomeMessage  = 'Hello ' + (username ? username : 'guest');

You can use:

var welcomeMessage  = 'Hello ' + (username || 'guest');

This is Javascripts equivallent of PHP's shorthand ternary operator ?:

Or even:

var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');

It evaluates the variable, and if it's false or unset, it goes on to the next.

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

Python Anaconda - How to Safely Uninstall

In my case Anaconda3 was not installed in home directory. Instead, it was installed in root. Therefore, I had to do the following to get it uninstalled:

sudo rm -rf /anaconda3/bin/python

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

How to stop a PowerShell script on the first error?

Sadly, due to buggy cmdlets like New-RegKey and Clear-Disk, none of these answers are enough. I've currently settled on the following code in a file called ps_support.ps1:

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$PSDefaultParameterValues['*:ErrorAction']='Stop'
function ThrowOnNativeFailure {
    if (-not $?)
    {
        throw 'Native Failure'
    }
}

Then in any powershell file, after the CmdletBinding and Param for the file (if present), I have the following:

$ErrorActionPreference = "Stop"
. "$PSScriptRoot\ps_support.ps1"

The duplicated ErrorActionPreference = "Stop" line is intentional. If I've goofed and somehow gotten the path to ps_support.ps1 wrong, that needs to not silently fail!

I keep ps_support.ps1 in a common location for my repo/workspace, so the path to it for the dot-sourcing may change depending on where the current .ps1 file is.

Any native call gets this treatment:

native_call.exe
ThrowOnNativeFailure

Having that file to dot-source has helped me maintain my sanity while writing powershell scripts. :-)

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

Git: Find the most recent common ancestor of two branches

With gitk you can view the two branches graphically:

gitk branch1 branch2

And then it's easy to find the common ancestor in the history of the two branches.

Service Temporarily Unavailable Magento?

You can do this thing:

Go to http://localhost/magento/downloader url. Here I am running the magento store on my localhost. Now you can login to magento connect manager and uninstall the extension which you installed previously.

Hope this works !!!!!

Thanks.

How to set column widths to a jQuery datatable?

Configuration Options:

$(document).ready(function () {

  $("#companiesTable").dataTable({
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
    "bAutoWidth": false, // Disable the auto width calculation 
    "aoColumns": [
      { "sWidth": "30%" }, // 1st column width 
      { "sWidth": "30%" }, // 2nd column width 
      { "sWidth": "40%" } // 3rd column width and so on 
    ]
  });
});

Specify the css for the table:

table.display {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed;         // add this 
  word-wrap:break-word;        // add this 
}

HTML:

<table id="companiesTable" class="display"> 
  <thead>
    <tr>
      <th>Company name</th>
      <th>Address</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>

    <% for(Company c: DataRepository.GetCompanies()){ %>
      <tr>  
        <td><%=c.getName()%></td>
        <td><%=c.getAddress()%></td>
        <td><%=c.getTown()%></td>
      </tr>
    <% } %>

  </tbody>
</table>

It works for me!

How to parse JSON using Node.js?

Using JSON for your configuration with Node.js? Read this and get your configuration skills over 9000...

Note: People claiming that data = require('./data.json'); is a security risk and downvoting people's answers with zealous zeal: You're exactly and completely wrong. Try placing non-JSON in that file... Node will give you an error, exactly like it would if you did the same thing with the much slower and harder to code manual file read and then subsequent JSON.parse(). Please stop spreading misinformation; you're hurting the world, not helping. Node was designed to allow this; it is not a security risk!

Proper applications come in 3+ layers of configuration:

  1. Server/Container config
  2. Application config
  3. (optional) Tenant/Community/Organization config
  4. User config

Most developers treat their server and app config as if it can change. It can't. You can layer changes from higher layers on top of each other, but you're modifying base requirements. Some things need to exist! Make your config act like it's immutable, because some of it basically is, just like your source code.

Failing to see that lots of your stuff isn't going to change after startup leads to anti-patterns like littering your config loading with try/catch blocks, and pretending you can continue without your properly setup application. You can't. If you can, that belongs in the community/user config layer, not the server/app config layer. You're just doing it wrong. The optional stuff should be layered on top when the application finishes it's bootstrap.

Stop banging your head against the wall: Your config should be ultra simple.

Take a look at how easy it is to setup something as complex as a protocol-agnostic and datasource-agnostic service framework using a simple json config file and simple app.js file...

container-config.js...

{
    "service": {
        "type"  : "http",
        "name"  : "login",
        "port"  : 8085
    },
    "data": {
        "type"  : "mysql",
        "host"  : "localhost",
        "user"  : "notRoot",
        "pass"  : "oober1337",
        "name"  : "connect"
    }
}

index.js... (the engine that powers everything)

var config      = require('./container-config.json');       // Get our service configuration.
var data        = require(config.data.type);            // Load our data source plugin ('npm install mysql' for mysql).
var service     = require(config.service.type);         // Load our service plugin ('http' is built-in to node).
var processor   = require('./app.js');                  // Load our processor (the code you write).

var connection  = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server      = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });

app.js... (the code that powers your protocol-agnostic and data-source agnostic service)

module.exports = function(request, response){
    response.end('Responding to: ' + request.url);
}

Using this pattern, you can now load community and user config stuff on top of your booted app, dev ops is ready to shove your work into a container and scale it. You're read for multitenant. Userland is isolated. You can now separate the concerns of which service protocol you're using, which database type you're using, and just focus on writing good code.

Because you're using layers, you can rely on a single source of truth for everything, at any time (the layered config object), and avoid error checks at every step, worrying about "oh crap, how am I going to make this work without proper config?!?".

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

Disable autocomplete via CSS

you can easily implement by jQuery

$('input').attr('autocomplete','off');

Credentials for the SQL Server Agent service are invalid

Taking SQL Server cluster role offline-Online on node 1 worked for me.

Hide Command Window of .BAT file that Executes Another .EXE File

I haven't really found a good way to do that natively, so I just use a utility called hstart which does it for me. If there's a neater way to do it, that would be nice.

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

It sounds like Maven is using the JRE, not the JDK. Perhaps you installed Maven before installing the JDK?

Check the settings files. There are three in total, system, user, and project. It's most likely in the installation configuration ($M2_HOME/conf/settings.xml) or, possibly, the per-user configuration (${user.dir}/.m2/settings.xml).

How to Diff between local uncommitted changes and origin

Given that the remote repository has been cached via git fetch it should be possible to compare against these commits. Try the following:

$ git fetch origin
$ git diff origin/master

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

How can I make my flexbox layout take 100% vertical space?

Let me show you another way that works 100%. I will also add some padding for the example.

<div class = "container">
  <div class = "flex-pad-x">
    <div class = "flex-pad-y">
      <div class = "flex-pad-y">
        <div class = "flex-grow-y">
         Content Centered
        </div>
      </div>
    </div>
  </div>
</div>

.container {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom: 0px;
  right: 0px;
  width: 100%;
  height: 100%;
}

  .flex-pad-x {
    padding: 0px 20px;
    height: 100%;
    display: flex;
  }

  .flex-pad-y {
    padding: 20px 0px;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .flex-grow-y {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
   }

As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.

1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.

Hope this helps

Daniel

Linux command to list all available commands and aliases

Use "which searchstr". Returns either the path of the binary or the alias setup if it's an alias

Edit: If you're looking for a list of aliases, you can use:

alias -p | cut -d= -f1 | cut -d' ' -f2

Add that in to whichever PATH searching answer you like. Assumes you're using bash..

How can I check whether an array is null / empty?

An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.