Programs & Examples On #Html entities

HTML entities provide a method of entering characters that cannot be expressed in the document's character encoding or that cannot easily be entered on a keyboard.

HTML entity for the middle dot

There's actually seven variants of this:

    char   description          unicode   html       html entity    utf-8

    ·      Middle Dot           U+00B7    ·     ·       C2 B7
    ·      Greek Ano Teleia     U+0387    ·                    CE 87
    •      Bullet               U+2022    •    •         E2 80 A2
    ‧      Hyphenation Point    U+2027    ₁                   E2 80 A7
    ∙      Bullet Operator      U+2219    ∙                   E2 88 99
    ●      Black Circle         U+25CF    ●                   E2 97 8F
    ⬤     Black Large Circle   U+2B24    ⬤                  E2 AC A4

Depending on your viewing application or font, the Bullet Operator may seem very similar to either the Middle Dot or the Bullet.

How to create string with multiple spaces in JavaScript

You can use the <pre> tag with innerHTML. The HTML <pre> element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written. If you don't want a different font, simply add pre as a selector in your CSS file and style it as desired.

Ex:

var a = '<pre>something        something</pre>';
document.body.innerHTML = a;

How to convert characters to HTML entities using plain JavaScript

All the other solutions suggested here, as well as most other JavaScript libraries that do HTML entity encoding/decoding, make several mistakes:

For a robust solution that avoids all these issues, use a library I wrote called he for this. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

HTML character codes for this ? or this ?

The Big and small black triangles facing the 4 directions can be represented thus:

&#x25B2;

&#x25B4;

&#x25B6;

&#x25B8;

&#x25BA;

&#x25BC;

&#x25BE;

&#x25C0;

&#x25C2;

&#x25C4;

Uses for the '&quot;' entity in HTML

As other answers pointed out, it is most likely generated by some tool.

But if I were the original author of the file, my answer would be: Consistency.

If I am not allowed to put double quotes in my attributes, why put them in the element's content ? Why do these specs always have these exceptional cases .. If I had to write the HTML spec, I would say All double quotes need to be encoded. Done.

Today it is like In attribute values we need to encode double quotes, except when the attribute value itself is defined by single quotes. In the content of elements, double quotes can be, but are not required to be, encoded. (And I am surely forgetting some cases here).

Double quotes are a keyword of the spec, encode them. Lesser/greater than are a keyword of the spec, encode them. etc..

Which characters need to be escaped in HTML?

It depends upon the context. Some possible contexts in HTML:

  • document body
  • inside common attributes
  • inside script tags
  • inside style tags
  • several more!

See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.

Adding HTML entities using CSS content

Use the hex code for a non-breaking space. Something like this:

.breadcrumbs a:before {
    content: '>\00a0';
}

How to Code Double Quotes via HTML Codes

There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.

There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello &quot;world&quot;"), and even then, there are almost always better options (like title='Hello "word"' or title="Hello “word”".

If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like &quot; to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.

What's the right way to decode a string that has special HTML entities in it?

This is so good answer. You can use this with angular like this:

 moduleDefinitions.filter('sanitize', ['$sce', function($sce) {
    return function(htmlCode) {
        var txt = document.createElement("textarea");
        txt.innerHTML = htmlCode;
        return $sce.trustAsHtml(txt.value);
    }
}]);

What do &lt; and &gt; stand for?

Others have noted the correct answer, but have not clearly explained the all-important reason:

  • why do we need this?

What do < and > stand for?

  • &lt; stands for the < sign. Just remember: lt == less than
  • &gt; stands for the > Just remember: gt == greater than

Why can’t we simply use the < and > characters in HTML?

  • This is because the > and < characters are ‘reserved’ characters in HTML.
  • HTML is a mark up language: The < and > are used to denote the starting and ending of different elements: e.g. <h1> and not for the displaying of the greater than or less than symbols. But what if you wanted to actually display those symbols? You would simply use &lt; and &gt; and the browser will know exactly how to display it.

Convert HTML Character Back to Text Using Java Standard Library

I think the Apache Commons Lang library's StringEscapeUtils.unescapeHtml3() and unescapeHtml4() methods are what you are looking for. See https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html.

Decode HTML entities in Python string?

I had a similar encoding issue. I used the normalize() method. I was getting a Unicode error using the pandas .to_html() method when exporting my data frame to an .html file in another directory. I ended up doing this and it worked...

    import unicodedata 

The dataframe object can be whatever you like, let's call it table...

    table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
    table.index+= 1

encode table data so that we can export it to out .html file in templates folder(this can be whatever location you wish :))

     #this is where the magic happens
     html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')

export normalized string to html file

    file = open("templates/home.html","w") 

    file.write(html_data) 

    file.close() 

Reference: unicodedata documentation

Is there Unicode glyph Symbol to represent "Search"

Use the ? symbol (encoded as &#9906; or &#x26B2;), and rotate it to achieve the desired effect:

<div style="-webkit-transform: rotate(45deg); 
               -moz-transform: rotate(45deg); 
                 -o-transform: rotate(45deg);
                    transform: rotate(45deg);">
    &#9906;
</div>

It rotates a symbol :)

Replacing &nbsp; from javascript dom text node

I think when you define a function with "var foo = function() {...};", the function is only defined after that line. In other words, try this:

var replaceHtmlEntites = (function() {
  var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
  var translate = {
    "nbsp": " ",
    "amp" : "&",
    "quot": "\"",
    "lt"  : "<",
    "gt"  : ">"
  };
  return function(s) {
    return ( s.replace(translate_re, function(match, entity) {
      return translate[entity];
    }) );
  }
})();

var cleanText = text.replace(/^\xa0*([^\xa0]*)\xa0*$/g,"");
cleanText = replaceHtmlEntities(text);

Edit: Also, only use "var" the first time you declare a variable (you're using it twice on the cleanText variable).

Edit 2: The problem is the spelling of the function name. You have "var replaceHtmlEntites =". It should be "var replaceHtmlEntities ="

How to round to 2 decimals with Python?

If you need not only round result but elso do math operations with round result, then you can use decimal.Decimal https://docs.python.org/2/library/decimal.html

from decimal import Decimal, ROUND_DOWN

Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32') 

What does the "On Error Resume Next" statement do?

It basically tells the program when you encounter an error just continue at the next line.

Iterate over values of object

It's not a map. It's simply an Object.

Edit: below code is worse than OP's, as Amit pointed out in comments.

You can "iterate over the values" by actually iterating over the keys with:

var value;
Object.keys(map).forEach(function(key) {
    value = map[key];
    console.log(value);
});

How to Auto-start an Android Application?

Edit your AndroidManifest.xml to add RECEIVE_BOOT_COMPLETED permission

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

Edit your AndroidManifest.xml application-part for below Permission

<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Now write below in Activity.

public class BootUpReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyActivity.class);  
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);  
    }
}

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

I combined some of Flavio's answer to this small solution.

.hidden-ul-bullets li {
    list-style: none;
}
.hidden-ul-bullets ul {
    margin-left: 0.25em; // for my purpose, a little indentation is wished
}

The decision about bullets is made at an enclosing element, typically a div. The drawback (or todo) of my solution is that the liststyle removal also applies to ordered lists.

jQuery duplicate DIV into another DIV

Put this on an event

$(function(){
    $('.package').click(function(){
       var content = $('.container').html();
       $(this).html(content);
    });
});

PHP new line break in emails

I know this is an old question but anyway it might help someone.

I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).

echo "line 1".PHP_EOL."line 2".PHP_EOL;

If you're planning to show the result in a browser then you have to use "<br>".

EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.

Access to the path denied error in C#

tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.

I have come across this error in my travels trying to read in an XML file. I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.

File details:

  • The path and file name are valid, the file exists
  • Both the service account and the logged in user have Full Control permissions to the file and the full path
  • The file is marked as Read-Only
  • It is running on Windows Server 2008 R2
  • The path to the file was using local drive letters, not UNC path

When trying to read the file programmatically, the following behavior was observed while running the exact same code:

  • When running as the logged in user, the file is read with no error
  • When running as the service account, trying to read the file generates the Access Is Denied error with no details

In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));

How does Trello access the user's clipboard?

Something very similar can be seen on http://goo.gl when you shorten the URL.

There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.

When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)

How to delete a character from a string using Python

In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears:

newstr = oldstr.replace("M", "")

If you want to remove the central character:

midlen = len(oldstr)/2   # //2 in python 3
newstr = oldstr[:midlen] + oldstr[midlen+1:]

You asked if strings end with a special character. No, you are thinking like a C programmer. In Python, strings are stored with their length, so any byte value, including \0, can appear in a string.

Grep to find item in Perl array

You can also check single value in multiple arrays like,

if (grep /$match/, @array, @array_one, @array_two, @array_Three)
{
    print "found it\n";
}

How to check if two words are anagrams

let's take a question: Given two strings s and t, write a function to determine if t is an anagram of s.

For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false.

Method 1(Using HashMap ):

public class Method1 {

    public static void main(String[] args) {
        String a = "protijayi";
        String b = "jayiproti";
        System.out.println(isAnagram(a, b ));// output => true

    }

    private static boolean isAnagram(String a, String b) {
        Map<Character ,Integer> map = new HashMap<>();
        for( char c : a.toCharArray()) {
            map.put(c,    map.getOrDefault(c, 0 ) + 1 );
        }
        for(char c : b.toCharArray()) {
            int count = map.getOrDefault(c, 0);
            if(count  == 0 ) {return false ; }
            else {map.put(c, count - 1 ) ; }
        }
        
        return true;
    }

}

Method 2 :

public class Method2 {
public static void main(String[] args) {
    String a = "protijayi";
    String b = "jayiproti";

    
    System.out.println(isAnagram(a, b));// output=> true
}

private static boolean isAnagram(String a, String b) {
   
    
    int[] alphabet = new int[26];
    for(int i = 0 ; i < a.length() ;i++) {
         alphabet[a.charAt(i) - 'a']++ ;
    }
    for (int i = 0; i < b.length(); i++) {
         alphabet[b.charAt(i) - 'a']-- ;
    }
    
    for(  int w :  alphabet ) {
         if(w != 0 ) {return false;}
    }
    return true;
    
}
}

Method 3 :

public class Method3 {
public static void main(String[] args) {
    String a = "protijayi";
    String b = "jayiproti";
    
    
    System.out.println(isAnagram(a, b ));// output => true
}

private static boolean isAnagram(String a, String b) {
    char[] ca = a.toCharArray() ;
    char[] cb = b.toCharArray();
    Arrays.sort(   ca     );
    
    Arrays.sort(   cb        );
    return Arrays.equals(ca , cb );
}
}

Method 4 :

public class AnagramsOrNot {
    public static void main(String[] args) {
        String a = "Protijayi";
        String b = "jayiProti";
        isAnagram(a, b);
    }

    private static void isAnagram(String a, String b) {
        Map<Integer, Integer> map = new LinkedHashMap<>();

        a.codePoints().forEach(code -> map.put(code, map.getOrDefault(code, 0) + 1));
        System.out.println(map);
        b.codePoints().forEach(code -> map.put(code, map.getOrDefault(code, 0) - 1));
        System.out.println(map);
        if (map.values().contains(0)) {
            System.out.println("Anagrams");
        } else {
            System.out.println("Not Anagrams");
        }
    }
}

In Python:

def areAnagram(a, b):
    if len(a) != len(b): return False
    count1 = [0] * 256
    count2 = [0] * 256
    for i in a:count1[ord(i)] += 1
    for i in b:count2[ord(i)] += 1

    for i in range(256):
        if(count1[i] != count2[i]):return False    

    return True


str1 = "Giniiii"
str2 = "Protijayi"
print(areAnagram(str1, str2))

Let's take another famous Interview Question: Group the Anagrams from a given String:

public class GroupAnagrams {
    public static void main(String[] args) {
        String a = "Gini Gina Protijayi iGin aGin jayiProti Soudipta";
        Map<String, List<String>> map = Arrays.stream(a.split(" ")).collect(Collectors.groupingBy(GroupAnagrams::sortedString));
        System.out.println("MAP => " + map);
        map.forEach((k,v) -> System.out.println(k +" and the anagrams are =>" + v ));
        /*
         Look at the Map output:
        MAP => {Giin=[Gini, iGin], Paiijorty=[Protijayi, jayiProti], Sadioptu=[Soudipta], Gain=[Gina, aGin]}
        As we can see, there are multiple Lists. Hence, we have to use a flatMap(List::stream)
        Now, Look at the output:
        Paiijorty and the anagrams are =>[Protijayi, jayiProti]
       
        Now, look at this output:
        Sadioptu and the anagrams are =>[Soudipta]
        List contains only word. No anagrams.
        That means we have to work with map.values(). List contains all the anagrams.
        
                     
        */
        String stringFromMapHavingListofLists = map.values().stream().flatMap(List::stream).collect(Collectors.joining(" "));
        System.out.println(stringFromMapHavingListofLists);
    }

    public static String sortedString(String a) {
        String sortedString = a.chars().sorted()
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();

        return sortedString;

    }
    
    /*
     * The output : Gini iGin Protijayi jayiProti Soudipta Gina aGin
     * All the anagrams are side by side.
     */
}

Now to Group Anagrams in Python is again easy.We have to : Sort the lists. Then, Create a dictionary. Now dictionary will tell us where are those anagrams are( Indices of Dictionary). Then values of the dictionary is the actual indices of the anagrams.

def groupAnagrams(words):
 
    # sort each word in the list
    A = [''.join(sorted(word)) for word in words]
    dict = {}
    for indexofsamewords, names in enumerate(A):
     dict.setdefault(names, []).append(indexofsamewords)
    print(dict)
    #{'AOOPR': [0, 2, 5, 11, 13], 'ABTU': [1, 3, 4], 'Sorry': [6], 'adnopr': [7], 'Sadioptu': [8, 16], ' KPaaehiklry': [9], 'Taeggllnouy': [10], 'Leov': [12], 'Paiijorty': [14, 18], 'Paaaikpr': [15], 'Saaaabhmryz': [17], ' CNaachlortttu': [19], 'Saaaaborvz': [20]}
 
    for index in dict.values():
     print([words[i] for i in index])
 

if __name__ == '__main__':
 
    # list of words
    words = ["ROOPA","TABU","OOPAR","BUTA","BUAT" , "PAROO","Soudipta",
        "Kheyali Park", "Tollygaunge", "AROOP","Love","AOORP", "Protijayi","Paikpara","dipSouta","Shyambazaar",
        "jayiProti", "North Calcutta", "Sovabazaar"]
 
    groupAnagrams(words)
 

The Output :

['ROOPA', 'OOPAR', 'PAROO', 'AROOP', 'AOORP']
['TABU', 'BUTA', 'BUAT']
['Soudipta', 'dipSouta']
['Kheyali Park']
['Tollygaunge']
['Love']
['Protijayi', 'jayiProti']
['Paikpara']
['Shyambazaar']
['North Calcutta']
['Sovabazaar']

Another Important Anagram Question : Find the Anagram occuring Max. number of times. In the Example, ROOPA is the word which has occured maximum number of times. Hence, ['ROOPA' 'OOPAR' 'PAROO' 'AROOP' 'AOORP'] will be the final output.

from sqlite3 import collections
from statistics import mode, mean

import numpy as np


# list of words
words = ["ROOPA","TABU","OOPAR","BUTA","BUAT" , "PAROO","Soudipta",
        "Kheyali Park", "Tollygaunge", "AROOP","Love","AOORP",
         "Protijayi","Paikpara","dipSouta","Shyambazaar",
        "jayiProti", "North Calcutta", "Sovabazaar"]

print(".....Method 1....... ")

sortedwords = [''.join(sorted(word)) for word in words]
print(sortedwords)
print("...........")
LongestAnagram = np.array(words)[np.array(sortedwords) == mode(sortedwords)]
# Longest anagram 
print("Longest anagram by Method 1:")
print(LongestAnagram)

print(".....................................................")  

print(".....Method 2....... ")  

A = [''.join(sorted(word)) for word in words]

dict = {}

for indexofsamewords,samewords in  enumerate(A):
    dict.setdefault(samewords,[]).append(samewords)
#print(dict)  
#{'AOOPR': ['AOOPR', 'AOOPR', 'AOOPR', 'AOOPR', 'AOOPR'], 'ABTU': ['ABTU', 'ABTU', 'ABTU'], 'Sadioptu': ['Sadioptu', 'Sadioptu'], ' KPaaehiklry': [' KPaaehiklry'], 'Taeggllnouy': ['Taeggllnouy'], 'Leov': ['Leov'], 'Paiijorty': ['Paiijorty', 'Paiijorty'], 'Paaaikpr': ['Paaaikpr'], 'Saaaabhmryz': ['Saaaabhmryz'], ' CNaachlortttu': [' CNaachlortttu'], 'Saaaaborvz': ['Saaaaborvz']}
     
aa =  max(dict.items() , key = lambda x : len(x[1]))
print("aa => " , aa)    
word, anagrams = aa 
print("Longest anagram by Method 2:")
print(" ".join(anagrams))    

The Output :

.....Method 1....... 
['AOOPR', 'ABTU', 'AOOPR', 'ABTU', 'ABTU', 'AOOPR', 'Sadioptu', ' KPaaehiklry', 'Taeggllnouy', 'AOOPR', 'Leov', 'AOOPR', 'Paiijorty', 'Paaaikpr', 'Sadioptu', 'Saaaabhmryz', 'Paiijorty', ' CNaachlortttu', 'Saaaaborvz']
...........
Longest anagram by Method 1:
['ROOPA' 'OOPAR' 'PAROO' 'AROOP' 'AOORP']
.....................................................
.....Method 2....... 
aa =>  ('AOOPR', ['AOOPR', 'AOOPR', 'AOOPR', 'AOOPR', 'AOOPR'])
Longest anagram by Method 2:
AOOPR AOOPR AOOPR AOOPR AOOPR






















     

How to align content of a div to the bottom

Here is another solution using flexbox but without using flex-end for bottom alignment. The idea is to set margin-bottom on h1 to auto to push the remaining content to the bottom:

_x000D_
_x000D_
#header {_x000D_
  height: 350px;_x000D_
  display:flex;_x000D_
  flex-direction:column;_x000D_
  border:1px solid;_x000D_
}_x000D_
_x000D_
#header h1 {_x000D_
 margin-bottom:auto;_x000D_
}
_x000D_
<div id="header">_x000D_
  <h1>Header title</h1>_x000D_
  Header content (one or multiple lines) Header content (one or multiple lines)Header content (one or multiple lines) Header content (one or multiple lines)_x000D_
</div>
_x000D_
_x000D_
_x000D_

We can also do the same with margin-top:auto on the text but in this case we need to wrap it inside a div or span:

_x000D_
_x000D_
#header {_x000D_
  height: 350px;_x000D_
  display:flex;_x000D_
  flex-direction:column;_x000D_
  border:1px solid;_x000D_
}_x000D_
_x000D_
#header span {_x000D_
 margin-top:auto;_x000D_
}
_x000D_
<div id="header">_x000D_
  <h1>Header title</h1>_x000D_
  <span>Header content (one or multiple lines)</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ADB No Devices Found

You have to download the drivers from the SDK manager (extras ? Google USB Driver)

Then you have to install the USB driver in Windows (it works for me in Windows 8.1):

(Copy and paste from http://developer.android.com/tools/extras/oem-usb.html#InstallingDriver:)

  1. Connect your Android-powered device to your computer's USB port.
  2. Right-click on "Computer" from your desktop or Windows Explorer, and select "Manage".
  3. Select "Devices" in the left pane.
  4. Locate and expand "Other device" in the right pane.
  5. Right-click the device name (such as Nexus S) and select "Update Driver Software." This will launch the "Hardware Update Wizard".
  6. Select "Browse my computer for driver software" and click "Next." Click "Browse" and locate the USB driver folder. (The Google USB Driver is located in <sdk>\extras\google\usb_driver\.)
  7. Click "Next" to install the driver.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.

OK, the answer is easy, but read on:

col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px

The pixel numbers are the breakpoints, so for example col-xs is targeting the element when the window is smaller than 768px(likely mobile devices)...

I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6 to show you how the grid system work in the page, look at how lg, md and xs are responsive to the window size:

Bootstrap grid system, col-*-6

$("#form1").validate is not a function

youll need to use the latest http://ajax.microsoft.com/ajax/jquery.validate/1.5.5/jquery.validate.js in conjunction with one of the Microsoft's CDN for getting your validation file.

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Copying sets Java

With Java 8 you can use stream and collect to copy the items:

Set<Item> newSet = oldSet.stream().collect(Collectors.toSet());

Or you can collect to an ImmutableSet (if you know that the set should not change):

Set<Item> newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());

How can I change the font size using seaborn FacetGrid?

I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults                                                                                                         
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);

plt.show()

This is the output:

enter image description here

Using Html.ActionLink to call action on different controller

I would recommend writing these helpers using named parameters for the sake of clarity as follows:

@Html.ActionLink(
    linkText: "Details",
    actionName: "Details",
    controllerName: "Product",
    routeValues: new {
        id = item.ID
    },
    htmlAttributes: null
)

How to make a form close when pressing the escape key?

The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

How to put text in the upper right, or lower right corner of a "box" using css

The first line would consist of 3 <div>s. One outer that contains two inner <div>s. The first inner <div> would have float:left which would make sure it stays to the left, the second would have float:right, which would stick it to the right.

<div style="width:500;height:50"><br>
<div style="float:left" >stuff </div><br>
<div style="float:right" >stuff </div>

... obviously the inline-styling isn't the best idea - but you get the point.

2,3, and 4 would be single <div>s.

5 would work like 1.

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

Saving ssh key fails

If you prefer to use a GUI to create the keys

  1. Use Putty Gen to generate a key
  2. Export the key as an open SSH key
  3. As mentioned by @VonC create the .ssh directory and then you can drop the private and public keys in there
  4. Or use a GUI program (like Tortoise Git) to use the SSH keys

For a walkthrough on putty gen for the above steps, please see http://ask-leo.com/how_do_i_create_and_use_public_keys_with_ssh.html

When is a C++ destructor called?

Others have already addressed the other issues, so I'll just look at one point: do you ever want to manually delete an object.

The answer is yes. @DavidSchwartz gave one example, but it's a fairly unusual one. I'll give an example that's under the hood of what a lot of C++ programmers use all the time: std::vector (and std::deque, though it's not used quite as much).

As most people know, std::vector will allocate a larger block of memory when/if you add more items than its current allocation can hold. When it does this, however, it has a block of memory that's capable of holding more objects than are currently in the vector.

To manage that, what vector does under the covers is allocate raw memory via the Allocator object (which, unless you specify otherwise, means it uses ::operator new). Then, when you use (for example) push_back to add an item to the vector, internally the vector uses a placement new to create an item in the (previously) unused part of its memory space.

Now, what happens when/if you erase an item from the vector? It can't just use delete -- that would release its entire block of memory; it needs to destroy one object in that memory without destroying any others, or releasing any of the block of memory it controls (for example, if you erase 5 items from a vector, then immediately push_back 5 more items, it's guaranteed that the vector will not reallocate memory when you do so.

To do that, the vector directly destroys the objects in the memory by explicitly calling the destructor, not by using delete.

If, perchance, somebody else were to write a container using contiguous storage roughly like a vector does (or some variant of that, like std::deque really does), you'd almost certainly want to use the same technique.

Just for example, let's consider how you might write code for a circular ring-buffer.

#ifndef CBUFFER_H_INC
#define CBUFFER_H_INC

template <class T>
class circular_buffer {
    T *data;
    unsigned read_pos;
    unsigned write_pos;
    unsigned in_use;
    const unsigned capacity;
public:
    circular_buffer(unsigned size) :
        data((T *)operator new(size * sizeof(T))),
        read_pos(0),
        write_pos(0),
        in_use(0),
        capacity(size)
    {}

    void push(T const &t) {
        // ensure there's room in buffer:
        if (in_use == capacity) 
            pop();

        // construct copy of object in-place into buffer
        new(&data[write_pos++]) T(t);
        // keep pointer in bounds.
        write_pos %= capacity;
        ++in_use;
    }

    // return oldest object in queue:
    T front() {
        return data[read_pos];
    }

    // remove oldest object from queue:
    void pop() { 
        // destroy the object:
        data[read_pos++].~T();

        // keep pointer in bounds.
        read_pos %= capacity;
        --in_use;
    }
  
~circular_buffer() {
    // first destroy any content
    while (in_use != 0)
        pop();

    // then release the buffer.
    operator delete(data); 
}

};

#endif

Unlike the standard containers, this uses operator new and operator delete directly. For real use, you probably do want to use an allocator class, but for the moment it would do more to distract than contribute (IMO, anyway).

References with text in LaTeX

Have a look to this wiki: LaTeX/Labels and Cross-referencing:

The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:

\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...

Better way to revert to a previous SVN revision of a file?

What you're looking for is called a "reverse merge". You should consult the docs regarding the merge function in the SVN book (as luapyad, or more precisely the first commenter on that post, points out). If you're using Tortoise, you can also just go into the log view and right-click and choose "revert changes from this revision" on the one where you made the mistake.

Creating a select box with a search option

Select2 http://select2.github.io may be even better and more active than Chosen.

See this comparison: http://sitepoint.com/jquery-select-box-components-chosen-vs-select2

I went for Select2 (a few months ago) because Chosen had an issue when using Chinese characters via an IME http://github.com/harvesthq/chosen/issues/2663 It works great.

DevTools failed to load SourceMap: Could not load content for chrome-extension

That's because Chrome added support for source maps.

Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.

Then, look for Sources, and disable the options: "Enable javascript source maps" "Enable CSS source maps"

If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.

How to set a:link height/width with css?

Anchors will need to be a different display type than their default to take a height. display:inline-block; or display:block;.

Also check on line-height which might be interesting with this.

PHP Redirect with POST data

function post(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.



    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Example:

 post('url', {name: 'Johnny Bravo'});

Convert output of MySQL query to utf8

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;

Maven: mvn command not found

mvn -version

export PATH=$PATH:/opt/apache-maven-3.6.0/bin

Browser detection in JavaScript?

All the information about web browser is contained in navigator object. The name and version are there.

var appname = window.navigator.appName;

Source: javascript browser detection

How to center body on a page?

You have to specify the width to the body for it to center on the page.

Or put all the content in the div and center it.

<body>
    <div>
    jhfgdfjh
    </div>
</body>?

div {
    margin: 0px auto;
    width:400px;
}

?

Returning a pointer to a vector element in c++

Refer to dirkgently's and anon's answers, you can call the front function instead of begin function, so you do not have to write the *, but only the &.

Code Example:

vector<myObject> vec; //You have a vector of your objects
myObject first = vec.front(); //returns reference, not iterator, to the first object in the vector so you had only to write the data type in the generic of your vector, i.e. myObject, and not all the iterator stuff and the vector again and :: of course
myObject* pointer_to_first_object = &first; //* between & and first is not there anymore, first is already the first object, not iterator to it.

Using Google Text-To-Speech in Javascript

I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:

_x000D_
_x000D_
const listenBtn = document.getElementById('myvoice');

listenBtn.addEventListener('click', (e) => {
  e.preventDefault();

  const msg = new SpeechSynthesisUtterance(
    "Hello, hope my code is helpful"
  );
  window.speechSynthesis.speak(msg);

});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
_x000D_
_x000D_

How to force a view refresh without having it trigger automatically from an observable?

You can't call something on the entire viewModel, but on an individual observable you can call myObservable.valueHasMutated() to notify subscribers that they should re-evaluate. This is generally not necessary in KO, as you mentioned.

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

download and install visual studio 2008

Microsoft Visual Studio 2008 Service Pack 1 (iso)

http://www.microsoft.com/en-us/download/details.aspx?id=13276

http://download.microsoft.com/download/a/3/7/a371b6d1-fc5e-44f7-914c-cb452b4043a9/VS2008SP1ENUX1512962.iso

Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB

Supported Operating System

    Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
    Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
    Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
    On Windows Vista: 2.4 GHz CPU, 768 MB RAM
    Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Angular 2.0 router not working on reloading the browser

Server configuration is not a solution for an SPA is what even I think. You dont want to reload an angular SPA again if a wrong route comes in, do you? So I will not depend on a server route and redirect to other route but yes I will let index.html handle all the requests for angular routes of the angular app path.

Try this instead of otherwise or wrong routes. It works for me, not sure but seems like work in progress. Stumbled this myself when facing an issue.

@RouteConfig([
  { path: '/**', redirectTo: ['MycmpnameCmp'] }, 
   ...
  }
])

https://github.com/angular/angular/issues/4055

However remember to configure your server folders and access right in case you have HTML or web scripts which are not SPA. Else you will face issues. For me when facing issue like you it was a mix of server configuration and above.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

This answer may help you if you are using Karma:

I've did exactly as it's mentioned in @wmnitin's answer, but the error was always there. When use "ng serve" instead of "karma start", it works !

Convert a String of Hex into ASCII in Java

Check out Convert a string representation of a hex dump to a byte array using Java?

Disregarding encoding, etc. you can do new String (hexStringToByteArray("75546..."));

UITableview: How to Disable Selection for Some Rows but Not Others

None from the answers above really addresses the issue correctly. The reason is that we want to disable selection of the cell but not necessarily of subviews inside the cell.

In my case I was presenting a UISwitch in the middle of the row and I wanted to disable selection for the rest of the row (which is empty) but not for the switch! The proper way of doing that is hence in the method

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

where a statement of the form

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

disables selection for the specific cell while at the same time allows the user to manipulate the switch and hence use the appropriate selector. This is not true if somebody disables user interaction through the

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

method which merely prepares the cell and does not allow interaction with the UISwitch.

Moreover, using the method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

in order to deselect the cell with a statement of the form

[tableView deselectRowAtIndexPath:indexPath animated:NO];

still shows the row being selected while the user presses on the original contentView of the cell.

Just my two cents. I am pretty sure many will find this useful.

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Get only filename from url in php without any variable values which exist in the url

Try the following code:

For PHP 5.4.0 and above:

$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);

For PHP Version < 5.4.0

$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);

SELECT CASE WHEN THEN (SELECT)

You Could try the other format for the case statement

CASE WHEN Product.type_id = 10
THEN
(
  Select Statement
)
ELSE
(
  Other select statement

)  
END
FROM Product 
WHERE Product.product_id = $pid

See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.

Why do I get an error instantiating an interface?

You can't instantiate interfaces or abstract classes.

That's because it wouldn't have any logic to it.

Interfaces provide a contract of the methods that should be in a class, without implementation. (So there's no actual logic in the interface).

Abstract classes provide basic logic of a class, but are not fully functional (not everything is implemented). So again, you won't be able to do anything with it.

PHP Warning: PHP Startup: ????????: Unable to initialize module

Erase the module that can't be initialized and reinstall it.

No ConcurrentList<T> in .Net 4.0?

System.Collections.Generic.List<t> is already thread safe for multiple readers. Trying to make it thread safe for multiple writers wouldn't make sense. (For reasons Henk and Stephen already mentioned)

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

How to catch an Exception from a thread

You cannot do this, since it doesn't really make sense. If you hadn't called t.join() then you main thread could be anywhere in the code when the t thread throws an exception.

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

How do I read an attribute on a class at runtime?

When you have Overridden Methods with same Name Use the helper below

public static TValue GetControllerMethodAttributeValue<T, TT, TAttribute, TValue>(this T type, Expression<Func<T, TT>> exp, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute
        {
            var memberExpression = exp?.Body as MethodCallExpression;

            if (memberExpression.Method.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault() is TAttribute attr && valueSelector != null)
            {
                return valueSelector(attr);
            }

            return default(TValue);
        }

Usage: var someController = new SomeController(Some params); var str = typeof(SomeController).GetControllerMethodAttributeValue(x => someController.SomeMethod(It.IsAny()), (RouteAttribute routeAttribute) => routeAttribute.Template);

How to handle screen orientation change when progress dialog and background thread active?

My solution was to extend the ProgressDialog class to get my own MyProgressDialog.

I redefined show() and dismiss() methods to lock the orientation before showing the Dialog and unlock it back when Dialog is dismissed.

So when the Dialog is shown and the orientation of the device changes, the orientation of the screen remains until dismiss() is called, then screen-orientation changes according to sensor-values/device-orientation.

Here is my code:

public class MyProgressDialog extends ProgressDialog {
    private Context mContext;

    public MyProgressDialog(Context context) {
        super(context);
        mContext = context;
    }

    public MyProgressDialog(Context context, int theme) {
        super(context, theme);
        mContext = context;
    }
    
    public void show() {
        if (mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        else
            ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        super.show();
    }
    
    public void dismiss() {
        super.dismiss();
        ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }
}

Facebook Graph API : get larger pictures in one request

I researched Graph API Explorer extensively and finally found full_picture

https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture

P.S. I noticed that full_picture won't always provide full size image I want. 'attachments' does

https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture,attachments

git is not installed or not in the PATH

In my case the issue was not resolved because i did not restart my system. Please make sure you do restart your system.

What is setup.py?

To install a Python package you've downloaded, you extract the archive and run the setup.py script inside:

python setup.py install

To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. gem install rails-4.1.1.gem

A package manager is more comfortable too, because it's familiar and reliable. On the other hand, each setup.py is novel, because it's specific to the package. It demands faith in convention "I trust this setup.py takes the same commands as others I have used in the past". That's a regrettable tax on mental willpower.

I'm not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it's awkard and jarring. There's a harmony to commands all being to the same package manager application. You might even grow fond it.

How to use confirm using sweet alert?

document.querySelector('#from1').onsubmit = function(e){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};

How to make an HTTP POST web request

There are some really good answers on here. Let me post a different way to set your headers with the WebClient(). I will also show you how to set an API key.

        var client = new WebClient();
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
        client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
        //If you have your data stored in an object serialize it into json to pass to the webclient with Newtonsoft's JsonConvert
        var encodedJson = JsonConvert.SerializeObject(newAccount);

        client.Headers.Add($"x-api-key:{ApiKey}");
        client.Headers.Add("Content-Type:application/json");
        try
        {
            var response = client.UploadString($"{apiurl}", encodedJson);
            //if you have a model to deserialize the json into Newtonsoft will help bind the data to the model, this is an extremely useful trick for GET calls when you have a lot of data, you can strongly type a model and dump it into an instance of that class.
            Response response1 = JsonConvert.DeserializeObject<Response>(response);

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

For WebStorm 2019.3 File > Preferences or Settings > Languages & Frameworks > Node.js and NPM -> Enable Coding assitance for NodeJs

Note that the additional packages that you want to use are included.

$(document).ready equivalent without jQuery

It's always good to use JavaScript equivalents as compared to jQuery. One reason is one fewer library to depend on and they are much faster than the jQuery equivalents.

One fantastic reference for jQuery equivalents is http://youmightnotneedjquery.com/.

As far as your question is concerned, I took the below code from the above link :) Only caveat is it only works with Internet Explorer 9 and later.

function ready(fn) {
    if (document.readyState != 'loading') {
        fn();
    }
    else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

Programmatically get the version number of a DLL

Answer by @Ben proved to be useful for me. But I needed to check the product version as it was the main increment happening in my software and followed semantic versioning.

myFileVersionInfo.ProductVersion

This method met my expectations

Update: Instead of explicitly mentioning dll path in program (as needed in production version), we can get product version using Assembly.

Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo =FileVersionInfo.GetVersionInfo(assembly.Location); 
string ProdVersion= fileVersionInfo.ProductVersion;

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Let's break down the full URL that a client would type into their address bar to reach your servlet:

http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo

The parts are:

  1. scheme: http
  2. hostname: www.example.com
  3. port: 80
  4. context path: awesome-application
  5. servlet path: path/to/servlet
  6. path info: path/info
  7. query: a=1&b=2
  8. fragment: boo

The request URI (returned by getRequestURI) corresponds to parts 4, 5 and 6.

(incidentally, even though you're not asking for this, the method getRequestURL would give you parts 1, 2, 3, 4, 5 and 6).

Now:

  • part 4 (the context path) is used to select your particular application out of many other applications that may be running in the server
  • part 5 (the servlet path) is used to select a particular servlet out of many other servlets that may be bundled in your application's WAR
  • part 6 (the path info) is interpreted by your servlet's logic (e.g. it may point to some resource controlled by your servlet).
  • part 7 (the query) is also made available to your servlet using getQueryString
  • part 8 (the fragment) is not even sent to the server and is relevant and known only to the client

The following always holds (except for URL encoding differences):

requestURI = contextPath + servletPath + pathInfo

The following example from the Servlet 3.0 specification is very helpful:


Note: image follows, I don't have the time to recreate in HTML:

enter image description here

How to Resize a Bitmap in Android?

While the previous answers do scale the image and take care of the aspect ratio, the resampling itself should be done so that there is no aliasing. Taking care of scale is a matter of fixing arguments correctly. There are many comments about the quality of the output images from standard scaling call. to maintain quality of the image one should use the standard call:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);

with the last argument set to true because it will do the bilinear filtering for resampling to prevent aliasing. Read more about aliasing here: https://en.wikipedia.org/wiki/Aliasing

From android documentation:

https://developer.android.com/reference/android/graphics/Bitmap#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)


public static Bitmap createScaledBitmap (Bitmap src, 
                int dstWidth, 
                int dstHeight, 
                boolean filter)

filter : boolean, Whether or not bilinear filtering should be used when scaling the bitmap. If this is true then bilinear filtering will be used when scaling which has better image quality at the cost of worse performance. If this is false then nearest-neighbor scaling is used instead which will have worse image quality but is faster. Recommended default is to set filter to 'true' as the cost of bilinear filtering is typically minimal and the improved image quality is significant.

How to use 'hover' in CSS

You need to concatenate the selector and pseudo selector. You'll also need a style element to contain your styles. Most people use an external stylesheet, for lots of benefits (caching for one).

<a class="hover">click</a>

<style type="text/css">

    a.hover:hover {
        text-decoration: underline;

    }

</style>

Just a note: the hover class is not necessary, unless you are defining only certain links to have this behavior (which may be the case)

Purge Kafka Topic

While the accepted answer is correct, that method has been deprecated. Topic configuration should now be done via kafka-configs.

kafka-configs --zookeeper localhost:2181 --entity-type topics --alter --add-config retention.ms=1000 --entity-name MyTopic

Configurations set via this method can be displayed with the command

kafka-configs --zookeeper localhost:2181 --entity-type topics --describe --entity-name MyTopic

PHP form - on submit stay on same page

You have to use code similar to this:

echo "<div id='divwithform'>";

if(isset($_POST['submit']))  // if form was submitted (if you came here with form data)
{
    echo "Success";
}
else                // if form was not submitted (if you came here without form data)
{
    echo "<form> ... </form>";
} 

echo "</div>";

Code with if like this is typical for many pages, however this is very simplified.

Normally, you have to validate some data in first "if" (check if form fields were not empty etc).

Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.

Trying to create a file in Android: open failed: EROFS (Read-only file system)

To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir(); to get the allowed directory for the app.

Or:
getCashDir(); <-- should work
context.getCashDir(); (if in a broadcast receiver)
getDataDir(); <--Api 24

How to use Morgan logger?

In my case:

-console.log()  // works
-console.error() // works
-app.use(logger('dev')) // Morgan is NOT logging requests that look like "GET /myURL 304 9.072 ms - -"

FIX: I was using Visual Studio code, and I had to add this to my Launch Config

"outputCapture": "std"

Suggestion, in case you are running from an IDE, run directly from the command line to make sure the IDE is not causing the problem.

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

Simple JavaScript login form validation

<!DOCTYPE html>
<html>
<head>
<script>
function vali() {
var u=document.forms["myform"]["user"].value;
var p=document.forms["myform"]["pwd"].value;
if(u == p) {
alert("Welcome");
window.location="sec.html";
return false;
}
else
{
alert("Please Try again!");
return false;
}
}
</script>
</head>
<body>
<form method="post">
<fieldset style="width:35px;">  <legend>Login Here</legend>
<input type="text" name="user" placeholder="Username" required>
<br>
<input type="Password" name="pwd" placeholder="Password" required>
<br>
<input type="submit" name="submit" value="submit" onclick="return vali()">
</form>
</fieldset>
</html>

'tuple' object does not support item assignment

The second line should have been pixels[0], with an S. You probably have a tuple named pixel, and tuples are immutable. Construct new pixels instead:

image = Image.open('balloon.jpg')

pixels = [(pix[0] + 20,) + pix[1:] for pix in image.getdata()]

image.putdate(pixels)

Set Colorbar Range in matplotlib

Use the CLIM function (equivalent to CAXIS function in MATLAB):

plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4)  # identical to caxis([-4,4]) in MATLAB
plt.show()

What is the purpose of Android's <merge> tag in XML layouts?

<merge/> is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.

For example, if you were to <include/> a layout from another file without using merge, the two files might look something like this:

layout1.xml:

<FrameLayout>
   <include layout="@layout/layout2"/>
</FrameLayout>

layout2.xml:

<FrameLayout>
   <TextView />
   <TextView />
</FrameLayout>

which is functionally equivalent to this single layout:

<FrameLayout>
   <FrameLayout>
      <TextView />
      <TextView />
   </FrameLayout>
</FrameLayout>

That FrameLayout in layout2.xml may not be useful. <merge/> helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):

layout2.xml:

<merge>
   <TextView />
   <TextView />
</merge>

This is functionally equivalent to this layout:

<FrameLayout>
   <TextView />
   <TextView />
</FrameLayout>

but since you are using <include/> you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

Load CSV data into MySQL in Python

The above answer seems good. But another way of doing this is adding the auto commit option along with the db connect. This automatically commits every other operations performed in the db, avoiding the use of mentioning sql.commit() every time.

 mydb = MySQLdb.connect(host='localhost',
        user='root',
        passwd='',
        db='mydb',autocommit=true)

Bootstrap 3 Navbar Collapse

If the problem you face is the menu breaking into multiple lines, you can try one of the following:

1) Try to reduce the number of menu items or their length, like removing menu items or shortening the words.

2) Reducing the padding between the menu items, like this:

.navbar .nav > li > a {
padding: 10px 15px 10px; /* Change here the second value for padding-left and padding right */
}

Default padding is 15px both sides (left and right).

If you prefer to change each individual side use:

padding-left: 7px; 
padding-right: 8px;

This setting affects the dropdown list too.

This doesn't answer the question but it could help others who don't want to mess with the CSS or using LESS variables. The two common approaches to solve this problem.

Installing Bootstrap 3 on Rails App

As many know, there is no need for a gem.

Steps to take:

  1. Download Bootstrap
  2. Copy

    bootstrap/dist/css/bootstrap.css
    bootstrap/dist/css/bootstrap.min.css 
    

    to: app/assets/stylesheets

  3. Copy

    bootstrap/dist/js/bootstrap.js
    bootstrap/dist/js/bootstrap.min.js 
    

    to: app/assets/javascripts

  4. Append to: app/assets/stylesheets/application.css

    *= require bootstrap

  5. Append to: app/assets/javascripts/application.js

    //= require bootstrap

That is all. You are ready to add a new cool Bootstrap template.


Why app/ instead of vendor/?

It is important to add the files to app/assets, so in the future you'll be able to overwrite Bootstrap styles.

If later you want to add a custom.css.scss file with custom styles. You'll have something similar to this in application.css:

 *= require bootstrap                                                            
 *= require custom  

If you placed the bootstrap files in app/assets, everything works as expected. But, if you placed them in vendor/assets, the Bootstrap files will be loaded last. Like this:

<link href="/assets/custom.css?body=1" media="screen" rel="stylesheet">
<link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet">

So, some of your customizations won't be used as the Bootstrap styles will override them.

Reason behind this

Rails will search for assets in many locations; to get a list of this locations you can do this:

$ rails console
> Rails.application.config.assets.paths

In the output you'll see that app/assets takes precedence, thus loading it first.

Find the greatest number in a list of numbers

    #Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))

    #create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
              eighth, ninth, tenth]
odd_numbers = []

    #filter list and add odd numbers to new list
for value in sorted_list:
    if value%2 != 0:
        odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)

PHP cURL HTTP PUT

In a POST method, you can put an array. However, in a PUT method, you should use http_build_query to build the params like this:

curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

ERROR

There was a mistake when I added to the same list from where I took elements:

fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
    for (i in this) {
        this.add(_fun(i))   <---   ERROR
    }
    return this   <--- ERROR
}

DECISION

Works great when adding to a new list:

fun <T> MutableList<T>.mathList(_fun: (T) -> T): MutableList<T> {
    val newList = mutableListOf<T>()   <---   DECISION
    for (i in this) {
        newList.add(_fun(i))   <---   DECISION
    }
    return newList   <---   DECISION
}

make: *** [ ] Error 1 error

I got the same thing. Running "make" and it fails with just this message.

% make
make: *** [all] Error 1

This was caused by a command in a rule terminates with non-zero exit status. E.g. imagine the following (stupid) Makefile:

all:
       @false
       echo "hello"

This would fail (without printing "hello") with the above message since false terminates with exit status 1.

In my case, I was trying to be clever and make a backup of a file before processing it (so that I could compare the newly generated file with my previous one). I did this by having a in my Make rule that looked like this:

@[ -e $@ ] && mv $@ [email protected]

...not realizing that if the target file does not exist, then the above construction will exit (without running the mv command) with exit status 1, and thus any subsequent commands in that rule failed to run. Rewriting my faulty line to:

@if [ -e $@ ]; then mv $@ [email protected]; fi

Solved my problem.

jQuery - getting custom attribute from selected option

You can also try this one as well with data-myTag

<select id="location">
    <option value="a" data-myTag="123">My option</option>
    <option value="b" data-myTag="456">My other option</option>
</select>

<input type="hidden" id="setMyTag" />

<script>
    $(function() {
        $("#location").change(function(){
           var myTag = $('option:selected', this).data("myTag");

           $('#setMyTag').val(myTag);
        });
    });
</script>

Pandas: Convert Timestamp to datetime.date

Assume time column is in timestamp integer msec format

1 day = 86400000 ms

Here you go:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

How can I open a website in my web browser using Python?

The webbrowser module looks promising: https://www.youtube.com/watch?v=jU3P7qz3ZrM

import webbrowser
webbrowser.open('http://google.co.kr', new=2)

How can I count the number of characters in a Bash variable

you can use wc to count the number of characters in the file wc -m filename.txt. Hope that help.

How to detect the device orientation using CSS media queries?

@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */
}

but it still looks like you have to experiment

How to get the last five characters of a string using Substring() in C#?

Here is a quick extension method you can use that mimics PHP syntax. Include AssemblyName.Extensions to the code file you are using the extension in.

Then you could call:

input.SubstringReverse(-5) and it will return "Three".

namespace AssemblyName.Extensions {

    public static class StringExtensions
    {
        /// <summary>
        /// Takes a negative integer - counts back from the end of the string.
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        public static string SubstringReverse(this string str, int length)
        {
            if (length > 0) 
            {
                throw new ArgumentOutOfRangeException("Length must be less than zero.");
            }

            if (str.Length < Math.Abs(length))
            {
                throw new ArgumentOutOfRangeException("Length cannot be greater than the length of the string.");
            }

            return str.Substring((str.Length + length), Math.Abs(length));
        }
    }
}

MySQL Workbench not displaying query results

This was still happening to me on version 6.3.9 on OSX. I downloaded 6.1.7 again to actually see the result grid again.

What a pain in the butt!

Xcode warning: "Multiple build commands for output file"

In the Project Navigator, select your Xcode Project file. This will show you the project settings as well as the targets in the project. Look in the "Copy Bundle Resources" Build Phase. You should find the offending files in that list twice. Delete the duplicate reference.

Xcode is complaining that you are trying to bundle the same file with your application two times.

jQuery ajax call to REST service

From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.

With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.

This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.

The url for the rest api would be http://localhost/restws/json/product/get

Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

How to align iframe always in the center

Try this:

#wrapper {
    text-align: center;
}

#wrapper iframe {
    display: inline-block;
}

equals vs Arrays.equals in Java

import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {
   // initializing three object arrays
   Object[] array1 = new Object[] { 1, 123 };
   Object[] array2 = new Object[] { 1, 123, 22, 4 };
   Object[] array3 = new Object[] { 1, 123 };

   // comparing array1 and array2
   boolean retval=Arrays.equals(array1, array2);
   System.out.println("array1 and array2 equal: " + retval);
   System.out.println("array1 and array2 equal: " + array1.equals(array2));

   // comparing array1 and array3
   boolean retval2=Arrays.equals(array1, array3);
   System.out.println("array1 and array3 equal: " + retval2);
   System.out.println("array1 and array3 equal: " + array1.equals(array3));

   }
}

Here is the output:

    array1 and array2 equal: false
    array1 and array2 equal: false

    array1 and array3 equal: true
    array1 and array3 equal: false

Seeing this kind of problem I would personally go for Arrays.equals(array1, array2) as per your question to avoid confusion.

How to "z-index" to make a menu always on top of the content

you could put the style in container div menu with:

<div style="position:relative; z-index:10">
   ...
   <!--html menu-->
   ...
</div>

before enter image description here

after

enter image description here

How do I get the picture size with PIL?

Since scipy's imread is deprecated, use imageio.imread.

  1. Install - pip install imageio
  2. Use height, width, channels = imageio.imread(filepath).shape

Options for initializing a string array

string[] str = new string[]{"1","2"};
string[] str = new string[4];

Pandas groupby: How to get a union of strings

Following @Erfan's good answer, most of the times in an analysis of aggregate values you want the unique possible combinations of these existing character values:

unique_chars = lambda x: ', '.join(x.unique())
(df
 .groupby(['A'])
 .agg({'C': unique_chars}))

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

In my scenario the build service was not using the same user account that I imported the key with using sn.exe.

After changing the account to my administrator account, everything is working just fine.

Type List vs type ArrayList in Java

For example you might decide a LinkedList is the best choice for your application, but then later decide ArrayList might be a better choice for performance reason.

Use:

List list = new ArrayList(100); // will be better also to set the initial capacity of a collection 

Instead of:

ArrayList list = new ArrayList();

For reference:

enter image description here

(posted mostly for Collection diagram)

Android - Back button in the title bar

After a quality time I have found, theme option is the main problem in my code And following is the proper way to show the toolbar for me

In AndroidManifest file first you have to change your theme style

Theme.AppCompat.Light.DarkActionBar
to 
Theme.AppCompat.Light.NoActionBar

then at your activity xml you need to call your own Toolbar like

<androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:elevation="4dp"/>

And then this toolbar should be called in your Java file by

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

And for toolbar showing U should check the null to avoid NullPointerException

if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

For Home activity back add this

@Override
public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==android.R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

OR for your desired activity back

public boolean onOptionsItemSelected(MenuItem item){
    Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

All you need to do is to go to the control panel > Computer Management > Services and manually start the SQL express or SQL server. It worked for me.

Good luck.

Lost connection to MySQL server during query?

I was getting this error with a "broken pipe" when I tried to do bulk inserts with millions of records. I ended up solving this by chunking my data into smaller batch sizes and then running an executemany command with the mysql cursor for each of the inserts I needed to do. This solved the problem and didn't seem to affect the performance in any noticeable way.

eg.

def chunks(data):
    for i in range(0, len(data), CHUNK_SIZE):
        yield data[i:i + CHUNK_SIZE]


def bulk_import(update_list):
    new_list = list(chunks(update_list))
    for batch in new_list:
         cursor.execute(#SQL STATEMENT HERE)

How to start a background process in Python?

Note: This answer is less current than it was when posted in 2009. Using the subprocess module shown in other answers is now recommended in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(or, alternatively, you may try the less portable os.P_NOWAIT flag).

See the documentation here.

Query comparing dates in SQL

You put <= and it will catch the given date too. You can replace it with < only.

varbinary to string on SQL Server

Try this

SELECT CONVERT(varchar(5000), yourvarbincolumn, 0)

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

How copy data from Excel to a table using Oracle SQL Developer

For PLSQL version 9.0.0.1601

  1. From the context menu of the Table, choose "Edit Data"
  2. Insert or edit the data
  3. Post change

JavaScript open in a new window, not tab

You might try following function:

<script type="text/javascript">
function open(url)
{
  var popup = window.open(url, "_blank", "width=200, height=200") ;
  popup.location = URL;
}
</script>

The HTML code for execution:

<a href="#" onclick="open('http://www.google.com')">google search</a>

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.

HTML table: keep the same width for columns

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your <thead> to <caption> and remove the <td> inside of it, and then set fixed widths for the cells in <tbody>.

Adding iOS UITableView HeaderView (not section header)

In Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter
}

HTML table with fixed headers and a fixed column?

If what you want is to have the headers stay put while the data in the table scrolls vertically, you should implement a <tbody> styled with "overflow-y: auto" like this:

<table>
  <thead>
    <tr>
      <th>Header1</th>
       . . . 
    </tr>
   </thead>
   <tbody style="height: 300px; overflow-y: auto"> 
     <tr>
       . . .
     </tr>
     . . .
   </tbody>
 </table>

If the <tbody> content grows taller than the desired height, it will start scrolling. However, the headers will stay fixed at the top regardless of the scroll position.

How to create a multiline UITextfield?

This code block is enough. Please don't forget to set delegate in viewDidLoad or by storyboard just before to use the following extension:

extension YOUR_VIEW_CONTROLLER: UITextViewDelegate {

func textViewDidBeginEditing (_ textView: UITextView) {
    if YOUR_TEXT_VIEW.text.isEmpty || YOUR_TEXT_VIEW.text == "YOUR DEFAULT PLACEHOLDER TEXT HERE" {
        YOUR_TEXT_VIEW.text = nil
        YOUR_TEXT_VIEW.textColor = .red // YOUR PREFERED COLOR HERE
    }
}
func textViewDidEndEditing (_ textView: UITextView) {
    if YOUR_TEXT_VIEW.text.isEmpty {
        YOUR_TEXT_VIEW.textColor = UIColor.gray // YOUR PREFERED PLACEHOLDER COLOR HERE
        YOUR_TEXT_VIEW.text =  "YOUR DEFAULT PLACEHOLDER TEXT HERE"
    }
}

}

How to display items side-by-side without using tables?

Yes, divs and CSS are usually a better and easier way to place your HTML. There are many different ways to do this and it all depends on the context.

For instance, if you want to place an image to the right of your text, you could do it like so:

<p style="width: 500px;">
<img src="image.png" style="float: right;" />
This is some text
</p> 

And if you want to display multiple items side by side, float is also usually preferred.For example:

<div>
  <img src="image1.png" style="float: left;" />
  <img src="image2.png" style="float: left;" />
  <img src="image3.png" style="float: left;" />
</div>

Floating these images to the same side will have then laying next to each other for as long as you hava horizontal space.

How do I get the full path of the current file's directory?

Python 3

For the directory of the script being run:

import pathlib
pathlib.Path(__file__).parent.absolute()

For the current working directory:

import pathlib
pathlib.Path().absolute()

Python 2 and 3

For the directory of the script being run:

import os
os.path.dirname(os.path.abspath(__file__))

If you mean the current working directory:

import os
os.path.abspath(os.getcwd())

Note that before and after file is two underscores, not just one.

Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.

References

  1. pathlib in the python documentation.
  2. os.path 2.7, os.path 3.8
  3. os.getcwd 2.7, os.getcwd 3.8
  4. what does the __file__ variable mean/do?

Create a Path from String in Java7

From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Path p1 = Paths.get("/tmp/foo"); 

is the same as

Path p4 = FileSystems.getDefault().getPath("/tmp/foo");

Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));

Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log"); 

In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Change remote repository credentials (authentication) on Intellij IDEA 14

In Intellinj IDEA 14, we can change the Git password by the following steps:

From the menu bar :

  1. Select File -> Settings -> Appearance & Behavior -> System Settings .

  2. Choose Passwords.

  3. Click the 'Master Password' under 'Disk storage protection'.

  4. In the Password field, enter your old password. Enter your new password in the subsequent fields.

  5. Now the master password will be changed.

How to add files/folders to .gitignore in IntelliJ IDEA?

Here is the screen print showing the options to ignore the file or folder after the installation of the .ignore plugin. The generated file name would be .gitignore enter image description here

ESLint - "window" is not defined. How to allow global variables in package.json

I found it on this page: http://eslint.org/docs/user-guide/configuring

In package.json, this works:

"eslintConfig": {
  "globals": {
    "window": true
  }
}

How to debug a GLSL shader?

void main(){
  float bug=0.0;
  vec3 tile=texture2D(colMap, coords.st).xyz;
  vec4 col=vec4(tile, 1.0);

  if(something) bug=1.0;

  col.x+=bug;

  gl_FragColor=col;
}

Docker-compose: node_modules not present in a volume after npm install succeeds

I tried the most popular answers on this page but ran into an issue: the node_modules directory in my Docker instance would get cached in the the named or unnamed mount point, and later would overwrite the node_modules directory that was built as part of the Docker build process. Thus, new modules I added to package.json would not show up in the Docker instance.

Fortunately I found this excellent page which explains what was going on and gives at least 3 ways to work around it: https://burnedikt.com/dockerized-node-development-and-mounting-node-volumes/

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

How do I make an Event in the Usercontrol and have it handled in the Main Form?

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

User control:

[Browsable(true)] [Category("Action")] 
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}

Form:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}

Notes:

  • Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e); you can use ButtonClick?.Invoke(this, e);, which does essentially the same, but is shorter.

  • The Browsable attribute makes the event visible in Visual Studio's designer (events view), Category shows it in the "Action" category, and Description provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.

Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

try
{
   ...
}
catch (Exception e)
{
   if (e instanceof FooException)
     throw e;
}

How to set Navigation Drawer to be opened from right to left

I did following modification to the Navigation Drawer Activity example in Android Studio. With support libraries 25.3.1.

MainActivity.java:

private DrawerLayout mDrawerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
        mDrawerLayout.closeDrawer(GravityCompat.END);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    switch (itemId) {
        case android.R.id.home:
            finish();
            return true;

        case R.id.action_right_drawer:
            if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                mDrawerLayout.closeDrawer(GravityCompat.END);
            } else {
                mDrawerLayout.openDrawer(GravityCompat.END);
            }
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.

    mDrawerLayout.closeDrawer(GravityCompat.END);
    return true;
}

main.xml (download ic_menu_white_24px from https://material.io/icons/):

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_right_drawer"
        android:title="Drawer menu"
        android:icon="@drawable/ic_menu_white_24px"
        android:orderInCategory="100"
        app:showAsAction="always" />
</menu>

In activity_main.xml change

android:layout_gravity="start"

to

android:layout_gravity="end"

Fastest way to list all primes below N

This is the way you can compare with others.

# You have to list primes upto n
nums = xrange(2, n)
for i in range(2, 10):
    nums = filter(lambda s: s==i or s%i, nums)
print nums

So simple...

What is the difference between using constructor vs getInitialState in React / React Native?

Constructor The constructor is a method that's automatically called during the creation of an object from a class. ... Simply put, the constructor aids in constructing things. In React, the constructor is no different. It can be used to bind event handlers to the component and/or initializing the local state of the component.Jan 23, 2019

getInitialState In ES6 classes, you can define the initial state by assigning this.state in the constructor:

Look at this example

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

Styling the last td in a table with css

you could use the last-child psuedo class

table tr td:last-child {
    border: none;
}

This will style the last td only. It's not fully supported yet so it may be unsuitable

How to redirect output of an already running process

You can also do it using reredirect (https://github.com/jerome-pouiller/reredirect/).

The command bellow redirects the outputs (standard and error) of the process PID to FILE:

reredirect -m FILE PID

The README of reredirect also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.

The tool also provides relink, a script allowing to redirect the outputs to the current terminal:

relink PID
relink PID | grep usefull_content

(reredirect seems to have same features than Dupx described in another answer but, it does not depend on Gdb).

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Trigger a button click with JavaScript on the Enter key in a text box

For modern JS keyCode is deprecated, use key instead

searchInput.onkeyup = function (e) {
    if (e.key === 'Enter') {
        searchBtn.click();
    }
}

Underscore prefix for property and method names in JavaScript

"Only conventions? Or is there more behind the underscore prefix?"

Apart from privacy conventions, I also wanted to help bring awareness that the underscore prefix is also used for arguments that are dependent on independent arguments, specifically in URI anchor maps. Dependent keys always point to a map.

Example ( from https://github.com/mmikowski/urianchor ) :

$.uriAnchor.setAnchor({
  page   : 'profile',
  _page  : {
    uname   : 'wendy',
    online  : 'today'
  }
});

The URI anchor on the browser search field is changed to:

\#!page=profile:uname,wendy|online,today

This is a convention used to drive an application state based on hash changes.

How can I check what version/edition of Visual Studio is installed programmatically?

Its not very subtle, but there is a folder in the install location that carries the installed version name.

eg I've got:

C:\Program Files\Microsoft Visual Studio 9.0\Microsoft Visual Studio 2008 Standard Edition - ENU

and

C:\Program Files\Microsoft Visual Studio 10.0\Microsoft Visual Studio 2010 Professional - ENU

You could find the install location from the registry keys you listed above.

Alternatively this will be in the registry at a number of places, eg:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Setup\Microsoft Visual Studio 2008 Standard Edition - ENU

There are loads of values and keys with the string in, you can find them by looking for "Microsoft Visual Studio 2010" in the Regedit>Edit>Find function.

You'd just need to pick the one you want and do a little bit of string matching.

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

Regular expressions inside SQL Server

stored value in DB is: 5XXXXXX [where x can be any digit]

You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.

Use:

WHERE CHARINDEX(column, '5') = 1
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

i have also different cases like XXXX7XX for example, so it has to be generic.

Use:

WHERE PATINDEX('%7%', column) = 5
  AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
  AND ISNUMERIC(column) = 1

References:

Regex Support

SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:

  • 5\d{6} for your first example
  • \d{4}7\d{2} for your second example

For more info on regular expressions, I highly recommend this website.

iFrame src change event detection?

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

Html code:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>

Js:

    function resizeIframe(obj) {
        alert(obj.contentWindow.location.pathname);
    }

What is the purpose of global.asax in asp.net

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

form_for with nested resources

You don't need to do special things in the form. You just build the comment correctly in the show action:

class ArticlesController < ActionController::Base
  ....
  def show
    @article = Article.find(params[:id])
    @new_comment = @article.comments.build
  end
  ....
end

and then make a form for it in the article view:

<% form_for @new_comment do |f| %>
   <%= f.text_area :text %>
   <%= f.submit "Post Comment" %>
<% end %>

by default, this comment will go to the create action of CommentsController, which you will then probably want to put redirect :back into so you're routed back to the Article page.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

My personal opinion: Go for Swing together with the NetBeans platform.

If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.

I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.

The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate "pure" Swing components into such an application.

The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I solved this problem by adding following code into my /etc/my.cnf file -

enter image description here

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

After saving that,I went into my system settings and stopped MYSQL server and started again, and it worked.

How to set the title of UIButton as left alignment?

Swift 4+

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

Browse for a directory in C#

You could just use the FolderBrowserDialog class from the System.Windows.Forms namespace.

Updating user data - ASP.NET Identity

I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked.

With the new DI model I added the constructor's Controller the context to the DB.

I tried to see what are the conflict with _conext.ChangeTracker.Entries() and adding AsNoTracking() to my calls without success.

I only need to change the state of my object (in this case Identity)

_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);

And worked without create another store or object and mapping.

I hope someone else is useful my two cents.

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

How do you open a file in C++?

Follow the steps,

  1. Include Header files or name space to access File class.
  2. Make File class object Depending on your IDE platform ( i.e, CFile,QFile,fstream).
  3. Now you can easily find that class methods to open/read/close/getline or else of any file.
CFile/QFile/ifstream m_file;
m_file.Open(path,Other parameter/mood to open file);

For reading file you have to make buffer or string to save data and you can pass that variable in read() method.

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

How to encode text to base64 in python

It looks it's essential to call decode() function to make use of actual string data even after calling base64.b64decode over base64 encoded string. Because never forget it always return bytes literals.

import base64
conv_bytes = bytes('your string', 'utf-8')
print(conv_bytes)                                 # b'your string'
encoded_str = base64.b64encode(conv_bytes)
print(encoded_str)                                # b'eW91ciBzdHJpbmc='
print(base64.b64decode(encoded_str))              # b'your string'
print(base64.b64decode(encoded_str).decode())     # your string

Git copy file preserving history

Simply copy the file, add and commit it:

cp dir1/A.txt dir2/A.txt
git add dir2/A.txt
git commit -m "Duplicated file from dir1/ to dir2/"

Then the following commands will show the full pre-copy history:

git log --follow dir2/A.txt

To see inherited line-by-line annotations from the original file use this:

git blame -C -C -C dir2/A.txt

Git does not track copies at commit-time, instead it detects them when inspecting history with e.g. git blame and git log.

Most of this information comes from the answers here: Record file copy operation with Git

How can I increment a char?

In Python 2.x, just use the ord and chr functions:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord receives Unicode chars and chr produces them).

But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:

>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'

Calculate mean across dimension in a 2D array

If you do this a lot, NumPy is the way to go.

If for some reason you can't use NumPy:

>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]

Add ArrayList to another ArrayList in java

Initiate the NodeList inside the for loop and you will get the desired output.

ArrayList<String> nodes = new ArrayList<String>();
 ArrayList list=new ArrayList();

        for(int i=0;i<PropertyNode.getLength()-1;i++){
            ArrayList NodeList=new ArrayList();
            Node childNode =  PropertyNode.item(i);
                NodeList Children = childNode.getChildNodes();

                if(Children!=null){
                    nodes.clear();
                    nodes.add("PropertyStart");
                    nodes.add(Children.item(3).getTextContent());
                    nodes.add(Children.item(7).getTextContent());
                    nodes.add(Children.item(9).getTextContent());
                    nodes.add(Children.item(11).getTextContent());
                    nodes.add(Children.item(13).getTextContent());
                    nodes.add("PropertyEnd");

                }   
                NodeList.addAll(nodes);
                list.add(NodeList);
        }

Explanation: NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once. The loop is only adding its variables in single NodeList array hence you must be seeing

[/*list*/    [  /*NodeList*/   ]   ]

and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

403 Forbidden error when making an ajax Post request in Django framework

You must change your folder chmod 755 and file(.php ,.html) chmod 644.

How to use @Nullable and @Nonnull annotations more effectively?

In Java I'd use Guava's Optional type. Being an actual type you get compiler guarantees about its use. It's easy to bypass it and obtain a NullPointerException, but at least the signature of the method clearly communicates what it expects as an argument or what it might return.

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

How to reload the current state?

Silly workaround that always works.

$state.go("otherState").then(function(){
     $state.go("wantedState")
});

Confused about Service vs Factory

Service style: (probably the simplest one) returns the actual function: Useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference.

A service in AngularJS is a singleton JavaScript object which contains a set of functions

var myModule = angular.module("myModule", []);

myModule.value  ("myValue"  , "12345");

function MyService(myValue) {
    this.doIt = function() {
        console.log("done: " + myValue;
    }
}

myModule.service("myService", MyService);
myModule.controller("MyController", function($scope, myService) {

    myService.doIt();

});

Factory style: (more involved but more sophisticated) returns the function's return value: instantiate an object like new Object() in java.

Factory is a function that creates values. When a service, controller etc. needs a value injected from a factory, the factory creates the value on demand. Once created, the value is reused for all services, controllers etc. which need it injected.

var myModule = angular.module("myModule", []);

myModule.value("numberValue", 999);

myModule.factory("myFactory", function(numberValue) {
    return "a value: " + numberValue;
})  
myModule.controller("MyController", function($scope, myFactory) {

    console.log(myFactory);

});

Provider style: (full blown, configurable version) returns the output of the function's $get function: Configurable.

Providers in AngularJS is the most flexible form of factory you can create. You register a provider with a module just like you do with a service or factory, except you use the provider() function instead.

var myModule = angular.module("myModule", []);

myModule.provider("mySecondService", function() {
    var provider = {};
    var config   = { configParam : "default" };

    provider.doConfig = function(configParam) {
        config.configParam = configParam;
    }

    provider.$get = function() {
        var service = {};

        service.doService = function() {
            console.log("mySecondService: " + config.configParam);
        }

        return service;
    }

    return provider;
});

myModule.config( function( mySecondServiceProvider ) {
    mySecondServiceProvider.doConfig("new config param");
});

myModule.controller("MyController", function($scope, mySecondService) {

    $scope.whenButtonClicked = function() {
        mySecondService.doIt();
    }

});

src jenkov

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html ng-app="app">_x000D_
    <head>_x000D_
     <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>_x000D_
     <meta charset=utf-8 />_x000D_
     <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body ng-controller="MyCtrl">_x000D_
     {{serviceOutput}}_x000D_
     <br/><br/>_x000D_
     {{factoryOutput}}_x000D_
     <br/><br/>_x000D_
     {{providerOutput}}_x000D_
    _x000D_
     <script>_x000D_
    _x000D_
      var app = angular.module( 'app', [] );_x000D_
    _x000D_
      var MyFunc = function() {_x000D_
    _x000D_
       this.name = "default name";_x000D_
    _x000D_
       this.$get = function() {_x000D_
        this.name = "new name"_x000D_
        return "Hello from MyFunc.$get(). this.name = " + this.name;_x000D_
       };_x000D_
    _x000D_
       return "Hello from MyFunc(). this.name = " + this.name;_x000D_
      };_x000D_
    _x000D_
      // returns the actual function_x000D_
      app.service( 'myService', MyFunc );_x000D_
    _x000D_
      // returns the function's return value_x000D_
      app.factory( 'myFactory', MyFunc );_x000D_
    _x000D_
      // returns the output of the function's $get function_x000D_
      app.provider( 'myProv', MyFunc );_x000D_
    _x000D_
      function MyCtrl( $scope, myService, myFactory, myProv ) {_x000D_
    _x000D_
       $scope.serviceOutput = "myService = " + myService;_x000D_
       $scope.factoryOutput = "myFactory = " + myFactory;_x000D_
       $scope.providerOutput = "myProvider = " + myProv;_x000D_
    _x000D_
      }_x000D_
    _x000D_
     </script>_x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

jsbin

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myApp">_x000D_
<head>_x000D_
 <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>_x000D_
 <meta charset=utf-8 />_x000D_
 <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div ng-controller="MyCtrl">_x000D_
    {{hellos}}_x000D_
</div>_x000D_
 <script>_x000D_
_x000D_
 var myApp = angular.module('myApp', []);_x000D_
_x000D_
//service style, probably the simplest one_x000D_
myApp.service('helloWorldFromService', function() {_x000D_
    this.sayHello = function() {_x000D_
        return "Hello, World!"_x000D_
    };_x000D_
});_x000D_
_x000D_
//factory style, more involved but more sophisticated_x000D_
myApp.factory('helloWorldFromFactory', function() {_x000D_
    return {_x000D_
        sayHello: function() {_x000D_
            return "Hello, World!"_x000D_
        }_x000D_
    };_x000D_
});_x000D_
    _x000D_
//provider style, full blown, configurable version     _x000D_
myApp.provider('helloWorld', function() {_x000D_
_x000D_
    this.name = 'Default';_x000D_
_x000D_
    this.$get = function() {_x000D_
        var name = this.name;_x000D_
        return {_x000D_
            sayHello: function() {_x000D_
                return "Hello, " + name + "!"_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setName = function(name) {_x000D_
        this.name = name;_x000D_
    };_x000D_
});_x000D_
_x000D_
//hey, we can configure a provider!            _x000D_
myApp.config(function(helloWorldProvider){_x000D_
    helloWorldProvider.setName('World');_x000D_
});_x000D_
        _x000D_
_x000D_
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {_x000D_
    _x000D_
    $scope.hellos = [_x000D_
        helloWorld.sayHello(),_x000D_
        helloWorldFromFactory.sayHello(),_x000D_
        helloWorldFromService.sayHello()];_x000D_
}_x000D_
 </script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

jsfiddle

How to get height of entire document with JavaScript?

Document sizes are a browser compatibility nightmare because, although all browsers expose clientHeight and scrollHeight properties, they don't all agree how the values are calculated.

There used to be a complex best-practice formula around for how you tested for correct height/width. This involved using document.documentElement properties if available or falling back on document properties and so on.

The simplest way to get correct height is to get all height values found on document, or documentElement, and use the highest one. This is basically what jQuery does:

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );

A quick test with Firebug + jQuery bookmarklet returns the correct height for both cited pages, and so does the code example.

Note that testing the height of the document before the document is ready will always result in a 0. Also, if you load more stuff in, or the user resizes the window, you may need to re-test. Use onload or a document ready event if you need this at load time, otherwise just test whenever you need the number.

Axios Delete request with body and headers?

I had the same issue I solved it like that:

axios.delete(url, {data:{username:"user", password:"pass"}, headers:{Authorization: "token"}})

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

Execute a command line binary with Node.js

Use this lightweight npm package: system-commands

Look at it here.

Import it like this:

const system = require('system-commands')

Run commands like this:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})

Argparse: Required arguments listed under "optional arguments"?

Parameters starting with - or -- are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.

See also the documentation:

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.

Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):

parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT

Foo

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Output file name

required named arguments:
  -i INPUT, --input INPUT
                        Input file name

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

MyISAM versus InnoDB

I know this won't be popular but here goes:

myISAM lacks support for database essentials like transactions and referential integrity which often results in glitchy / buggy applications. You cannot not learn proper database design fundamentals if they are not even supported by your db engine.

Not using referential integrity or transactions in the database world is like not using object oriented programming in the software world.

InnoDB exists now, use that instead! Even MySQL developers have finally conceded to change this to the default engine in newer versions, despite myISAM being the original engine that was the default in all legacy systems.

No it does not matter if you are reading or writing or what performance considerations you have, using myISAM can result in a variety of problems, such as this one I just ran into: I was performing a database sync and at the same time someone else accessed an application that accessed a table set to myISAM. Due to the lack of transaction support and the generally poor reliability of this engine, this crashed the entire database and I had to manually restart mysql!

Over the past 15 years of development I have used many databases and engines. myISAM crashed on me about a dozen times during this period, other databases, only once! And that was a microsoft SQL database where some developer wrote faulty CLR code (common language runtime - basically C# code that executes inside the database) by the way, it was not the database engine's fault exactly.

I agree with the other answers here that say that quality high-availability, high-performance applications should not use myISAM as it will not work, it is not robust or stable enough to result in a frustration-free experience. See Bill Karwin's answer for more details.

P.S. Gotta love it when myISAM fanboys downvote but can't tell you which part of this answer is incorrect.

jQuery events .load(), .ready(), .unload()

Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.

enabling cross-origin resource sharing on IIS7

The 405 response is a "Method not allowed" response. It sounds like your server isn't properly configured to handle CORS preflight requests. You need to do two things:

1) Enable IIS7 to respond to HTTP OPTIONS requests. You are getting the 405 because IIS7 is rejecting the OPTIONS request. I don't know how to do this as I'm not familiar with IIS7, but there are probably others on Stack Overflow who do.

2) Configure your application to respond to CORS preflight requests. You can do this by adding the following two lines underneath the Access-Control-Allow-Origin line in the <customHeaders> section:

<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

You may have to add other values to the Access-Control-Allow-Headers section based on what headers your request is asking for. Do you have the sample code for making a request?

You can learn more about CORS and CORS preflight here: http://www.html5rocks.com/en/tutorials/cors/

How do I put the image on the right side of the text in a UIButton?

How about Constraints? Unlike semanticContentAttribute, they don't change semantics. Something like this perhaps:

 button.rightAnchorconstraint(equalTo: button.rightAnchor).isActive = true

or in Objective-C:

[button.imageView.rightAnchor constraintEqualToAnchor:button.rightAnchor].isActive = YES;

Caveats: Untested, iOS 9+

Invoke(Delegate)

A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke to ask the main thread to do it on your behalf.

For instance, if you want to change the text of a label from a worker thread, you can do something like this:

theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

First, Start MongoDB:

sudo service mongod start

Then, Run:

mongo

How to filter by IP address in Wireshark?

Match destination: ip.dst == x.x.x.x

Match source: ip.src == x.x.x.x

Match either: ip.addr == x.x.x.x

How to get cumulative sum

Without using any type of JOIN cumulative salary for a person fetch by using follow query:

SELECT * , (
  SELECT SUM( salary ) 
  FROM  `abc` AS table1
  WHERE table1.ID <=  `abc`.ID
    AND table1.name =  `abc`.Name
) AS cum
FROM  `abc` 
ORDER BY Name

Converting from hex to string

Like so?

static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}

Handling identity columns in an "Insert Into TABLE Values()" statement?

Another "trick" for generating the column list is simply to drag the "Columns" node from Object Explorer onto a query window.

Java Swing - how to show a panel on top of another panel?

I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. Tutorial for positioning without a LayoutManager.

public class Main {
    private JFrame frame = new JFrame();
    private JLayeredPane lpane = new JLayeredPane();
    private JPanel panelBlue = new JPanel();
    private JPanel panelGreen = new JPanel();
    public Main()
    {
        frame.setPreferredSize(new Dimension(600, 400));
        frame.setLayout(new BorderLayout());
        frame.add(lpane, BorderLayout.CENTER);
        lpane.setBounds(0, 0, 600, 400);
        panelBlue.setBackground(Color.BLUE);
        panelBlue.setBounds(0, 0, 600, 400);
        panelBlue.setOpaque(true);
        panelGreen.setBackground(Color.GREEN);
        panelGreen.setBounds(200, 100, 100, 100);
        panelGreen.setOpaque(true);
        lpane.add(panelBlue, new Integer(0), 0);
        lpane.add(panelGreen, new Integer(1), 0);
        frame.pack();
        frame.setVisible(true);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }

}

You use setBounds to position the panels inside the layered pane and also to set their sizes.

Edit to reflect changes to original post You will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

Remove the project from the server from the Server View. Then run the project under the same server.

The problem is as @BalusC told corrupt of server.xml of tomcat which is configured in the eclipse. So when you do the above process server.xml will be recreated .

Android Studio: /dev/kvm device permission denied

Provide appropriate permissions with this command

sudo chmod 777 -R /dev/kvm

How to access Anaconda command prompt in Windows 10 (64-bit)

Go with the mouse to the Windows Icon (lower left) and start typing "Anaconda". There should show up some matching entries. Select "Anaconda Prompt". A new command window, named "Anaconda Prompt" will open. Now, you can work from there with Python, conda and other tools.

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

Send email using java

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendEmail extends Object{

public static void main(String [] args)
{

    try{

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.mail.yahoo.com"); // for gmail use smtp.gmail.com
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true"); 
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("[email protected]", "password");
            }
        });

        mailSession.setDebug(true); // Enable the debug mode

        Message msg = new MimeMessage( mailSession );

        //--[ Set the FROM, TO, DATE and SUBJECT fields
        msg.setFrom( new InternetAddress( "[email protected]" ) );
        msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse("[email protected]") );
        msg.setSentDate( new Date());
        msg.setSubject( "Hello World!" );

        //--[ Create the body of the mail
        msg.setText( "Hello from my first e-mail sent with JavaMail" );

        //--[ Ask the Transport class to send our mail message
        Transport.send( msg );

    }catch(Exception E){
        System.out.println( "Oops something has gone pearshaped!");
        System.out.println( E );
    }
}
}

Required jar files

Click here - How to add External Jars

Asp Net Web API 2.1 get client IP address

With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress

How to start MySQL server on windows xp

You need to run the server first. The command you use (in the question) starts a client to connect to the server but the server is not there so there the error.

Since I am not a Windows user (Linux comes equipped) so I might not be the best person to tell you how but I can point to you to a guide and another guide that show you how to get MySQL server up and running in Windows.

After you get that running, you can use the command (in the question) to connect it.

NOTE: You may also try http://www.apachefriends.org/en/xampp.html if you plan to use MySQL for web database development.

Hope this helps.

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

Thanks to galloglass' answer. The code works great with Python 2.7. There is only one thing I want to metion. When read the manifest.mbdb file, you should use binary mode. Otherwise, not all content are read.

I also made some minor changes to make the code work with Python 3.4. Here is the code.

#!/usr/bin/env python
import sys
import hashlib

mbdx = {}

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value << 8) + data[offset]
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if chr(data[offset]) == chr(0xFF) and chr(data[offset + 1]) == chr(0xFF):
        return '', offset + 2  # Blank string
    length, offset = getint(data, offset, 2)  # 2-byte length
    value = data[offset:offset + length]
    return value.decode(encoding='latin-1'), (offset + length)

def process_mbdb_file(filename):
    mbdb = {}  # Map offset of info in this file => file info
    data = open(filename, 'rb').read()  # 'b' is needed to read all content at once
    if data[0:4].decode() != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2  # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
        fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
        id = hashlib.sha1(fullpath.encode())
        mbdx[fileinfo['start_offset']] = id.hexdigest()
    return mbdb

def modestr(val):
    def mode(val):
        if (val & 0x4):
            r = 'r'
        else:
            r = '-'
        if (val & 0x2):
            w = 'w'
        else:
            w = '-'
        if (val & 0x1):
            x = 'x'
        else:
            x = '-'
        return r + w + x
    return mode(val >> 6) + mode((val >> 3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000:
        type = 'l'  # symlink
    elif (f['mode'] & 0xE000) == 0x8000:
        type = '-'  # file
    elif (f['mode'] & 0xE000) == 0x4000:
        type = 'd'  # dir
    else:
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?'  # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
            (type, modestr(f['mode'] & 0x0FFF), f['userid'], f['groupid'], f['filelen'],
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget']  # symlink destination
    for name, value in f['properties'].items():  # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file(
        r"Manifest.mbdb")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print(fileinfo_str(fileinfo, verbose))

Mockito: Mock private field initialization

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do

object.hasparams

How to read strings from a Scanner in a Java console application?

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));

Hope this helps.

using scp in terminal

I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop

The username@remotecomputer is the same string you used with ssh initially.

ToList().ForEach in Linq

As xanatos said, this is a misuse of ForEach.

If you are going to use linq to handle this, I would do it like this:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
    item.SomeProperty = null;
}
collection.AddRange(departments);

However, the Loop approach is more readable and therefore more maintainable.

Div vertical scrollbar show

What browser are you testing in?

What DOCType have you set?

How exactly are you declaring your CSS?

Are you sure you haven't missed a ; before/after the overflow-y: scroll?

I've just tested the following in IE7 and Firefox and it works fine

_x000D_
_x000D_
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents -->        _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
  test<br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Checking for NULL pointer in C/C++

  • Pointers are not booleans
  • Modern C/C++ compilers emit a warning when you write if (foo = bar) by accident.

Therefore I prefer

if (foo == NULL)
{
    // null case
}
else
{
    // non null case
}

or

if (foo != NULL)
{
    // non null case
}
else
{
    // null case
}

However, if I were writing a set of style guidelines I would not be putting things like this in it, I would be putting things like:

Make sure you do a null check on the pointer.

How to read a file in Groovy into a string?

Here you can Find some other way to do the same.

Read file.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();

Read Full file.

File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();

Read file Line Bye Line.

File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
 log.info file1.readLines().get(i)

}

Create a new file.

new File("C:\Temp\FileName.txt").createNewFile();