Programs & Examples On #Undeclared identifier

What is an 'undeclared identifier' error and how do I fix it?

These error meassages

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

mean that you use name printf but the compiler does not see where the name was declared and accordingly does not know what it means.

Any name used in a program shall be declared before its using. The compiler has to know what the name denotes.

In this particular case the compiler does not see the declaration of name printf . As we know (but not the compiler) it is the name of standard C function declared in header <stdio.h> in C or in header <cstdio> in C++ and placed in standard (std::) and global (::) (not necessarily) name spaces.

So before using this function we have to provide its name declaration to the compiler by including corresponding headers.

For example C:

#include <stdio.h>

int main( void )
{
   printf( "Hello World\n" );
}

C++:

#include <cstdio>

int main()
{
   std::printf( "Hello World\n" );
   // or printf( "Hello World\n" );
   // or ::printf( "Hello World\n" );
}

Sometimes the reason of such an error is a simple typo. For example let's assume that you defined function PrintHello

void PrintHello()
{
    std::printf( "Hello World\n" );
}

but in main you made a typo and instead of PrintHello you typed printHello with lower case letter 'p'.

#include <cstdio>

void PrintHello()
{
    std::printf( "Hello World\n" );
}

int main()
{
   printHello();
}

In this case the compiler will issue such an error because it does not see the declaration of name printHello. PrintHello and printHello are two different names one of which was declared and other was not declared but used in the body of main

Redis: Show database size/size for keys

Take a look at this project it outputs some interesting stats about keyspaces based on regexs and prefixes. It uses the DEBUG OBJECT command and scans the db, identifying groups of keys and estimating the percentage of space they're taking up.

https://github.com/snmaynard/redis-audit

Output looks like this:

Summary  

---------------------------------------------------+--------------+-------------------+---------------------------------------------------  
Key                                                | Memory Usage | Expiry Proportion | Last Access Time                                    
---------------------------------------------------+--------------+-------------------+---------------------------------------------------  
notification_3109439                               | 88.14%       | 0.0%              | 2 minutes                               
user_profile_3897016                               | 11.86%       | 99.98%            | 20 seconds  
---------------------------------------------------+--------------+-------------------+---------------------------------------------------  

Or this this one: https://github.com/sripathikrishnan/redis-rdb-tools which does a full analysis on the entire keyspace by analyzing a dump.rdb file offline. This one works well also. It can give you the avg/min/max size for the entries in your db, and will even do it based on a prefix.

JavaScript by reference vs. by value

  1. Primitive type variable like string,number are always pass as pass by value.
  2. Array and Object is passed as pass by reference or pass by value based on these two condition.

    • if you are changing value of that Object or array with new Object or Array then it is pass by Value.

      object1 = {item: "car"}; array1=[1,2,3];

    here you are assigning new object or array to old one.you are not changing the value of property of old object.so it is pass by value.

    • if you are changing a property value of an object or array then it is pass by Reference.

      object1.item= "car"; array1[0]=9;

    here you are changing a property value of old object.you are not assigning new object or array to old one.so it is pass by reference.

Code

    function passVar(object1, object2, number1) {

        object1.key1= "laptop";
        object2 = {
            key2: "computer"
        };
        number1 = number1 + 1;
    }

    var object1 = {
        key1: "car"
    };
    var object2 = {
        key2: "bike"
    };
    var number1 = 10;

    passVar(object1, object2, number1);
    console.log(object1.key1);
    console.log(object2.key2);
    console.log(number1);

Output: -
    laptop
    bike
    10

Reading a plain text file in Java

This might not be the exact answer to the question. It's just another way of reading a file where you do not explicitly specify the path to your file in your Java code and instead, you read it as a command-line argument.

With the following code,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class InputReader{

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s="";
        while((s=br.readLine())!=null){
            System.out.println(s);
        }
    }
}

just go ahead and run it with:

java InputReader < input.txt

This would read the contents of the input.txt and print it to the your console.

You can also make your System.out.println() to write to a specific file through the command line as follows:

java InputReader < input.txt > output.txt

This would read from input.txt and write to output.txt.

invalid use of non-static member function

The simplest fix is to make the comparator function be static:

static int comparator (const Bar & first, const Bar & second);
^^^^^^

When invoking it in Count, its name will be Foo::comparator.

The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo.

Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo.

change cursor from block or rectangle to line?

please Press fn +ins key together

How to convert array to SimpleXML

I found all of the answers to use too much code. Here is an easy way to do it:

function to_xml(SimpleXMLElement $object, array $data)
{   
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $new_object = $object->addChild($key);
            to_xml($new_object, $value);
        } else {
            // if the key is an integer, it needs text with it to actually work.
            if ($key != 0 && $key == (int) $key) {
                $key = "key_$key";
            }

            $object->addChild($key, $value);
        }   
    }   
}   

Then it's a simple matter of sending the array into the function, which uses recursion, so it will handle a multi-dimensional array:

$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);

Now $xml contains a beautiful XML object based on your array exactly how you wrote it.

print $xml->asXML();

Thymeleaf using path variables to th:href

try this one is a very easy method if you are in list of model foreach (var item in Modal) loop

<th:href="/category/edit/@item.idCategory>View</a>"

or

<th:href="/category/edit/@item.idCategory">View</a>

svn over HTTP proxy

Ok, this should be really easy:

$ sudo vi /etc/subversion/servers

Edit the file:

[Global]
http-proxy-host=my.proxy.com
http-proxy-port=3128

Save it, run svn again and it will work.

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

How do you synchronise projects to GitHub with Android Studio?

In Android Studio 0.8.2 , you have the same option (ie Share on GitHub). If you want to find it, you can use ctrl+shift+a and enter github in the input text.

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

Can Python test the membership of multiple values in a list?

Another way to do it:

>>> set(['a','b']).issubset( ['b','a','foo','bar'] )
True

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Bootstrap table striped: How do I change the stripe background colour?

I came across this post while hunting down a solution for myself. By using chrome's inspector, I was able to determine that the striped color was being applied from the --bs-table-striped-color tag.

overriding that tag in your css:

<style scoped>
table {
--bs-table-striped-color: #85d1ee;
}
</style>

how to bold words within a paragraph in HTML/CSS?

if you want to just "bold", Mike Hofer's answer is mostly correct.

but notice that the tag bolds its contents by default, but you can change this behavior using css, example:

p strong {
    font-weight: normal;
    font-style: italic;
}

Now your "bold" is italic :)

So, try to use tags by its meaning, not by its default style.

'python' is not recognized as an internal or external command

I have found the answer... click on the installer and check the box "Add python to environment variables" DO NOT uninstall the old one rather click on modify....Click on link for picture...

enter image description here

JQuery Calculate Day Difference in 2 date textboxes

$("#edate").change(function(){

   var edate = new Date($('#edate').val());
   var sdate = new Date($('#sdate').val());
   
   days = (edate- sdate) / (1000 * 60 * 60 * 24);
   days=days+1;
   alert (days);
   $("#nod").val(days);
});

Location of the android sdk has not been setup in the preferences in mac os?

I had the same problem when I was trying to upgrade from ADT 20.0.x to ADT 23.0.x on Eclipse Indigo.

To fix the issue, I had to uninstall the ADT plugin (remove feature) from Eclipse, then reinstall the newer versions.

This maybe done by going to Help->Install New Software. Then at the bottom of the page, click What is already installed?

All what is left now is to install the newer versions as usual from help->Install New Software.

Sending Multipart File as POST parameters with RestTemplate requests

If you have to send a multipart file that is composed, among other things, by an Object that needs to be converted with a specific HttpMessageConverter and you get the "no suitable HttpMessageConverter" error no matter what you try, you may want to try with this:

RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter converter = new FormHttpMessageConverter();

converter.addPartConverter(new TheRequiredHttpMessageConverter());
//for example, in my case it was "new MappingJackson2HttpMessageConverter()"

restTemplate.getMessageConverters().add(converter);

This solved the problem for me with a custom Object that, together with a file (instanceof FileSystemResource, in my case), was part of the multipart file I needed to send. I tried with TrueGuidance's solution (and many others found around the web) to no avail, then I looked at FormHttpMessageConverter's source code and tried this.

Progress Bar with HTML and CSS

In modern browsers you could use a CSS3 & HTML5 progress Element!

_x000D_
_x000D_
progress {_x000D_
  width: 40%;_x000D_
  display: block; /* default: inline-block */_x000D_
  margin: 2em auto;_x000D_
  padding: 3px;_x000D_
  border: 0 none;_x000D_
  background: #444;_x000D_
  border-radius: 14px;_x000D_
}_x000D_
progress::-moz-progress-bar {_x000D_
  border-radius: 12px;_x000D_
  background: orange;_x000D_
_x000D_
}_x000D_
/* webkit */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0) {_x000D_
  progress {_x000D_
    height: 25px;_x000D_
  }_x000D_
}_x000D_
progress::-webkit-progress-bar {_x000D_
    background: transparent;_x000D_
}  _x000D_
progress::-webkit-progress-value {  _x000D_
  border-radius: 12px;_x000D_
  background: orange;_x000D_
} 
_x000D_
<progress max="100" value="40"></progress>
_x000D_
_x000D_
_x000D_

How do I get a python program to do nothing?

You could use a pass statement:

if condition:
    pass

Python 2.x documentation

Python 3.x documentation

However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.

If you have something like this:

if condition:        # condition in your case being `num2 == num5`
    pass
else:
    do_something()

You can in general change it to this:

if not condition:
    do_something()

But in this specific case you could (and should) do this:

if num2 != num5:        # != is the not-equal-to operator
    do_something()

jQuery set checkbox checked

I know this asks for a Jquery solution, but I just thought I'd point out that it is very easy to toggle this in plain javascript.

var element = document.getElementById("estado_cat");
element.checked = 1;

It will work in all current and future versions.

How do I find which program is using port 80 in Windows?

Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).

As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008

The following command will show what network traffic is in use at the port level:

Netstat -a -n -o

or

Netstat -a -n -o >%USERPROFILE%\ports.txt

(to open the port and process list in a text editor, where you can search for information you want)

Then,

with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.

Example:

tasklist /svc /FI "PID eq 1348"

How do I hide an element when printing a web page?

You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):

<div id="printOption">
    <a href="javascript:void();" 
       onclick="document.getElementById('printOption').style.visibility = 'hidden'; 
       document.print(); 
       return true;">
       Print
    </a>
</div>

The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).

The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.

C# - How to get Program Files (x86) on Windows 64 bit

C# Code:

Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)

Output:

C:\Program Files (x86)

Note:

We need to tell the compiler to not prefer a particular build platform.

Go to Visual Studio > Project Properties > Build > Uncheck "Prefer 32 bit"

Reason:

By default for most .NET Projects is "Any CPU 32-bit preferred"

When you uncheck 32 bit assembly will:

JIT to 32-bit code on 32 bit process

JIT to 32-bit code on 64 bit process

Alternative to the HTML Bold tag

You're thinking of the CSS property font-weight:

p { font-weight: bold; }

How to remove foreign key constraint in sql server?

ALTER TABLE table
DROP FOREIGN KEY fk_key

EDIT: didn't notice you were using sql-server, my bad

ALTER TABLE table
DROP CONSTRAINT fk_key

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

How to change the color of the axis, ticks and labels for a plot in matplotlib

If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.

This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))

enter image description here

enter image description here

You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]

How to convert URL parameters to a JavaScript object?

I found $.String.deparam the most complete pre built solution (can do nested objects etc.). Check out the documentation.

APK signing error : Failed to read key from keystore

For someone not using the signing configs and trying to test out the Cordova Release command by typing all the parameters at command line, you may need to enclose your passwords with single quotes if you have special characters in your password

cordova run android --release -- --keystore=../my-release-key.keystore --storePassword='password' --alias=alias_name --password='password'

Setting initial values on load with Select2 with Ajax

The function which you are specifying as initSelection is called with the initial value as argument. So if value is empty, the function is not called.
When you specifiy value='[{"id":"IN","name":"India"}]' instead of data-initvalue the function gets called and the selection can get initialized.

How to consume a webApi from asp.net Web API to store result in database?

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
    var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
    foreach (var x in yourcustomobjects)
    {
        //Call your store method and pass in your own object
        SaveCustomObjectToDB(x);
    }
}
else
{
    //Something has gone wrong, handle it here
}

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Insert an element at a specific index in a list and return the updated list

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here's the timeit comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.

Python 3.9.1

  1. My answer using sliced insertion - Fastest ( 2.25 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.33 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    50000 loops, best of 5: 5.01 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 135 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    2000 loops, best of 5: 135 µsec per loop
    

Python 2.7.16

  1. My answer using sliced insertion - Fastest (2.09 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 2.09 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.36 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 3: 2.36 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 4.44 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 103 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 103 µsec per loop
    

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

Deny access to one specific folder in .htaccess

We will set the directory to be very secure, denying access for all file types. Below is the code you want to insert into the .htaccess file.

Order Allow,Deny 
Deny from all 

Since we have now set the security, we now want to allow access to our desired file types. To do that, add the code below to the .htaccess file under the security code you just inserted.

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

your final .htaccess file will look like

Order Allow,Deny 
Deny from all 

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

Source from Allow access to specific file types in a protected directory

String comparison - Android

You can use, contentEquals() function. It may help you..

Partly JSON unmarshal into a map in Go

Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

Example:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

Sample output:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen

jQuery: Performing synchronous AJAX requests

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success: function (result) {
            /* if result is a JSon object */
            if (result.valid)
                return true;
            else
                return false;
        }
    });
}

Why does adb return offline after the device string?

Check that the ADB version that you are running is newer than the version of the OS on the connected devices. For me, updating the ADB helped to get the device online.

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

jsonify a SQLAlchemy result set in Flask

I was working with a sql query defaultdict of lists of RowProxy objects named jobDict It took me a while to figure out what Type the objects were.

This was a really simple quick way to resolve to some clean jsonEncoding just by typecasting the row to a list and by initially defining the dict with a value of list.

    jobDict = defaultdict(list)
    def set_default(obj):
        # trickyness needed here via import to know type
        if isinstance(obj, RowProxy):
            return list(obj)
        raise TypeError


    jsonEncoded = json.dumps(jobDict, default=set_default)

PHP CURL Enable Linux

if you have used curl above the page and below your html is present and unfortunately your html page is not able to view then just enable your curl. But in order to check CURL is enable or not in php you need to write following code:

echo 'Curl: ', function_exists('curl_version') ? 'Enabled' : 'Disabled';

What order are the Junit @Before/@After called?

You can use @BeforeClass annotation to assure that setup() is always called first. Similarly, you can use @AfterClass annotation to assure that tearDown() is always called last.

This is usually not recommended, but it is supported.

It's not exactly what you want - but it'll essentially keep your DB connection open the entire time your tests are running, and then close it once and for all at the end.

LEFT JOIN only first row

Version without subselect:

   SELECT f.title,
          f.content,
          MIN(a.artist_name) artist_name
     FROM feeds f
LEFT JOIN feeds_artists fa ON fa.feed_id = f.id
LEFT JOIN artists a ON fa.artist_id = a.artist_id
 GROUP BY f.id

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

MySQL makes a difference between "localhost" and "127.0.0.1".

It might be possible that 'root'@'localhost' is not allowed because there is an entry in the user table that will only allow root login from 127.0.0.1.

This could also explain why some application on your server can connect to the database and some not because there are different ways of connecting to the database. And you currently do not allow it through "localhost".

Adding n hours to a date in Java?

You can use this method, It is easy to understand and implement :

public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
    calendar.add(Calendar.MINUTE, nombreMinute);
    calendar.add(Calendar.SECOND, nombreSeconde);
    return calendar.getTime();
}

Getting The ASCII Value of a character in a C# string

This example might help you. by using simple casting you can get code behind urdu character.

string str = "?????";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

Is it ok to use `any?` to check if an array is not empty?

Avoid any? for large arrays.

  • any? is O(n)
  • empty? is O(1)

any? does not check the length but actually scans the whole array for truthy elements.

static VALUE
rb_ary_any_p(VALUE ary)
{
  long i, len = RARRAY_LEN(ary);
  const VALUE *ptr = RARRAY_CONST_PTR(ary);

  if (!len) return Qfalse;
  if (!rb_block_given_p()) {
    for (i = 0; i < len; ++i) if (RTEST(ptr[i])) return Qtrue;
  }
  else {
    for (i = 0; i < RARRAY_LEN(ary); ++i) {
        if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
    }
  }
  return Qfalse;
}

empty? on the other hand checks the length of the array only.

static VALUE
rb_ary_empty_p(VALUE ary)
{
  if (RARRAY_LEN(ary) == 0)
    return Qtrue;
  return Qfalse;
}

The difference is relevant if you have "sparse" arrays that start with lots of nil values, like for example an array that was just created.

Get list of filenames in folder with Javascript

No, Javascript doesn't have access to the filesystem. Server side Javascript is a whole different story but I guess you don't mean that.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that using the @EnableAutoConfiguration annotation on a test class won't work if you are using @SpringApplicationConfiguration to load your Application class. The thing is that you already have a @EnableAutoConfiguration annotation in the Application class that does not exclude the CrshAutoConfiguration.Spring uses that annotation instead of the one on your test class to do the auto configuration of your beans.

I think that your best bet is to use a different application context for your tests and exclude the CrshAutoConfiguration in that class.

I did some tests and it seems that @EnableAutoConfiguration on the test class is completely ignore if you are using the @SpringApplicationConfiguration annotation and the SpringJUnit4ClassRunner.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Add "-O file.tgz" or "-O file.tar.gz" at the end wget command and extract "file.tgz" or "file.tar.gz"

Here is the sample code for google colab-

!wget -q  --trust-server-names  https://downloads.apache.org/spark/spark-3.0.0/spark-3.0.0-bin-hadoop2.7.tgz  -O file.tgz 
print("Download completed successfully !!!")
!tar zxvf  file.tgz 

Note- Please ensure that http path for tgz is valid and file is not corrupted

Provisioning Profiles menu item missing from Xcode 5

Provisioning files are located in:

/Users/${USER}/Library/MobileDevice/Provisioning Profiles/

Just remove the out-of-date files.

Batch: Remove file extension

Using cygwin bash to do the chopping

  :: e.g. FILE=basename.mp4 => FILE_NO_EXT=basename
  set FILE=%1
  for /f "delims=" %%a in ('bash -c "FILE=%FILE%; echo ${FILE/.*/}" ') do set FILE_NO_EXT=%%a

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

How to convert Double to int directly?

All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.

You can use Math.round(double) function or simply do :

(int)(yourDoubleValue + 0.5d)

How to run docker-compose up -d at system start up?

Use restart: always in your docker compose file.

Docker-compose up -d will launch container from images again. Use docker-compose start to start the stopped containers, it never launches new containers from images.

nginx:   
    restart: always   
    image: nginx   
    ports:
      - "80:80"
      - "443:443"   links:
      - other_container:other_container

Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.

Using LIMIT within GROUP BY to get N results per group?

Took some working, but I thougth my solution would be something to share as it is seems elegant as well as quite fast.

SELECT h.year, h.id, h.rate 
  FROM (
    SELECT id, 
      SUBSTRING_INDEX(GROUP_CONCAT(CONCAT(id, '-', year) ORDER BY rate DESC), ',' , 5) AS l
      FROM h
      WHERE year BETWEEN 2000 AND 2009
      GROUP BY id
      ORDER BY id
  ) AS h_temp
    LEFT JOIN h ON h.id = h_temp.id 
      AND SUBSTRING_INDEX(h_temp.l, CONCAT(h.id, '-', h.year), 1) != h_temp.l

Note that this example is specified for the purpose of the question and can be modified quite easily for other similar purposes.

get current page from url

You could try this below.

string url = "http://localhost:1302/TESTERS/Default6.aspx";

string fileName = System.IO.Path.GetFileName(url);

Hope this helps.

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

In my case failure was caused by com.android.providers.media app. I faced this on x86 android emulator. What did I do:

$ adb shell df
Filesystem             Size   Used   Free   Blksize
...
/data                  224M   209M    14M   4096
....

Too low free space on /data

$ adb shell du /data
...
409870  /data/data/com.android.providers.media
...

Almost all was consumed by single app! It's system app so I consider better not to delete it. Instead I cleaned up app data.

$ adb shell pm clear com.android.providers.media
Success
$ adb shell df
Filesystem             Size   Used   Free   Blksize
...
/data                  224M     8M   215M   4096
...

Disk was cleared and app installed successfully.

Gridview row editing - dynamic binding to a DropDownList

The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.

I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.

When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)

The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:

protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

visual c++: #include files from other projects in the same solution

Expanding on @Benav's answer, my preferred approach is to:

  1. Add the solution directory to your include paths:
    • right click on your project in the Solution Explorer
    • select Properties
    • select All Configurations and All Platforms from the drop-downs
    • select C/C++ > General
    • add $(SolutionDir) to the Additional Include Directories
  2. Add references to each project you want to use:
    • right click on your project's References in the Solution Explorer
    • select Add Reference...
    • select the project(s) you want to refer to

Now you can include headers from your referenced projects like so:

#include "OtherProject/Header.h"

Notes:

  • This assumes that your solution file is stored one folder up from each of your projects, which is the default organization when creating projects with Visual Studio.
  • You could now include any file from a path relative to the solution folder, which may not be desirable but for the simplicity of the approach I'm ok with this.
  • Step 2 isn't necessary for #includes, but it sets the correct build dependencies, which you probably want.

Android Calling JavaScript functions in WebView

I figured out what the issue was : missing quotes in the testEcho() parameter. This is how I got the call to work:

myWebView.loadUrl("javascript:testEcho('Hello World!')");

How to exclude file only from root folder in Git

If the above solution does not work for you, try this:

#1.1 Do NOT ignore file pattern in  any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php

##########################

# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php

How can I pad a value with leading zeros?

Even later to the party.

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}

This handles negatives and situations where the number is longer than the field width. And floating-point.

How to prove that a problem is NP complete?

  1. Get familiar to a subset of NP Complete problems
  2. Prove NP Hardness : Reduce an arbitrary instance of an NP complete problem to an instance of your problem. This is the biggest piece of a pie and where the familiarity with NP Complete problems pays. The reduction will be more or less difficult depending on the NP Complete problem you choose.
  3. Prove that your problem is in NP : design an algorithm which can verify in polynomial time whether an instance is a solution.

How to convert an entire MySQL database characterset and collation to UTF-8?

For databases that have a high number of tables you can use a simple php script to update the charset of the database and all of the tables using the following:

$conn = mysqli_connect($host, $username, $password, $database);

if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$alter_database_charset_sql = "ALTER DATABASE ".$database." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
mysqli_query($conn, $alter_database_charset_sql);

$show_tables_result = mysqli_query($conn, "SHOW TABLES");
$tables  = mysqli_fetch_all($show_tables_result);

foreach ($tables as $index => $table) {
  $alter_table_sql = "ALTER TABLE ".$table[0]." CONVERT TO CHARACTER SET utf8  COLLATE utf8_unicode_ci";
  $alter_table_result = mysqli_query($conn, $alter_table_sql);
  echo "<pre>";
  var_dump($alter_table_result);
  echo "</pre>";
}

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

Abstract Class:-Real Time Example

I use often abstract classes in conjuction with Template method pattern.
In main abstract class I wrote the skeleton of main algorithm and make abstract methods as hooks where suclasses can make a specific implementation; I used often when writing data parser (or processor) that need to read data from one different place (file, database or some other sources), have similar processing step (maybe small differences) and different output.
This pattern looks like Strategy pattern but it give you less granularity and can degradated to a difficult mantainable code if main code grow too much or too exceptions from main flow are required (this considerations came from my experience).
Just a small example:

abstract class MainProcess {
  public static class Metrics {
    int skipped;
    int processed;
    int stored;
    int error;
  }
  private Metrics metrics;
  protected abstract Iterator<Item> readObjectsFromSource();
  protected abstract boolean storeItem(Item item);
  protected Item processItem(Item item) {
    /* do something on item and return it to store, or null to skip */
    return item;
  }
  public Metrics getMetrics() {
    return metrics;
  }
  /* Main method */
  final public void process() {
    this.metrics = new Metrics();
    Iterator<Item> items = readObjectsFromSource();
    for(Item item : items) {
      metrics.processed++;
      item = processItem(item);
      if(null != item) {

        if(storeItem(item))
          metrics.stored++;
        else
          metrics.error++;
      }
      else {
        metrics.skipped++;
      }
    }
  } 
}

class ProcessFromDatabase extends MainProcess {
  ProcessFromDatabase(String query) {
    this.query = query;
  }
  protected Iterator<Item> readObjectsFromSource() {
    return sessionFactory.getCurrentSession().query(query).list();
  }
  protected boolean storeItem(Item item) {
    return sessionFactory.getCurrentSession().saveOrUpdate(item);
  }
}

Here another example.

How to enable mod_rewrite for Apache 2.2

Open terminal and typin a2enmod rewrite, It will enable your mod_rewrite module for Apache.

Then go to /etc/apache2/sites-available and edit default file. (For this you must have writable permissions to this file and sites-available folder.)

Replace below with existing lines 4 to 14

DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

Now restart your apache by /etc/init.d/apache2 restart or service apache2 restart

Take clean URL test again and this time it will be passed.

How can I escape a single quote?

You could try using: &#145;

How to upgrade safely php version in wamp server

  1. Simply Download the PHP version that you want from this url: http://wampserver.aviatechno.net/
  2. Goto your wamp\bin\php directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp list of installed version in the directory
  3. Start wamp and click wamp icon and choose the version of php you want to use: https://gyazo.com/de5727d7e254795e238422783dec3758

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

Node.js for() loop returning the same values at each loop

I would suggest doing this in a more functional style :P

function CreateMessageboard(BoardMessages) {
  var htmlMessageboardString = BoardMessages
   .map(function(BoardMessage) {
     return MessageToHTMLString(BoardMessage);
   })
   .join('');
}

Try this

How can we generate getters and setters in Visual Studio?

If you are using Visual Studio 2005 and up, you can create a setter/getter real fast using the insert snippet command.

Right click on your code, click on Insert Snippet (Ctrl+K,X), and then choose "prop" from the list.

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

DataTables: Cannot read property 'length' of undefined

While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.

Yahoo Finance All Currencies quote API Documentation

I have used this URL to obtain multiple currency market quotes.

http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X

"USD",1.0000
"CAD",1.2458
"EUR",0.8396

They can be parsed in PHP like this:

$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');

$quote = array_map( 'str_getcsv', file($url) );

foreach ($quote as $key => $symb) {
    $symbol = $quote[$key][0];
    $value = $quote[$key][1];
}

Getting an element from a Set

The contract of the hash code makes clear that:

"If two objects are equal according to the Object method, then calling the hashCode method on each of the two objects must produce the same integer result."

So your assumption:

"To clarify, the equals method is overridden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo."

is wrong and you are breaking the contract. If we look at the "contains" method of Set interface, we have that:

boolean contains(Object o);
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element "e" such that o==null ? e==null : o.equals(e)

To accomplish what you want, you can use a Map where you define the key and store your element with the key that defines how objects are different or equal to each other.

Python list of dictionaries search

@Frédéric Hamidi's answer is great. In Python 3.x the syntax for .next() changed slightly. Thus a slight modification:

>>> dicts = [
     { "name": "Tom", "age": 10 },
     { "name": "Mark", "age": 5 },
     { "name": "Pam", "age": 7 },
     { "name": "Dick", "age": 12 }
 ]
>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}

As mentioned in the comments by @Matt, you can add a default value as such:

>>> next((item for item in dicts if item["name"] == "Pam"), False)
{'name': 'Pam', 'age': 7}
>>> next((item for item in dicts if item["name"] == "Sam"), False)
False
>>>

.map() a Javascript ES6 Map?

If you don't want to convert the entire Map into an array beforehand, and/or destructure key-value arrays, you can use this silly function:

_x000D_
_x000D_
/**_x000D_
 * Map over an ES6 Map._x000D_
 *_x000D_
 * @param {Map} map_x000D_
 * @param {Function} cb Callback. Receives two arguments: key, value._x000D_
 * @returns {Array}_x000D_
 */_x000D_
function mapMap(map, cb) {_x000D_
  let out = new Array(map.size);_x000D_
  let i = 0;_x000D_
  map.forEach((val, key) => {_x000D_
    out[i++] = cb(key, val);_x000D_
  });_x000D_
  return out;_x000D_
}_x000D_
_x000D_
let map = new Map([_x000D_
  ["a", 1],_x000D_
  ["b", 2],_x000D_
  ["c", 3]_x000D_
]);_x000D_
_x000D_
console.log(_x000D_
  mapMap(map, (k, v) => `${k}-${v}`).join(', ')_x000D_
); // a-1, b-2, c-3
_x000D_
_x000D_
_x000D_

Git: How to reset a remote Git repository to remove all commits?

Were I you I would do something like this:

Before doing anything please keep a copy (better safe than sorry)

git checkout master
git checkout -b temp 
git reset --hard <sha-1 of your first commit> 
git add .
git commit -m 'Squash all commits in single one'
git push origin temp

After doing that you can delete other branches.

Result: You are going to have a branch with only 2 commits.

Use git log --oneline to see your commits in a minimalistic way and to find SHA-1 for commits!

Is this how you define a function in jQuery?

No.

You define the functions exactly the same way you would in regular javascript.

//document ready
$(function(){
    myBlah();
})

var myBlah = function(blah){
    alert(blah);
}

Also: There is no need for the $

What does "Table does not support optimize, doing recreate + analyze instead" mean?

Best option is create new table with same properties

CREATE TABLE <NEW.NAME.TABLE> LIKE <TABLE.CRASHED>;
INSERT INTO <NEW.NAME.TABLE> SELECT * FROM <TABLE.CRASHED>;

Rename NEW.NAME.TABLE and TABLE.CRASH

RENAME TABLE <TABLE.CRASHED> TO <TABLE.CRASHED.BACKUP>;
RENAME TABLE <NEW.NAME.TABLE> TO <TABLE.CRASHED>;

After work well, delete

DROP TABLE <TABLE.CRASHED.BACKUP>;

Excel VBA Run Time Error '424' object required

Private Sub CommandButton1_Click()

    Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
    Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption

    Me.Hide

    Run "filename"

End Sub

Private Sub MUN_Change()
    Dim r As Integer
    r = 2

    While Range("m" & CStr(r)).Value <> ""
        If Range("m" & CStr(r)).Value = MUN.Text Then
        Label5.Caption = Range("n" & CStr(r)).Value
        End If
        r = r + 1
    Wend

End Sub

Private Sub PROV_Change()
    If PROV.Text = "LAGUNA" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M26:M56"
    ElseIf PROV.Text = "CAVITE" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M2:M25"
    ElseIf PROV.Text = "QUEZON" Then
        MUN.Text = ""
        MUN.RowSource = "Menu!M57:M97"
    End If
End Sub

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Request is not available in this context

When you have custom logging logic, it is rather annoying to be forced either not to log application_start or to have to let an exception occurs in the logger (even if handled).

It appears that rather than testing for Request availability, you can test for Handler availability: when there is no Request, it would be strange to still have a request handler. And testing for Handler does not raise that dreaded Request is not available in this context exception.

So you may change your code to:

var currContext = HttpContext.Current;
if (currContext != null && currContext.Handler != null)

Beware, in the context of a http module, Handler may not be defined though Request and Response are defined (I have seen that in BeginRequest event). So if you need request/response logging in a custom http module, my answer may not be suitable.

MySQL Cannot drop index needed in a foreign key constraint

drop the index and the foreign_key in the same query like below

ALTER TABLE `your_table_name` DROP FOREIGN KEY `your_index`;
ALTER TABLE `your_table_name` DROP COLUMN `your_foreign_key_id`;

document.getElementById("test").style.display="hidden" not working

its a block element, and you need to use none

document.getElementById("test").style.display="none"

hidden is used for visibility

What are the proper permissions for an upload folder with PHP/Apache?

What is important is that the apache user and group should have minimum read access and in some cases execute access. For the rest you can give 0 access.

This is the most safe setting.

How to get a list of MySQL views?

 select * FROM information_schema.views\G; 

Adding a simple UIAlertView

This page shows how to add an UIAlertController if you are using Swift.

How can I capture packets in Android?

Option 1 - Android PCAP

Limitation

Android PCAP should work so long as:

Your device runs Android 4.0 or higher (or, in theory, the few devices which run Android 3.2). Earlier versions of Android do not have a USB Host API

Option 2 - TcpDump

Limitation

Phone should be rooted

Option 3 - bitshark (I would prefer this)

Limitation

Phone should be rooted

Reason - the generated PCAP files can be analyzed in WireShark which helps us in doing the analysis.

Other Options without rooting your phone

  1. tPacketCapture

https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

Advantages

Using tPacketCapture is very easy, captured packet save into a PCAP file that can be easily analyzed by using a network protocol analyzer application such as Wireshark.

  1. You can route your android mobile traffic to PC and capture the traffic in the desktop using any network sniffing tool.

http://lifehacker.com/5369381/turn-your-windows-7-pc-into-a-wireless-hotspot

Reduce left and right margins in matplotlib plot

Just use ax = fig.add_axes([left, bottom, width, height]) if you want exact control of the figure layout. eg.

left = 0.05
bottom = 0.05
width = 0.9
height = 0.9
ax = fig.add_axes([left, bottom, width, height])

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

This solution solve my problem: (from: https://msdn.microsoft.com/en-us/library/ms239722.aspx)

To permanently attach a database file (.mdf) from the Data Connections node

  1. Open the shortcut menu for Data Connections and choose Add New Connection.

    The Add Connection dialog box appears.

  2. Choose the Change button.

    The Change Data Source dialog box appears.

  3. Select Microsoft SQL Server and choose the OK button.

    The Add Connection dialog box reappears, with Microsoft SQL Server (SqlClient) displayed in the Data source text box.

  4. In the Server Name box, type or browse to the path to the local instance of SQL Server. You can type the following:

    • "." for the default instance on your computer.
    • "(LocalDB)\v11.0" for the default instance of SQL Server Express LocalDB.
    • ".\SQLEXPRESS" for the default instance of SQL Server Express.

    For information about SQL Server Express LocalDB and SQL Server Express, see Local Data Overview.

  5. Select either Use Windows Authentication or Use SQL Server Authentication.

  6. Choose Attach a database file, Browse, and open an existing .mdf file.

  7. Choose the OK button.

    The new database appears in Server Explorer. It will remain connected to SQL Server until you explicitly detach it.

How can I convince IE to simply display application/json rather than offer to download it?

I had a similar problem. I was using the "$. GetJSON" jQuery and everything worked perfectly in Firefox and Chrome.

But it did not work in IE. So I tried to directly access the URL of json, but in IE it asked if I wanted to download the file.

After much searching I saw that there must be a header in the result with a content-type, in my case, the content-type was:

header("Content-type: text/html; charset=iso-8859-1");

But when the page that made the request receives this json, in IE, you have to be specified SAME CONTENT-TYPE, in my case was:

$.getJSON (
"<? site_url php echo (" ajax / tipoMenu ")?>"
{contentType: 'text / html; charset = utf-8'},
function (result) {

hugs

What USB driver should we use for the Nexus 5?

I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.

When I plugged it, there wasn't any yellow exclamation mark within Device Manager. So for me, the drivers were OK. But the device was not listed within my Eclipse DDMS. After a little bit of searching, it was just an option to change in the device settings. By default, the Nexus 5 USB computer connection is in MTP mode (Media Device).

What you have to do is:

  • Unplug the device from the computer
  • Go to Settings -> Storage.
  • In the ActionBar, click the option menu and choose "USB computer connection".
  • Check "Camera (PTP)" connection.
  • Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.
  • Finally, you should see it now in the DDMS and voilà.

I hope this will help!

find vs find_by vs where

Since Rails 4 you can do:

User.find_by(name: 'Bob')

which is the equivalent find_by_name in Rails 3.

Use #where when #find and #find_by are not enough.

How to cast an Object to an int

Assuming the object is an Integer object, then you can do this:

int i = ((Integer) obj).intValue();

If the object isn't an Integer object, then you have to detect the type and convert it based on its type.

Setting a system environment variable from a Windows batch file?

SetX is the command that you'll need in most of the cases.Though its possible to use REG or REGEDIT

Using registry editing commands you can avoid some of the restrictions of the SetX command - different data types, variables containing = in their name and so on.

@echo off

:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal


:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"

REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat - mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):

REGEDIT4

; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"

[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

I tested all the answers about this topic. And nothing worked here… but I found another solution.

Go to pom -> overview and add these to your properties:

Name: “maven.compiler.target” Value: “1.8”

and

Name: “maven.compiler.source” Value: “1.8”

Now do a maven update.

What is the difference between an IntentService and a Service?

Intent service is child of Service

IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.

Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication

Spring Resttemplate exception handling

I have handled this as below:

try {
  response = restTemplate.postForEntity(requestUrl, new HttpEntity<>(requestBody, headers), String.class);
} catch (HttpStatusCodeException ex) {
  response = new ResponseEntity<String>(ex.getResponseBodyAsString(), ex.getResponseHeaders(), ex.getStatusCode());
}

How do I initialize the base (super) class?

Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object and are what you are using, and invoke their base class through super(), e.g.

class X(object):
  def __init__(self, x):
    pass

  def doit(self, bar):
    pass

class Y(X):
  def __init__(self):
    super(Y, self).__init__(123)

  def doit(self, foo):
    return super(Y, self).doit(foo)

Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.

For completeness sake, old-style classes call base methods explicitly using the base class, i.e.

def doit(self, foo):
  return X.doit(self, foo)

But since you shouldn't be using old-style anymore, I wouldn't care about this too much.

Python 3 only knows about new-style classes (no matter if you derive from object or not).

Static method in a generic class?

It is correctly mentioned in the error: you cannot make a static reference to non-static type T. The reason is the type parameter T can be replaced by any of the type argument e.g. Clazz<String> or Clazz<integer> etc. But static fields/methods are shared by all non-static objects of the class.

The following excerpt is taken from the doc:

A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed. Consider the following class:

public class MobileDevice<T> {
    private static T os;

    // ...
}

If static fields of type parameters were allowed, then the following code would be confused:

MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();

Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It cannot be Smartphone, Pager, and TabletPC at the same time. You cannot, therefore, create static fields of type parameters.

As rightly pointed out by chris in his answer you need to use type parameter with the method and not with the class in this case. You can write it like:

static <E> void doIt(E object) 

Xcode 6 Bug: Unknown class in Interface Builder file

Selecting the proper Module for my Custom Class I solved this problem .

Here it is :

enter image description here

What resources are shared between threads?

From Wikipedia (I think that would make a really good answer for the interviewer :P)

Threads differ from traditional multitasking operating system processes in that:

  • processes are typically independent, while threads exist as subsets of a process
  • processes carry considerable state information, whereas multiple threads within a process share state as well as memory and other resources
  • processes have separate address spaces, whereas threads share their address space
  • processes interact only through system-provided inter-process communication mechanisms.
  • Context switching between threads in the same process is typically faster than context switching between processes.

HttpContext.Current.User.Identity.Name is Empty

In addition to "answered Mar 28 '11 at 12:27Bryan Bedard"

In case that the solution doesn't work, you have to enable Windows Authentication in iss manager. How to do that:

1.To start IIS Manager from the Run dialog box: On the Start menu, click All Programs, click Accessories, and then click Run. In the Open box, type inetmgr and then click OK.

2.In the Connections pane, expand the server name, expand Sites, and go to the level in the hierarchy pane that you want to configure, and then click the Web site or Web application. 3. Scroll to the IIS section in the Home pane, and then double-click Authentication.

4.In the Authentication pane, select Anonymous Authentication, and then click Disable. enter image description here

  1. In the Authentication pane, select Windows Authentication, and then click Enable.

Reference

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

Can't drop table: A foreign key constraint fails

This should do the trick:

SET FOREIGN_KEY_CHECKS=0; DROP TABLE bericht; SET FOREIGN_KEY_CHECKS=1;

As others point out, this is almost never what you want, even though it's whats asked in the question. A more safe solution is to delete the tables depending on bericht before deleting bericht. See CloudyMarble answer on how to do that. I use bash and the method in my post to drop all tables in a database when I don't want to or can't delete and recreate the database itself.

The #1217 error happens when other tables has foreign key constraints to the table you are trying to delete and you are using the InnoDB database engine. This solution temporarily disables checking the restraints and then re-enables them. Read the documentation for more. Be sure to delete foreign key restraints and fields in tables depending on bericht, otherwise you might leave your database in a broken state.

How to round up a number in Javascript?

this function limit decimal without round number

function limitDecimal(num,decimal){
     return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}

login to remote using "mstsc /admin" with password

It became a popular question and I got a notification. I am sorry, I forgot to answer before which I should have done. I solved it long back.

net use \\10.100.110.120\C$ MyPassword /user:domain\username /persistent:Yes

Run it in a batch file and you should get what you are looking for.

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

Where is database .bak file saved from SQL Server Management Studio?

have you tried:

C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup

Script to get all backups in the last week can be found at:

http://wraithnath.blogspot.com/2010/12/how-to-find-all-database-backups-in.html

I have plenty more backup SQL scripts there also at

http://wraithnath.blogspot.com/search/label/SQL

How would I stop a while loop after n amount of time?

You do not need to use the while True: loop in this case. There is a much simpler way to use the time condition directly:

import time

# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300   # [seconds]

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    test = 0
    if test == 5:
        break
    test -= 1

How to scroll to top of a div using jQuery?

I don't know why but you have to add a setTimeout with at least for me 200ms:

setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );

Tested with Firefox / Chrome / Edge.

Inserting a PDF file in LaTeX

I don't think there would be an automatic way. You might also want to add a page number to the appendix correctly. Assuming that you already have your pdf document of several pages, you'll have to extract each page first of your pdf document using Adobe Acrobat Professional for instance and save each of them as a separate pdf file. Then you'll have to include each of the the pdf documents as images on an each page basis (1 each page) and use newpage between each page e,g,

\appendix
\section{Quiz 1}\label{sec:Quiz}
\begin{figure}[htp] \centering{
\includegraphics[scale=0.82]{quizz.pdf}}
\caption{Experiment 1}
\end{figure}  

\newpage
\section{Sample paper}\label{sec:Sample}
\begin{figure}[htp] \centering{
\includegraphics[scale=0.75]{sampaper.pdf}}
\caption{Experiment 2}
\end{figure}

Now each page will appear with 1 pdf image per page and you'll have a correct page number at the bottom. As shown in my example, you'll have to play a bit with the scale factor for each image to get it in the right size that will fit on a single page. Hope that helps...

Download a file from NodeJS Server using Express

Use res.download()

It transfers the file at path as an “attachment”. For instance:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

How to link an input button to a file select window?

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ - simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

Find and replace with sed in directory and sub directories

Since there are also macOS folks reading this one (as I did), the following code worked for me (on 10.14)

egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @

All other answers using -i and -e do not work on macOS.

Source

KeyListener, keyPressed versus keyTyped

Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

Dynamically access object property using variable

const something = { bar: "Foobar!" };
const foo = 'bar';

something[\`${foo}\`];

Error while trying to retrieve text for error ORA-01019

You can refer to this link.

Install ODAC 64 bit driver using CMD after install ODAC 32 bit:

  1. Go to ODAC bit folder where install.bat file is located using CMD.
  2. Type install.bat all c:/oracle odac command and press Enter.

    Installation file will be located at “c:/oracle” folder.

When installing Oracle 11g client 32 and 64 bit, you must change oracle base path: “c:/oracle”

HttpServletRequest to complete URL

Somewhat late to the party, but I included this in my MarkUtils-Web library in WebUtils - Checkstyle-approved and JUnit-tested:

import javax.servlet.http.HttpServletRequest;

public class GetRequestUrl{
    /**
     * <p>A faster replacement for {@link HttpServletRequest#getRequestURL()}
     *  (returns a {@link String} instead of a {@link StringBuffer} - and internally uses a {@link StringBuilder})
     *  that also includes the {@linkplain HttpServletRequest#getQueryString() query string}.</p>
     * <p><a href="https://gist.github.com/ziesemer/700376d8da8c60585438"
     *  >https://gist.github.com/ziesemer/700376d8da8c60585438</a></p>
     * @author Mark A. Ziesemer
     *  <a href="http://www.ziesemer.com.">&lt;www.ziesemer.com&gt;</a>
     */
    public String getRequestUrl(final HttpServletRequest req){
        final String scheme = req.getScheme();
        final int port = req.getServerPort();
        final StringBuilder url = new StringBuilder(256);
        url.append(scheme);
        url.append("://");
        url.append(req.getServerName());
        if(!(("http".equals(scheme) && (port == 0 || port == 80))
                || ("https".equals(scheme) && port == 443))){
            url.append(':');
            url.append(port);
        }
        url.append(req.getRequestURI());
        final String qs = req.getQueryString();
        if(qs != null){
            url.append('?');
            url.append(qs);
        }
        final String result = url.toString();
        return result;
    }
}

Probably the fastest and most robust answer here so far behind Mat Banik's - but even his doesn't account for potential non-standard port configurations with HTTP/HTTPS.

See also:

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

Creating a new user and password with Ansible

Just for completeness I will post the ad-hoc command using ansible since there is a catch there as well.

First try generating an encrypted password using the mkpasswd utility that is available on most Linux systems:

mkpasswd --method=SHA-512

Then try the ansible ad-hock command:

ansible all -m user -a 'name=testuser shell=/bin/bash \
     comment="Test User" password=$6$XXXX' -k -u admin --sudo

But make sure:

  1. The command is in single quotes and NOT double otherwise your password will never work
  2. You run it with --sudo or you end up with an error like (useradd: cannot lock /etc/passwd; try again later)

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Experimental decorators warning in TypeScript compilation

I've to add the following in the settings.json file of vscode to remove the warning.

"javascript.implicitProjectConfig.experimentalDecorators": true

VSCode -> Preferences -> Settings

enter image description here

UPDATE

As Clepsyd pointed out, this setting had been deprecated. You need to use now

"js/ts.implicitProjectConfig.experimentalDecorators":true

enter image description here

@HostBinding and @HostListener: what do they do and what are they for?

Theory with less Jargons

@Hostlistnening deals basically with the host element say (a button) listening to an action by a user and performing a certain function say alert("Ahoy!") while @Hostbinding is the other way round. Here we listen to the changes that occurred on that button internally (Say when it was clicked what happened to the class) and we use that change to do something else, say emit a particular color.

Example

Think of the scenario that you would like to make a favorite icon on a component, now you know that you would have to know whether the item has been Favorited with its class changed, we need a way to determine this. That is exactly where @Hostbinding comes in.

And where there is the need to know what action actually was performed by the user that is where @Hostlistening comes in

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Works for any number from 0 to 999999999.

This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.

#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"",       "one",       "two",      "three",
                         "four",    "five",      "six",      "seven",
                         "eight",   "nine",      "ten",      "eleven",
                         "twelve",  "thirteen",  "fourteen", "fifteen",
                         "sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"",     "ten",   "twenty",  "thirty", "forty",
                         "fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
  cout << "Enter the number:";
  cin >> input;
  nFake = input;
  buffer = 0;
  while (nFake) {
    part[buffer] = nFake % 1000;
    nFake /= 1000;
    buffer++;
  }
  if (buffer == 0) {
    cout << "Zero.";
  } else if (buffer == 1) {
    convert(part[0]);
  } else if (buffer == 2) {
    convert(part[1]);
    cout << " thousand,";
    convert(part[0]);
  } else {
    convert(part[2]);
    cout << " million,";

    if (part[1]) {
      convert(part[1]);
      cout << " thousand,";
    } else {
      cout << "";
    }
    convert(part[0]);
  }
  system("pause");
  return (0);
}

void convert(int funcVar) {
  buffer = 0;
  if (funcVar >= 100) {
    a = funcVar / 100;
    b = funcVar % 100;
    if (b)
      cout << " " << ones[a] << " hundred and";
    else
      cout << " " << ones[a] << " hundred ";
    if (b < 20)
      cout << " " << ones[b];
    else {
      c = b / 10;
      cout << " " << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  } else {
    b = funcVar;
    if (b < 20)
      cout << ones[b];
    else {
      c = b / 10;
      cout << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  }
}

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to load all modules in a folder?

I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from http://pypi.python.org/pypi/automodinit/.

Usage is like this:

  1. Include the automodinit package into your setup.py dependencies.
  2. Replace all __init__.py files like this:
__all__ = ["I will get rewritten"]
# Don't modify the line above, or this line!
import automodinit
automodinit.automodinit(__name__, __file__, globals())
del automodinit
# Anything else you want can go after here, it won't get modified.

That's it! From now on importing a module will set __all__ to a list of .py[co] files in the module and will also import each of those files as though you had typed:

for x in __all__: import x

Therefore the effect of "from M import *" matches exactly "import M".

automodinit is happy running from inside ZIP archives and is therefore ZIP safe.

Niall

XDocument or XmlDocument

I am surprised none of the answers so far mentions the fact that XmlDocument provides no line information, while XDocument does (through the IXmlLineInfo interface).

This can be a critical feature in some cases (for example if you want to report errors in an XML, or keep track of where elements are defined in general) and you better be aware of this before you happily start to implement using XmlDocument, to later discover you have to change it all.

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Batch file: Find if substring is in string (not in a file)

The solutions that search a file for a substring can also search a string, eg. find or findstr.
In your case, the easy solution would be to pipe a string into the command instead of supplying a filename eg.

case-sensitive string:
echo "abcdefg" | find "bcd"

ignore case of string:
echo "abcdefg" | find /I "bcd"

IF no match found, you will get a blank line response on CMD and %ERRORLEVEL% set to 1

Trying to embed newline in a variable in bash

var="a b c"
for i in $var
do
   p=`echo -e "$p"'\n'$i`
done
echo "$p"

The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.

Ignore parent padding

Your parent is 120px wide - that is 100 width + 20 padding on each side so you need to make your line 120px wide. Here's the code. Next time note that padding adds up to element width.

#parent
{
    width: 100px;
    padding: 10px;
    background-color: Red;
}

hr
{
    width: 120px;
    margin:0 -10px;
    position:relative;
}

How can I count the numbers of rows that a MySQL query returned?

> SELECT COUNT(*) AS total FROM foo WHERE bar= 'value';

Ubuntu: OpenJDK 8 - Unable to locate package

As you can see I only have java 1.7 installed (on a Ubuntu 14.04 machine).

update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64

To install Java 8, I did,

sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk

Afterwards, now I have java 7 and 8,

update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64

BONUS ADDED (how to switch between different versions)

  • run the follwing command from the terminal:

sudo update-alternatives --config java

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      auto mode
  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      manual mode
* 2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1069      manual mode

Press enter to keep the current choice[*], or type selection number:

As you can see I'm running open jdk 8. To switch to to jdk 7, press 1 and hit the Enter key. Do the same for javac as well with, sudo update-alternatives --config javac.

Check versions to confirm the change: java -version and javac -version.

Rails Model find where not equal

You should always include the table name in the SQL query when dealing with associations.

Indeed if another table has the user_id column and you join both tables, you will have an ambiguous column name in the SQL query (i.e. troubles).

So, in your example:

GroupUser.where("groups_users.user_id != ?", me)

Or a bit more verbose:

GroupUser.where("#{table_name}.user_id IS NOT ?", me)

Note that if you are using a hash, you don't need to worry about that because Rails takes care of it for you:

GroupUser.where(user: me)

In Rails 4, as said by @dr4k3, the query method not has been added:

GroupUser.where.not(user: me)

Clear form fields with jQuery

None of the above works on a simple case when the page includes a call to web user control that involves IHttpHandler request processing (captcha). After sending the requsrt (for image processing) the code below does not clear the fields on the form (before sending the HttpHandler request ) everythings works correctly.

<input type="reset"  value="ClearAllFields" onclick="ClearContact()" />

 <script type="text/javascript">
       function ClearContact() {
           ("form :text").val("");
       }
    </script>

How to press/click the button using Selenium if the button does not have the Id?

In Selenium IDE you can do:

Command   |   clickAndWait
Target    |   //input[@value='Next' and @title='next']

It should work fine.

How to remove all listeners in an element?

I think that the fastest way to do this is to just clone the node, which will remove all event listeners:

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.

How to recursively download a folder via FTP on Linux

If you want to stick to command line FTP, you should try NcFTP. Then you can use get -R to recursively get a folder. You will also get completion.

Finding what branch a Git commit came from

A poor man's option is to use the tool tig1 on HEAD, search for the commit, and then visually follow the line from that commit back up until a merge commit is seen. The default merge message should specify what branch is getting merged to where :)

1 Tig is an ncurses-based text-mode interface for Git. It functions mainly as a Git repository browser, but it can also assist in staging changes for commit at chunk level and act as a pager for output from various Git commands.

Passing by reference in C

What you are doing is pass by value not pass by reference. Because you are sending the value of a variable 'p' to the function 'f' (in main as f(p);)

The same program in C with pass by reference will look like,(!!!this program gives 2 errors as pass by reference is not supported in C)

#include <stdio.h>

void f(int &j) {    //j is reference variable to i same as int &j = i
  j++;
}

int main() {
  int i = 20;
  f(i);
  printf("i = %d\n", i);

  return 0;
}

Output:-

3:12: error: expected ';', ',' or ')' before '&' token
             void f(int &j);
                        ^
9:3:  warning: implicit declaration of function 'f'
               f(a);
               ^

How do I get an apk file from an Android device?

All these answers require multiple steps for each apk file retrieved from the device. 1. determine package name, 2. find the file, and 3. download it. I built a simple apk_grabber python script to do this for any app that matches a given regex, and then decompiles those apks into jar files.

What is the copy-and-swap idiom?

There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....

What is the copy-and-swap idiom?

A way of implementing the assignment operator in terms of a swap function:

X& operator=(X rhs)
{
    swap(rhs);
    return *this;
}

The fundamental idea is that:

  • the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)

  • that acquisition can be attempted before modifying the current state of the object (i.e. *this) if a copy of the new value is made, which is why rhs is accepted by value (i.e. copied) rather than by reference

  • swapping the state of the local copy rhs and *this is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)

When should it be used? (Which problems does it solve [/create]?)

  • When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap with strong exception guarantee, and ideally one that can't fail/throw..†

  • When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap and destructor functions.

    • Self-assignment done as a copy-and-swap avoids oft-overlooked edge cases.‡

  • When any performance penalty or momentarily higher resource usage created by having an extra temporary object during the assignment is not important to your application. ?

swap throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp; and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string's as James comments on another answer:

@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24


‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x); code where f is (perhaps only for some #ifdef branches) a macro ala #define f(x) x or a function returning a reference to x, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;). For example:

struct X
{
    T* p_;
    size_t size_;
    X& operator=(const X& rhs)
    {
        delete[] p_;  // OUCH!
        p_ = new T[size_ = rhs.size_];
        std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
    }
    ...
};

On self-assignment, the above code delete's x.p_;, points p_ at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy attempts a self-assignment to every just-destructed 'T'!


? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):

struct Client
{
    IP_Address ip_address_;
    int socket_;
    X(const X& rhs)
      : ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
    { }
};

Here, a hand-written Client::operator= might check if *this is already connected to the same server as rhs (perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).

Flask-SQLalchemy update a row's information

This does not work if you modify a pickled attribute of the model. Pickled attributes should be replaced in order to trigger updates:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from pprint import pprint

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqllite:////tmp/users.db'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.PickleType())

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()

# Create a user.
bob = User('Bob', {})
db.session.add(bob)
db.session.commit()

# Retrieve the row by its name.
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Modifying data is ignored.
bob.data['foo'] = 123
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {}

# Replacing data is respected.
bob.data = {'bar': 321}
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

# Modifying data is ignored.
bob.data['moo'] = 789
db.session.commit()
bob = User.query.filter_by(name='Bob').first()
pprint(bob.data)  # {'bar': 321}

Maven: how to override the dependency added by a library

I also had trouble overruling a dependency in a third party library. I used scot's approach with the exclusion but I also added the dependency with the newer version in the pom. (I used Maven 3.3.3)

So for the stAX example it would look like this:

<dependency>
  <groupId>a.group</groupId>
  <artifactId>a.artifact</artifactId>
  <version>a.version</version>
  <exclusions>
    <!--  STAX comes with Java 1.6 -->
    <exclusion>
      <artifactId>stax-api</artifactId>
      <groupId>javax.xml.stream</groupId>
    </exclusion>
    <exclusion>
      <artifactId>stax-api</artifactId>
      <groupId>stax</groupId>
    </exclusion>
  </exclusions>
<dependency>

<dependency>
    <groupId>javax.xml.stream</groupId>
    <artifactId>stax-api</artifactId>
    <version>1.0-2</version>
</dependency>

White space showing up on right side of page when background image should extend full length of page

I see the question has been answered to a general standard, but when I looked at your site I noticed there is still a horizontal scroll-bar. I also notice the reason for this: You have used the code:

.homepageconference .container {
padding-left: 12%;
}

which is being used alongside code stating that the element has a width of 100%, causing an element with a total width of 112% of screen size. To fix this, either remove the padding, replace the padding with a margin of 12% for the same effect, or change the width (or max-width) of the element to 88%. This occurs in main.css at line 343. Hope this helps!

Unit testing void methods?

Test its side-effects. This includes:

  • Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
  • Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)
  • Does it have the right effect on the state of the object/type you're calling it on?

Of course, there's a limit to how much you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Lot's of great answer. I just want to add a small note about decoupling the stream.

cin.tie(NULL);

I have faced an issue while decoupling the stream with CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.

So, If anyone wants to untie the stream, the output stream must be flushed.

Edit: I am not familiar with all the platform but this is what I have experienced.

jQuery append() vs appendChild()

appendChild is a pure javascript method where as append is a jQuery method.

Android Studio - Importing external Library/Jar

I had the problem not able to load jar file in libs folder in Android Studio. If you have added JAR file in libs folder, then just open build.gradle file and save it without editing anything else. If you have added this line

compile fileTree(dir: 'libs', include: ['*.jar'])

save it and clean the project .. In next build time Android Studio will load the JAR file.

Hope this helps.

MySQL: Quick breakdown of the types of joins

Full Outer join don't exist in mysql , you might need to use a combination of left and right join.

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

Regex to validate date format dd/mm/yyyy

For use only for the day:

<input placeholder="day" maxlength="2" minlength="1" formControlName="birthDay" 
   name="birthDay"pattern="(0[1-9]|1[0-9]|2[0-9]|3[0-1])" >/

For use only for the month:

 <input placeholder="month" maxlength="2" minlength="1" 
  formControlName="month" name="month" formControlName="month" name="month" pattern="(0[1- 
  9]|1[0-2])">/

How to utilize date add function in Google spreadsheet?

I like to keep it simple. If A1 holds the date and B1 holds the number of months to add, then

=date(year(A1),month(A1)+B1,day(A1))

would calculate the required result. The same way could be used for days or years

Can I use return value of INSERT...RETURNING in another INSERT?

You can do so starting with Postgres 9.1:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows

In the meanwhile, if you're only interested in the id, you can do so with a trigger:

create function t1_ins_into_t2()
  returns trigger
as $$
begin
  insert into table2 (val) values (new.id);
  return new;
end;
$$ language plpgsql;

create trigger t1_ins_into_t2
  after insert on table1
for each row
execute procedure t1_ins_into_t2();

Unknown Column In Where Clause

For me the root of the problem was a number which I copied to use in a WHERE clause. The number had "invisible" symbol, at least for MySQL Workbench. I placed the number in the Chrome console it was clearly visible.

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

How do you test that a Python function throws an exception?

While all the answers are perfectly fine, I was looking for a way to test if a function raised an exception without relying on unit testing frameworks and having to write test classes.

I ended up writing the following:

def assert_error(e, x):
    try:
        e(x)
    except:
        return
    raise AssertionError()

def failing_function(x):
    raise ValueError()

def dummy_function(x):
    return x

if __name__=="__main__":
    assert_error(failing_function, 0)
    assert_error(dummy_function, 0)

And it fails on the right line :

Traceback (most recent call last):
  File "assert_error.py", line 16, in <module>
    assert_error(dummy_function, 0)
  File "assert_error.py", line 6, in assert_error
    raise AssertionError()
AssertionError

Image style height and width not taken in outlook mails

Put the width and height in separate attributes, with no unit:

<img style="margin: 0; border: 0; padding: 0; display: block;"
src="images/img.jpg" width="120" height="150">

Another Option:

<!--[if gte mso 9]>
<style type="text/css">
img.header { width: 600px; } /* or something like that */
</style>
<![endif]-->

How to convert a string to an integer in JavaScript?

Please see the below example.It will help clear your doubt

Example                  Result

parseInt("4")            4
parseInt("5aaa")         5
parseInt("4.33333")      4
parseInt("aaa");         NaN (means "Not a Number")

by using parseint function It will only give op of integer present and not the string

Show just the current branch in Git

For completeness, echo $(__git_ps1), on Linux at least, should give you the name of the current branch surrounded by parentheses.

This may be useful is some scenarios as it is not a Git command (while depending on Git), notably for setting up your Bash command prompt to display the current branch.

For example:

/mnt/c/git/ConsoleApp1 (test-branch)> echo $(__git_ps1)
(test-branch)
/mnt/c/git/ConsoleApp1 (test-branch)> git checkout master
Switched to branch 'master'
/mnt/c/git/ConsoleApp1 (master)> echo $(__git_ps1)
(master)
/mnt/c/git/ConsoleApp1 (master)> cd ..
/mnt/c/git> echo $(__git_ps1)

/mnt/c/git>

Proper way to catch exception from JSON.parse

This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.

Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
    console.log(json);
}).catch(err => {
    console.log(err);
});

Unable to connect with remote debugger

In my case, selecting Debug JS Remotely launched Chrome, but did not connect with the android device. Normally, the new Chrome tab/window would have the debugging URL pre-populated in the address bar, but in this case the address bar was blank. After the timeout period, the "Unable to connect with remote debugger" error message was displayed. I fixed this with the following procedure:

  • Run adb reverse tcp:8081 tcp:8081
  • Paste http://localhost:8081/debugger-ui into the address field of my Chrome browser. You should see the normal debugging screen but your app will still not be connected.

That should fix the problem. If not, you may need to take the following additional steps:

  • Close and uninstall the app from your Android device
  • Reinstall the app with react-native run-android
  • Enable remote debugging on your app.
  • Your app should now be connected to the debugger.

%matplotlib line magic causes SyntaxError in Python script

This is the case you are using Julia:

The analogue of IPython's %matplotlib in Julia is to use the PyPlot package, which gives a Julia interface to Matplotlib including inline plots in IJulia notebooks. (The equivalent of numpy is already loaded by default in Julia.) Given PyPlot, the analogue of %matplotlib inline is using PyPlot, since PyPlot defaults to inline plots in IJulia.

Select where count of one field is greater than one

I give an example up on Group By between two table in Sql:

Select cn.name,ct.name,count(ct.id) totalcity from city ct left join country cn on ct.countryid = cn.id Group By cn.name,ct.name Having totalcity > 2


How to determine if binary tree is balanced?

To have a better performance specially on huge trees you can save the height in each node so it is a trade off space Vs performance:

class Node {
    Node left;
    Node right;
    int value;
    int height;
}

Example of implementing the addition and same for deletion

void addNode(Node root,int v)
{    int height =0;
     while(root != null)
     {
         // Since we are adding new node so the height 
         // will increase by one in each node we will pass by
         root.height += 1;
         height++;
         else if(v > root.value){
            root = root.left();
            }
         else{
         root = root.right();
         }

     }

         height++;
         Node n = new Node(v , height);
         root = n;         
}
int treeMaxHeight(Node root)
{
 return Math.Max(root.left.height,root.right.height);
}

int treeMinHeight(Node root)
{
 return Math.Min(root.left.height,root.right.height);

}

Boolean isNodeBlanced(Node root)
{
   if (treeMaxHeight(root) - treeMinHeight(root) > 2)
       return false;

  return true;
}

Boolean isTreeBlanced (Node root)
{
    if(root == null || isTreeBalanced(root.left) && isTreeBalanced(root.right) && isNodeBlanced(root))
    return true;

  return false;

}

Java, How to specify absolute value and square roots

import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

Swift Alamofire: How to get the HTTP response status code

I needed to know how to get the actual error code number.

I inherited a project from someone else and I had to get the error codes from a .catch clause that they had previously setup for Alamofire:

} .catch { (error) in

    guard let error = error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
}

Or if you need to get it from the response value follow @mbryzinski's answer

Alamofire ... { (response) in

    guard let error = response.result.error as? AFError else { return }
    guard let statusCode = error.responseCode else { return }

    print("Alamofire statusCode num is: ", statusCode)
})

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

Indirectly referenced from required .class file

This issue happen because of few jars are getting references from other jar and reference jar is missing .

Example : Spring framework

Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem

In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

Spring-bean.jar is missing

Once you add dependency in your class path issue will resolve.

Firebase (FCM) how to get token

FASTEST AND GOOD FOR PROTOTYPE

The quick solution is to store it in sharedPrefs and add this logic to onCreate method in your MainActivity or class which is extending Application.

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken", newToken);
    getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("fb", newToken).apply();
});

Log.d("newToken", getActivity().getPreferences(Context.MODE_PRIVATE).getString("fb", "empty :("));

CLEANER WAY

A better option is to create a service and keep inside a similar logic. Firstly create new Service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("newToken", s);
        getSharedPreferences("_", MODE_PRIVATE).edit().putString("fb", s).apply();
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

    public static String getToken(Context context) {
        return context.getSharedPreferences("_", MODE_PRIVATE).getString("fb", "empty");
    }
}

And then add it to AndroidManifest file

<service
        android:name=".MyFirebaseMessagingService"
        android:stopWithTask="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
</service>

Finally, you are able to use a static method from your Service MyFirebaseMessagingService.getToken(Context);

THE FASTEST BUT DEPRECATED

Log.d("Firebase", "token "+ FirebaseInstanceId.getInstance().getToken());

It's still working when you are using older firebase library than version 17.x.x

How to install APK from PC?

Airdroid , android market install the app on android then go onto the computer type in the address given, type in the password given (or scan the QR code). Go to settings and under security (if your running the new ICS or Jellybean) or go to settings->apps->managment and select unknown sources(for gingerbread) then click on (I think) speed install, or something along those lines. it will be on the top of the page slightly towards the left. drag and drop as many .apks as you want then on you android just tap the install buttons that appear. Airdroid is wonderful and does a lot more than just apks.

PHP ini file_get_contents external url

The is related to the ini configuration setting allow_url_fopen.

You should be aware that enable that option may make some bugs in your code exploitable.

For instance, this failure to validate input may turn into a full-fledged remote code execution vulnerability:

copy($_GET["file"], "."); 

Math functions in AngularJS bindings

That doesn't look like a very Angular way of doing it. I'm not entirely sure why it doesn't work, but you'd probably need to access the scope in order to use a function like that.

My suggestion would be to create a filter. That's the Angular way.

myModule.filter('ceil', function() {
    return function(input) {
        return Math.ceil(input);
    };
});

Then in your HTML do this:

<p>The percentage is {{ (100*count/total) | ceil }}%</p>

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

How to do while loops with multiple conditions

Have you noticed that in the code you posted, condition2 is never set to False? This way, your loop body is never executed.

Also, note that in Python, not condition is preferred to condition == False; likewise, condition is preferred to condition == True.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Even after enabling Intel Virtualization Technology (Intel VT-x), I got the error message ' dev/kvm not found ' in Android Studio.by making Hyper-V feature off in Windows 8.1 issue was fixed.

here is how to access Windows Hyper-V feature

Control Panel -> Programs and Features -> Turn Windows features on and off.

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

length and length() in Java

Consider:

int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();

myArray.length    // Gives the length of the array
myString.length() // Gives the length of the string
myList.size()     // Gives the length of the list

It's very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally, a method, length(), was used to avoid duplication of the same information. Another is that using a method length() helps emphasize the immutability of strings, even though the size of an array is also unchangeable.

Ultimately this is just an inconsistency that evolved that would definitely be fixed if the language were ever redesigned from the ground up. As far as I know no other languages (C#, Python, Scala, etc.) do the same thing, so this is likely just a slight flaw that ended up as part of the language.

You'll get an error if you use the wrong one anyway.

SOAP PHP fault parsing WSDL: failed to load external entity?

I had the same problem, I succeeded by adding:

new \SoapClient(URI WSDL OR NULL if non-WSDL mode, [
    'cache_wsdl' => WSDL_CACHE_NONE, 
    'proxy_host' => 'URL PROXY',
    'proxy_port' => 'PORT PROXY'
]);

Hope this help :)

Disable click outside of bootstrap modal area to close modal

data-keyboard="false" data-backdrop="static" in your html code for start of modal Box div

Including one C source file in another?

You can properly include .C or .CPP files into other source files. Depending on your IDE, you can usually prevent double-linkage by looking at the source files properties you want to be included, usually by right clicking on it and clicking properties, and uncheck/check compile/link/exclude from build or whatever option it may be. Or you could not include the file in the project itself, thus the IDE wont even know it exists and wont try to compile it. And with makefiles you simply just wouldn't put the file in it for compiling and linking.

EDIT: Sorry I made it an answer instead of a reply onto other answers :(