Programs & Examples On #Compatibility level

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

Google access token expiration time

Since there is no accepted answer I will try to answer this one:

[s] - seconds

How to get the difference (only additions) between two files in linux

All of the below is copied directly from @TomOnTime's serverfault answer here:

Show lines that only exist in file a: (i.e. what was deleted from a)

comm -23 a b

Show lines that only exist in file b: (i.e. what was added to b)

comm -13 a b

Show lines that only exist in one file or the other: (but not both)

comm -3 a b | sed 's/^\t//'

(Warning: If file a has lines that start with TAB, it (the first TAB) will be removed from the output.)

NOTE: Both files need to be sorted for "comm" to work properly. If they aren't already sorted, you should sort them:

sort <a >a.sorted
sort <b >b.sorted
comm -12 a.sorted b.sorted

If the files are extremely long, this may be quite a burden as it requires an extra copy and therefore twice as much disk space.

Edit: note that the command can be written more concisely using process substitution (thanks to @phk for the comment):

comm -12 <(sort < a) <(sort < b)

cat, grep and cut - translated to python

you need to use os.system module to execute shell command

import os
os.system('command')

if you want to save the output for later use, you need to use subprocess module

import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]

How to press back button in android programmatically?

You don't need to override onBackPressed() - it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed() whenever you want to "programatically press" the back button.

That would only result to finish() being called, though ;)

I think you're confused with what the back button does. By default, it's just a call to finish(), so it just exits the current activity. If you have something behind that activity, that screen will show.

What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.

how to redirect to home page

document.location.href="/";

or

 window.location.href = "/";

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/Window/#window-location

(Note: I copied the difference explanation above, from this question.)

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

Delete empty lines using sed

You may have spaces or tabs in your "empty" line. Use POSIX classes with sed to remove all lines containing only whitespace:

sed '/^[[:space:]]*$/d'

A shorter version that uses ERE, for example with gnu sed:

sed -r '/^\s*$/d'

(Note that sed does NOT support PCRE.)

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Range with step of type float

Probably because you can't have part of an iterable. Also, floats are imprecise.

What is the reason for having '//' in Python?

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions perform float divisions, except those with //. This works with all versions from 2.2.0a2 on.

Select option padding not working in chrome

Not padding but if your goal is to simply make it larger, you can increase the font-size. And using it with font-size-adjust reduces the font-size back to normal on select and not on options, so it ends up making the option larger.

Not sure if it works on all browsers, or will keep working in current.

Tested on Chrome 85 & Firefox 81.

screenshot (on Firefox)

_x000D_
_x000D_
select {
    font-size: 2em;
    font-size-adjust: 0.3;
}
_x000D_
<label>
  Select: <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
          </select>
</label>
_x000D_
_x000D_
_x000D_

Best practice when adding whitespace in JSX

use {} or {``} or &nbsp; to create space between span element and content.

<b> {notif.name} </b> <span id="value"> &nbsp;{ notif.count }{``} </span>

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

How to get date representing the first day of a month?

The accepted answer works, and may be faster, but SQL 2012 and above have a more easily understood method:

SELECT cast(format(GETDATE(), 'yyyy-MM-01') as Date)

Bitbucket git credentials if signed up with Google

One way to skip this is by creating a specific app password variable.

  1. Settings
  2. App passwords
  3. Create app password

And you can use that generated password to access or to push commits from your terminal, when using a Google Account to sign in into Bitbucket.

set column width of a gridview in asp.net

Add HeaderStyle-Width and ItemStyle-width to TemplateFiels

 <asp:GridView ID="grdCanceled" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="grdCanceled_PageIndexChanging"  AllowPaging="true" PageSize="15"
         CssClass="table table-condensed table-striped table-bordered" GridLines="None">
             <HeaderStyle BackColor="#00BCD4"  ForeColor="White" />
             <PagerStyle CssClass="pagination-ys" />
               <Columns>
            <asp:TemplateField HeaderText="Mobile NO" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                <ItemTemplate>
                  <%#Eval("mobile") %>
                </ItemTemplate>
               </asp:TemplateField>
           <asp:TemplateField HeaderText="Name" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                <ItemTemplate>
                    <%#Eval("name") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                <ItemTemplate>
                    <%#Eval("city") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Reason" HeaderStyle-Width="25%" ItemStyle-Width="25%">
                 <ItemTemplate>
                    <%#Eval("reson") %>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Agent" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                 <ItemTemplate>
                     <%#Eval("Agent") %>
                 </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderText="Date" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                 <ItemTemplate>
                   <%#Eval("date","{0:dd-MMM-yy}") %>
                 </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="DList" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                  <ItemTemplate>
                      <%#Eval("service") %>
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="EndDate" HeaderStyle-Width="10%" ItemStyle-Width="10%">
                  <ItemTemplate>
                      <%#Eval("endDate","{0:dd-MMM-yy}") %>
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderStyle-Width="5%" ItemStyle-Width="5%">
                  <ItemTemplate>
                       <asp:CheckBox data-needed='<%#Eval("userId") %>' ID="chkChecked" runat="server" />
                   </ItemTemplate>
               </asp:TemplateField>
             </Columns>
          </asp:GridView>

Use CSS to automatically add 'required field' asterisk to form inputs

You can achieve the desired result by encapsulating the HTML code in a div tag which contains the "required' class followed by the "form-group" class. *however this works only if you have Bootstrap.

<div class="form-group required">
    <div class="required">
        <label>Name:</label>
        <input type="text">
    </div>
  <div>

A simple explanation of Naive Bayes Classification

Your question as I understand it is divided in two parts, part one being you need a better understanding of the Naive Bayes classifier & part two being the confusion surrounding Training set.

In general all of Machine Learning Algorithms need to be trained for supervised learning tasks like classification, prediction etc. or for unsupervised learning tasks like clustering.

During the training step, the algorithms are taught with a particular input dataset (training set) so that later on we may test them for unknown inputs (which they have never seen before) for which they may classify or predict etc (in case of supervised learning) based on their learning. This is what most of the Machine Learning techniques like Neural Networks, SVM, Bayesian etc. are based upon.

So in a general Machine Learning project basically you have to divide your input set to a Development Set (Training Set + Dev-Test Set) & a Test Set (or Evaluation set). Remember your basic objective would be that your system learns and classifies new inputs which they have never seen before in either Dev set or test set.

The test set typically has the same format as the training set. However, it is very important that the test set be distinct from the training corpus: if we simply reused the training set as the test set, then a model that simply memorized its input, without learning how to generalize to new examples, would receive misleadingly high scores.

In general, for an example, 70% of our data can be used as training set cases. Also remember to partition the original set into the training and test sets randomly.

Now I come to your other question about Naive Bayes.

To demonstrate the concept of Naïve Bayes Classification, consider the example given below:

enter image description here

As indicated, the objects can be classified as either GREEN or RED. Our task is to classify new cases as they arrive, i.e., decide to which class label they belong, based on the currently existing objects.

Since there are twice as many GREEN objects as RED, it is reasonable to believe that a new case (which hasn't been observed yet) is twice as likely to have membership GREEN rather than RED. In the Bayesian analysis, this belief is known as the prior probability. Prior probabilities are based on previous experience, in this case the percentage of GREEN and RED objects, and often used to predict outcomes before they actually happen.

Thus, we can write:

Prior Probability of GREEN: number of GREEN objects / total number of objects

Prior Probability of RED: number of RED objects / total number of objects

Since there is a total of 60 objects, 40 of which are GREEN and 20 RED, our prior probabilities for class membership are:

Prior Probability for GREEN: 40 / 60

Prior Probability for RED: 20 / 60

Having formulated our prior probability, we are now ready to classify a new object (WHITE circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more GREEN (or RED) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:

enter image description here

enter image description here

From the illustration above, it is clear that Likelihood of X given GREEN is smaller than Likelihood of X given RED, since the circle encompasses 1 GREEN object and 3 RED ones. Thus:

enter image description here

enter image description here

Although the prior probabilities indicate that X may belong to GREEN (given that there are twice as many GREEN compared to RED) the likelihood indicates otherwise; that the class membership of X is RED (given that there are more RED objects in the vicinity of X than GREEN). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).

enter image description here

Finally, we classify X as RED since its class membership achieves the largest posterior probability.

How do you specify the Java compiler version in a pom.xml file?

maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.

For short you can use properties like this:

<properties>
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>

I'm using Maven 3.2.5.

How can I count the occurrences of a list item?

Below are the three solutions:

Fastest is using a for loop and storing it in a Dict.

import time
from collections import Counter


def countElement(a):
    g = {}
    for i in a:
        if i in g: 
            g[i] +=1
        else: 
            g[i] =1
    return g


z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]


#Solution 1 - Faster
st = time.monotonic()
for i in range(1000000):
    b = countElement(z)
et = time.monotonic()
print(b)
print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))

#Solution 2 - Fast
st = time.monotonic()
for i in range(1000000):
    a = Counter(z)
et = time.monotonic()
print (a)
print('Using collections.Counter - Duration: {}'.format(et - st))

#Solution 3 - Slow
st = time.monotonic()
for i in range(1000000):
    g = dict([(i, z.count(i)) for i in set(z)])
et = time.monotonic()
print(g)
print('Using list comprehension - Duration: {}'.format(et - st))

Result

#Solution 1 - Faster
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
Simple for loop and storing it in dict - Duration: 12.032000000000153
#Solution 2 - Fast
Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
Using collections.Counter - Duration: 15.889999999999418
#Solution 3 - Slow
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
Using list comprehension - Duration: 33.0

What's the difference between VARCHAR and CHAR?

Char has a fixed length (supports 2000 characters), it is stand for character is a data type

Varchar has a variable length (supports 4000 characters)

Find a line in a file and remove it

This solution requires the Apache Commons IO library to be added to the build path. It works by reading the entire file and writing each line back but only if the search term is not contained.

public static void removeLineFromFile(File targetFile, String searchTerm)
        throws IOException
{
    StringBuffer fileContents = new StringBuffer(
            FileUtils.readFileToString(targetFile));
    String[] fileContentLines = fileContents.toString().split(
            System.lineSeparator());

    emptyFile(targetFile);
    fileContents = new StringBuffer();

    for (int fileContentLinesIndex = 0; fileContentLinesIndex < fileContentLines.length; fileContentLinesIndex++)
    {
        if (fileContentLines[fileContentLinesIndex].contains(searchTerm))
        {
            continue;
        }

        fileContents.append(fileContentLines[fileContentLinesIndex] + System.lineSeparator());
    }

    FileUtils.writeStringToFile(targetFile, fileContents.toString().trim());
}

private static void emptyFile(File targetFile) throws FileNotFoundException,
        IOException
{
    RandomAccessFile randomAccessFile = new RandomAccessFile(targetFile, "rw");

    randomAccessFile.setLength(0);
    randomAccessFile.close();
}

Is there a difference between PhoneGap and Cordova commands?

Now a days phonegap and cordova is owned by Adobe. Only name conversation was different. For install plugin functionality , we should use same command for phonegap and cordova too.

Command : cordova plugin add cordova-plugin-photo-library

Here,

  • cordova - keyword for initiator
  • plugin - initialize a plugin
  • cordova plugin photo library - plugin name.

You can also find more plugin from https://cordova.apache.org/docs/en/latest/

Formatting text in a TextBlock

You need to use Inlines:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
    <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
</TextBlock.Inlines>

With binding:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
    <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
</TextBlock.Inlines>

You can also bind the other properties:

<TextBlock.Inlines>
    <Run FontWeight="{Binding Weight}"
         FontSize="{Binding Size}"
         Text="{Binding LineOne}" />
    <Run FontStyle="{Binding Style}"
         Foreground="Binding Colour}"
         Text="{Binding LineTwo}" />
</TextBlock.Inlines>

You can bind through converters if you have bold as a boolean (say).

How to find minimum value from vector?

#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator>  // std::begin, std::end

int main() {
    std::vector<int> v = {5,14,2,4,6};
    auto result = std::min_element(std::begin(v), std::end(v));
    if (std::end(v)!=result)
        std::cout << *result << '\n';
}

The program you show has a few problems, the primary culprit being the for condition: i<v[n]. You initialize the array, setting the first 5 elements to various values and the rest to zero. n is set to the number of elements you explicitly initialized so v[n] is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.

Some minor issues:

  • avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)

  • avoid magic numbers. int v[100] is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.

  • avoid using namespace std; It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.

How do I update/upsert a document in Mongoose?

This coffeescript works for me with Node - the trick is that the _id get's stripped of its ObjectID wrapper when sent and returned from the client and so this needs to be replaced for updates (when no _id is provided, save will revert to insert and add one).

app.post '/new', (req, res) ->
    # post data becomes .query
    data = req.query
    coll = db.collection 'restos'
    data._id = ObjectID(data._id) if data._id

    coll.save data, {safe:true}, (err, result) ->
        console.log("error: "+err) if err
        return res.send 500, err if err

        console.log(result)
        return res.send 200, JSON.stringify result

Measuring elapsed time with the Time module

Another nice way to time things is to use the with python structure.

with structure is automatically calling __enter__ and __exit__ methods which is exactly what we need to time things.

Let's create a Timer class.

from time import time

class Timer():
    def __init__(self, message):
        self.message = message
    def __enter__(self):
        self.start = time()
        return None  # could return anything, to be used like this: with Timer("Message") as value:
    def __exit__(self, type, value, traceback):
        elapsed_time = (time() - self.start) * 1000
        print(self.message.format(elapsed_time))

Then, one can use the Timer class like this:

with Timer("Elapsed time to compute some prime numbers: {}ms"):
    primes = []
    for x in range(2, 500):
        if not any(x % p == 0 for p in primes):
            primes.append(x)
    print("Primes: {}".format(primes))

The result is the following:

Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]

Elapsed time to compute some prime numbers: 5.01704216003418ms

How do I execute a file in Cygwin?

just type ./a in the shell

How to get the data-id attribute?

Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will NOT be reflected in the data() jQuery function. You have to adjust it via data() function as well.

<a data-id="123">link</a>

js:

$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321

How can I add a custom HTTP header to ajax request with js or jQuery?

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

As already pointed out, b += 1 updates b in-place, while a = a + 1 computes a + 1 and then assigns the name a to the result (now a does not refer to a row of A anymore).

To understand the += operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape:

C = np.arange(12)
for c in C:
    c += 1
print(C)  # [ 0  1  2  3  4  5  6  7  8  9 10 11]

We see that C is not updated, meaning that c += 1 and c = c + 1 are equivalent. This is because now C is a 1D array (C.ndim == 1), and so when iterating over C, each integer element is pulled out and assigned to c.

Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1 into c = c + 1, where c now refers to a new integer, not coupled to C in any way. When you loop over the reshaped arrays, whole rows (np.ndarray's) are assigned to b (and a) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1.

It should be mentioned that though + and += are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__ and __iadd__ methods, respectively.

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Center image in table td in CSS

This fixed issues for me:

<style>
.super-centered {
    position:absolute; 
    width:100%;
    height:100%;
    text-align:center; 
    vertical-align:middle;
    z-index: 9999;
}
</style>

<table class="super-centered"><tr><td style="width:100%;height:100%;" align="center"     valign="middle" > 
<img alt="Loading ..." src="/ALHTheme/themes/html/ALHTheme/images/loading.gif">
</td></tr></table>

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

Best way to get value from Collection by index

You can get the value from collection using for-each loop or using iterator interface. For a Collection c for (<ElementType> elem: c) System.out.println(elem); or Using Iterator Interface

 Iterator it = c.iterator(); 
        while (it.hasNext()) 
        System.out.println(it.next()); 

Switch with if, else if, else, and loops inside case

Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:

boolean found = false;

case 1:

for (Element arrayItem : array) {
    if (arrayItem == whateverValue) {
        found = true;    
    } // else if ...
}
if (found) {
    break;
}
case 2:

Comparing two input values in a form validation with AngularJS

I recently wrote a custom directive which can be generic enough to do any validation. It take a validation function from the current scope

module.directive('customValidator', [function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: { validateFunction: '&' },
            link: function (scope, elm, attr, ngModelCtrl) {
                ngModelCtrl.$parsers.push(function (value) {
                    var result = scope.validateFunction({ 'value': value });
                    if (result || result === false) {
                        if (result.then) {
                            result.then(function (data) {           //For promise type result object
                                ngModelCtrl.$setValidity(attr.customValidator, data);
                            }, function (error) {
                                ngModelCtrl.$setValidity(attr.customValidator, false);
                            });
                        }
                        else {
                            ngModelCtrl.$setValidity(attr.customValidator, result);
                            return result ? value : undefined;      //For boolean result return based on boolean value
                        }
                    }
                    return value;
                });
            }
        };
    }]);

To use it you do

<input type="email" name="email2" ng-model="emailReg2" custom-validator='emailMatch' data-validate-function='checkEmailMatch(value)'>
<span ng-show="registerForm.email2.$error.emailMatch">Emails have to match!</span>

In you controller then you can implement the method, that should return true or false

$scope.checkEmailMatch=function(value) {
    return value===$scope.emailReg;
}

The advantage is that you do not have to write custom directive for each custom validation.

Concrete Javascript Regex for Accented Characters (Diacritics)

The accented Latin range \u00C0-\u017F was not quite enough for my database of names, so I extended the regex to

[a-zA-Z\u00C0-\u024F]
[a-zA-Z\u00C0-\u024F\u1E00-\u1EFF] // includes even more Latin chars

I added these code blocks (\u00C0-\u024F includes three adjacent blocks at once):

Note that \u00C0-\u00FF is actually only a part of Latin-1 Supplement. It skips unprintable control signals and all symbols except for the awkwardly-placed multiply × \u00D7 and divide ÷ \u00F7.

[a-zA-Z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u024F] // exclude ×÷

If you need more code points, you can find more ranges on Wikipedia's List of Unicode characters. For example, you could also add Latin Extended-C, D, and E, but I left them out because only historians seem interested in them now, and the D and E sets don't even render correctly in my browser.

The original regex stopping at \u017F borked on the name "?enol". According to FontSpace's Unicode Analyzer, that first character is \u0218, LATIN CAPITAL LETTER S WITH COMMA BELOW. (Yeah, it's usually spelled with a cedilla-S \u015E, "Senol." But I'm not flying to Turkey to go tell him, "You're spelling your name wrong!")

Why use 'virtual' for class properties in Entity Framework model definitions?

In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

UITableView Separator line

Here's the way to do this via storyboard in XCode 10.2.1. Separator defaults to default which is the line. Set it to none to remove the line.

tableview_separator

Display a float with two decimal places in Python

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

How can I change the Java Runtime Version on Windows (7)?

Once I updated my Java version to 8 as suggested by browser. However I had selected to uninstall previous Java 6 version I have been used for coding my projects. When I enter the command in "java -version" in cmd it showed 1.8 and I could not start eclipse IDE run on Java 1.6.

When I installed Java 8 update for the browser it had changed the "PATH" System variable appending "C:\ProgramData\Oracle\Java\javapath" to the beginning. Newly added path pointed to Java vesion 8. So I removed that path from "PATH" System variable and everything worked fine. :)

JSON and XML comparison

The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

Best Python IDE on Linux

I haven't played around with it much but eclipse/pydev feels nice.

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

How to create a JavaScript callback for knowing when an image is loaded?

If you are using React.js, you could do this:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

  • How to submit an HTML form on loading the page?

    You can try also using below script

    <html>
    <head>
    <script>
    function load()
    {
    document.frm1.submit()
    }
    </script>
    </head>
    
    <body onload="load()">
    <form action="http://www.google.com" id="frm1" name="frm1">
    <input type="text" value="" />
    </form>
    </body>
    </html> 
    

    What exactly is RESTful programming?

    REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the server and the resources it hosts. The key constraint is that the server and client must both agree on the media used, which in the case of the web is HTML.

    An API that adheres to the principles of REST does not require the client to know anything about the structure of the API. Rather, the server needs to provide whatever information the client needs to interact with the service. An HTML form is an example of this: The server specifies the location of the resource and the required fields. The browser doesn't know in advance where to submit the information, and it doesn't know in advance what information to submit. Both forms of information are entirely supplied by the server. (This principle is called HATEOAS: Hypermedia As The Engine Of Application State.)

    So, how does this apply to HTTP, and how can it be implemented in practice? HTTP is oriented around verbs and resources. The two verbs in mainstream usage are GET and POST, which I think everyone will recognize. However, the HTTP standard defines several others such as PUT and DELETE. These verbs are then applied to resources, according to the instructions provided by the server.

    For example, Let's imagine that we have a user database that is managed by a web service. Our service uses a custom hypermedia based on JSON, for which we assign the mimetype application/json+userdb (There might also be an application/xml+userdb and application/whatever+userdb - many media types may be supported). The client and the server have both been programmed to understand this format, but they don't know anything about each other. As Roy Fielding points out:

    A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.

    A request for the base resource / might return something like this:

    Request

    GET /
    Accept: application/json+userdb
    

    Response

    200 OK
    Content-Type: application/json+userdb
    
    {
        "version": "1.0",
        "links": [
            {
                "href": "/user",
                "rel": "list",
                "method": "GET"
            },
            {
                "href": "/user",
                "rel": "create",
                "method": "POST"
            }
        ]
    }
    

    We know from the description of our media that we can find information about related resources from sections called "links". This is called Hypermedia controls. In this case, we can tell from such a section that we can find a user list by making another request for /user:

    Request

    GET /user
    Accept: application/json+userdb
    

    Response

    200 OK
    Content-Type: application/json+userdb
    
    {
        "users": [
            {
                "id": 1,
                "name": "Emil",
                "country: "Sweden",
                "links": [
                    {
                        "href": "/user/1",
                        "rel": "self",
                        "method": "GET"
                    },
                    {
                        "href": "/user/1",
                        "rel": "edit",
                        "method": "PUT"
                    },
                    {
                        "href": "/user/1",
                        "rel": "delete",
                        "method": "DELETE"
                    }
                ]
            },
            {
                "id": 2,
                "name": "Adam",
                "country: "Scotland",
                "links": [
                    {
                        "href": "/user/2",
                        "rel": "self",
                        "method": "GET"
                    },
                    {
                        "href": "/user/2",
                        "rel": "edit",
                        "method": "PUT"
                    },
                    {
                        "href": "/user/2",
                        "rel": "delete",
                        "method": "DELETE"
                    }
                ]
            }
        ],
        "links": [
            {
                "href": "/user",
                "rel": "create",
                "method": "POST"
            }
        ]
    }
    

    We can tell a lot from this response. For instance, we now know we can create a new user by POSTing to /user:

    Request

    POST /user
    Accept: application/json+userdb
    Content-Type: application/json+userdb
    
    {
        "name": "Karl",
        "country": "Austria"
    }
    

    Response

    201 Created
    Content-Type: application/json+userdb
    
    {
        "user": {
            "id": 3,
            "name": "Karl",
            "country": "Austria",
            "links": [
                {
                    "href": "/user/3",
                    "rel": "self",
                    "method": "GET"
                },
                {
                    "href": "/user/3",
                    "rel": "edit",
                    "method": "PUT"
                },
                {
                    "href": "/user/3",
                    "rel": "delete",
                    "method": "DELETE"
                }
            ]
        },
        "links": {
           "href": "/user",
           "rel": "list",
           "method": "GET"
        }
    }
    

    We also know that we can change existing data:

    Request

    PUT /user/1
    Accept: application/json+userdb
    Content-Type: application/json+userdb
    
    {
        "name": "Emil",
        "country": "Bhutan"
    }
    

    Response

    200 OK
    Content-Type: application/json+userdb
    
    {
        "user": {
            "id": 1,
            "name": "Emil",
            "country": "Bhutan",
            "links": [
                {
                    "href": "/user/1",
                    "rel": "self",
                    "method": "GET"
                },
                {
                    "href": "/user/1",
                    "rel": "edit",
                    "method": "PUT"
                },
                {
                    "href": "/user/1",
                    "rel": "delete",
                    "method": "DELETE"
                }
            ]
        },
        "links": {
           "href": "/user",
           "rel": "list",
           "method": "GET"
        }
    }
    

    Notice that we are using different HTTP verbs (GET, PUT, POST, DELETE etc.) to manipulate these resources, and that the only knowledge we presume on the client's part is our media definition.

    Further reading:

    (This answer has been the subject of a fair amount of criticism for missing the point. For the most part, that has been a fair critique. What I originally described was more in line with how REST was usually implemented a few years ago when I first wrote this, rather than its true meaning. I've revised the answer to better represent the real meaning.)

    Programmatically go back to previous ViewController in Swift

    Swift 3, Swift 4

    if movetoroot { 
        navigationController?.popToRootViewController(animated: true)
    } else {
        navigationController?.popViewController(animated: true)
    }
    

    navigationController is optional because there might not be one.

    Easy way to build Android UI?

    The Android Development Tools (ADT) plugin for Eclipse includes a visual editor for android application layout files:

    http://developer.android.com/tools/help/adt.html

    Number of days between past date and current date in Google spreadsheet

    Since this is the top Google answer for this, and it was way easier than I expected, here is the simple answer. Just subtract date1 from date2.

    If this is your spreadsheet dates

         A            B
    1 10/11/2017  12/1/2017
    

    =(B1)-(A1)

    results in 51, which is the number of days between a past date and a current date in Google spreadsheet

    As long as it is a date format Google Sheets recognizes, you can directly subtract them and it will be correct.

    To do it for a current date, just use the =TODAY() function.

    =TODAY()-A1

    While today works great, you can't use a date directly in the formula, you should referencing a cell that contains a date.

    =(12/1/2017)-(10/1/2017) results in 0.0009915716411, not 61.

    How to create a file on Android Internal Storage?

    I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.

    If you execute the following statement:

    File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
    resolveMe.createNewFile();
    

    It will resolve the path to the root /data/ somewhere higher up in Android.

    I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.

    File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
    resolveMeSDCard.createNewFile();
    

    A quick fix would be to change your following code:

    File f = new File(getLocalPath().replace("/data/data/", "/"));
    

    Hope this helps

    How to define constants in ReactJS

    You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

    import React from "react";
    
    const sizeToLetterMap = {
      small_square: 's',
      large_square: 'q',
      thumbnail: 't',
      small_240: 'm',
      small_320: 'n',
      medium_640: 'z',
      medium_800: 'c',
      large_1024: 'b',
      large_1600: 'h',
      large_2048: 'k',
      original: 'o'
    };
    
    class PhotoComponent extends React.Component {
      constructor(args) {
        super(args);
      }
    
      photoUrl(image, size_text) {
        return (<span>
          Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
        </span>);
      }
    
      render() {
        return (
          <div className="photo-wrapper">
            The url is: {this.photoUrl(this.props.image, this.props.size_text)}
          </div>
        )
      }
    }
    
    export default PhotoComponent;
    
    // Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
    // Of course the component must first be imported where used, example:
    // import PhotoComponent from "./photo_component.jsx";
    

    Getting "unixtime" in Java

    Java 8 added a new API for working with dates and times. With Java 8 you can use

    import java.time.Instant
    ...
    long unixTimestamp = Instant.now().getEpochSecond();
    

    Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

    Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

    OK so I think i know the issue you're having.

    Basically, because Composer can't see the migration files you are creating, you are having to run the dump-autoload command which won't download anything new, but looks for all of the classes it needs to include again. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php), and this is why your migration is working after you run that command.

    How to fix it (possibly) You need to add some extra information to your composer.json file.

    "autoload": {
        "classmap": [
            "PATH TO YOUR MIGRATIONS FOLDER"
        ],
    }
    

    You need to add the path to your migrations folder to the classmap array. Then run the following three commands...

    php artisan clear-compiled 
    composer dump-autoload
    php artisan optimize
    

    This will clear the current compiled files, update the classes it needs and then write them back out so you don't have to do it again.

    Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticable).

    Hope you can manage to get this sorted, as its very annoying indeed :(

    Select a date from date picker using Selenium webdriver

    try this,

    http://seleniumcapsules.blogspot.com/2012/10/design-of-datepicker.html

    1. an icon used as a trigger;
    2. display a calendar when the icon is clicked;
    3. Previous Year button(<<), optional;
    4. Next Year Button(>>), optional;
    5. Previous Month button(<);
    6. Next Month button(>);
    7. day buttons;
    8. Weekday indicators;
    9. Calendar title i.e. "September, 2011" which representing current month and current year.

    Decimal separator comma (',') with numberDecimal inputType in EditText

    to get localize your input use:

    char sep = DecimalFormatSymbols.getInstance().getDecimalSeparator();
    

    and then add:

    textEdit.setKeyListener(DigitsKeyListener.getInstance("0123456789" + sep));
    

    than don't forget to replace "," with "." so Float or Double can parse it without errors.

    How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

    While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

    This can be resolved by specifying a primary key on the @new_super table, as follows:

    DECLARE @new_super TABLE (
      row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
      super_id   int
    );
    

    This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

    MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

    First thing to do is run this:

    SHOW GRANTS;
    

    You will quickly see you were assigned the anonymous user to authenticate into mysql.

    Instead of logging into mysql with

    mysql
    

    login like this:

    mysql -uroot
    

    By default, root@localhost has all rights and no password.

    If you cannot login as root without a password, do the following:

    Step 01) Add the two options in the mysqld section of my.ini:

    [mysqld]
    skip-grant-tables
    skip-networking
    

    Step 02) Restart mysql

    net stop mysql
    <wait 10 seconds>
    net start mysql
    

    Step 03) Connect to mysql

    mysql
    

    Step 04) Create a password from root@localhost

    UPDATE mysql.user SET password=password('whateverpasswordyoulike')
    WHERE user='root' AND host='localhost';
    exit
    

    Step 05) Restart mysql

    net stop mysql
    <wait 10 seconds>
    net start mysql
    

    Step 06) Login as root with password

    mysql -u root -p
    

    You should be good from there.

    CAVEAT: Please remove anonymous users !!!

    Populate unique values into a VBA array from Excel

    one more way ...

    Sub get_unique()
    Dim unique_string As String
        lr = Sheets("data").Cells(Sheets("data").Rows.Count, 1).End(xlUp).Row
        Set range1 = Sheets("data").Range("A2:A" & lr)
        For Each cel In range1
           If Not InStr(output, cel.Value) > 0 Then
               unique_string = unique_string & cel.Value & ","
           End If
        Next
    End Sub
    

    how to display progress while loading a url to webview in android?

    You will have to over ride onPageStarted and onPageFinished callbacks

    mWebView.setWebViewClient(new WebViewClient() {
    
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (progressBar!= null && progressBar.isShowing()) {
                    progressBar.dismiss();
                }
                progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
            }
    
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
    
                return true;
            }
    
            public void onPageFinished(WebView view, String url) {
                if (progressBar.isShowing()) {
                    progressBar.dismiss();
                }
            }
    
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                alertDialog.setTitle("Error");
                alertDialog.setMessage(description);
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
                alertDialog.show();
            }
        });
    

    Looping through all the properties of object php

    Before you run the $object through a foreach loop you have to convert it to an array:

    $array = (array) $object;  
    
     foreach($array as $key=>$val){
          echo "$key: $val";
          echo "<br>";
     }
    

    Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

    I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

    Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

    HTML input field hint

    I think for your situation, the easy and simple for your html input , you can probably add the attribute title

    <input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">
    

    In Postgresql, force unique on combination of two columns

    CREATE TABLE someTable (
        id serial PRIMARY KEY,
        col1 int NOT NULL,
        col2 int NOT NULL,
        UNIQUE (col1, col2)
    )
    

    autoincrement is not postgresql. You want a serial.

    If col1 and col2 make a unique and can't be null then they make a good primary key:

    CREATE TABLE someTable (
        col1 int NOT NULL,
        col2 int NOT NULL,
        PRIMARY KEY (col1, col2)
    )
    

    How do I install a pip package globally instead of locally?

    Maybe --force-reinstall would work, otherwise --ignore-installed should do the trick.

    Change form size at runtime in C#

    As a complement to the answers given above; do not forget about Form MinimumSize Property, in case you require to create smaller Forms.

    Example Bellow:

    private void SetDefaultWindowSize()
    {
       int sizeW, sizeH;
       sizeW = 180;
       sizeH = 100;
    
       var size = new Size(sizeW, sizeH);
    
       Size = size;
       MinimumSize = size;
    }
    
    private void SetNewSize()
    {
       Size = new Size(Width, 10);
    }
    

    YAML mapping values are not allowed in this context

    The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

    jobs:
     - - name: A
       - schedule: "0 0/5 * 1/1 * ? *"
       - - type: mongodb.cluster
         - config:
           - host: mongodb://localhost:27017/admin?replicaSet=rs
           - minSecondaries: 2
           - minOplogHours: 100
           - maxSecondaryDelay: 120
     - - name: B
       - schedule: "0 0/5 * 1/1 * ? *"
       - - type: mongodb.cluster
         - config:
           - host: mongodb://localhost:27017/admin?replicaSet=rs
           - minSecondaries: 2
           - minOplogHours: 100
           - maxSecondaryDelay: 120
    

    Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

    How to write LDAP query to test if user is member of a group?

    I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

    Expand div to max width when float:left is set

    Hi there is an easy way with overflow hidden method on right element.

    _x000D_
    _x000D_
        .content .left {_x000D_
            float:left;_x000D_
            width:100px;_x000D_
            background-color:green;_x000D_
          }_x000D_
          .content .right {_x000D_
            overflow: hidden;_x000D_
            background-color:red;_x000D_
          }
    _x000D_
    <!DOCTYPE html>   _x000D_
    <html lang="en">     _x000D_
        <head>      _x000D_
               _x000D_
            <title>Content Menu</title>         _x000D_
              _x000D_
        </head>_x000D_
        <body>    _x000D_
        <div class="content">_x000D_
          <div class="left">_x000D_
            <p>Hi, Flo! I am Left</p>_x000D_
          </div>_x000D_
          <div class="right">  _x000D_
            <p>is</p>_x000D_
            <p>this</p>_x000D_
            <p>what</p>_x000D_
            <p>you are looking for?</p>_x000D_
            <p> It done with overflow hidden and result is same.</p>_x000D_
          </div>_x000D_
        </div>_x000D_
        </body>_x000D_
    </html> 
    _x000D_
    _x000D_
    _x000D_

    Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

    I have fixed this issue by logging in using Xorg. By default, I have used Wayland. It looks like Wayland eliminates most of the design flaws of the Xorg it has its own issues.enter image description here

    How to determine whether a substring is in a different string

    People mentioned string.find(), string.index(), and string.indexOf() in the comments, and I summarize them here (according to the Python Documentation):

    First of all there is not a string.indexOf() method. The link posted by Deviljho shows this is a JavaScript function.

    Second the string.find() and string.index() actually return the index of a substring. The only difference is how they handle the substring not found situation: string.find() returns -1 while string.index() raises an ValueError.

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

    Here is a simple customview for display circle progress. You can modify and optimize more to suitable for your project.

    class CircleProgressBar @JvmOverloads constructor(
            context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
    ) : View(context, attrs, defStyleAttr) {
        private val backgroundWidth = 10f
        private val progressWidth = 20f
    
        private val backgroundPaint = Paint().apply {
            color = Color.LTGRAY
            style = Paint.Style.STROKE
            strokeWidth = backgroundWidth
            isAntiAlias = true
        }
    
        private val progressPaint = Paint().apply {
            color = Color.RED
            style = Paint.Style.STROKE
            strokeWidth = progressWidth
            isAntiAlias = true
        }
    
        var progress: Float = 0f
            set(value) {
                field = value
                invalidate()
            }
    
        private val oval = RectF()
        private var centerX: Float = 0f
        private var centerY: Float = 0f
        private var radius: Float = 0f
    
        override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            centerX = w.toFloat() / 2
            centerY = h.toFloat() / 2
            radius = w.toFloat() / 2 - progressWidth
            oval.set(centerX - radius,
                    centerY - radius,
                    centerX + radius,
                    centerY + radius)
            super.onSizeChanged(w, h, oldw, oldh)
        }
    
        override fun onDraw(canvas: Canvas?) {
            super.onDraw(canvas)
            canvas?.drawCircle(centerX, centerY, radius, backgroundPaint)
            canvas?.drawArc(oval, 270f, 360f * progress, false, progressPaint)
        }
    }
    

    Example using

    xml

    <com.example.androidcircleprogressbar.CircleProgressBar
        android:id="@+id/circle_progress"
        android:layout_width="200dp"
        android:layout_height="200dp" />
    

    kotlin

    class MainActivity : AppCompatActivity() {
        val TOTAL_TIME = 10 * 1000L
    
        override fun onCreate(savedInstanceState: Bundle?) {
            ...
    
            timeOutRemoveTimer.start()
        }
    
        private var timeOutRemoveTimer = object : CountDownTimer(TOTAL_TIME, 10) {
            override fun onFinish() {
                circle_progress.progress = 1f
            }
    
            override fun onTick(millisUntilFinished: Long) {
                circle_progress.progress = (TOTAL_TIME - millisUntilFinished).toFloat() / TOTAL_TIME
            }
        }
    }
    

    Result

    Splitting String and put it on int array

    List<String> stringList = new ArrayList<String>(Arrays.asList(arr.split(",")));
    List<Integer> intList = new ArrayList<Integer>();
    for (String s : stringList) 
       intList.add(Integer.valueOf(s));
    

    version `CXXABI_1.3.8' not found (required by ...)

    GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

    export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH
    

    Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

    Starting iPhone app development in Linux?

    If you value your time, buy a Mac! I don't know enough about Linux development options to offer a viable solution, but it seems the proposed methods involve some pretty roundabout work. If you plan on seriously writing and selling iPhone apps, I think you could easily recoup the cost of a Mac Mini or Macbook. :-)

    Android ListView with different layouts for each row

    Take a look in the code below.

    First, we create custom layouts. In this case, four types.

    even.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff500000"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/white"
            android:layout_width="match_parent"
            android:layout_gravity="center"
            android:textSize="24sp"
            android:layout_height="wrap_content" />
    
     </LinearLayout>
    

    odd.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff001f50"
        android:gravity="right"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/white"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:textSize="28sp"
            android:layout_height="wrap_content"  />
    
     </LinearLayout>
    

    white.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ffffffff"
        android:gravity="right"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/black"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:textSize="28sp"
            android:layout_height="wrap_content"   />
    
     </LinearLayout>
    

    black.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:background="#ff000000"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/text"
            android:textColor="@android:color/white"
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:textSize="33sp"
            android:layout_height="wrap_content"   />
    
     </LinearLayout>
    

    Then, we create the listview item. In our case, with a string and a type.

    public class ListViewItem {
            private String text;
            private int type;
    
            public ListViewItem(String text, int type) {
                this.text = text;
                this.type = type;
            }
    
            public String getText() {
                return text;
            }
    
            public void setText(String text) {
                this.text = text;
            }
    
            public int getType() {
                return type;
            }
    
            public void setType(int type) {
                this.type = type;
            }
    
        }
    

    After that, we create a view holder. It's strongly recommended because Android OS keeps the layout reference to reuse your item when it disappears and appears back on the screen. If you don't use this approach, every single time that your item appears on the screen Android OS will create a new one and causing your app to leak memory.

    public class ViewHolder {
            TextView text;
    
            public ViewHolder(TextView text) {
                this.text = text;
            }
    
            public TextView getText() {
                return text;
            }
    
            public void setText(TextView text) {
                this.text = text;
            }
    
        }
    

    Finally, we create our custom adapter overriding getViewTypeCount() and getItemViewType(int position).

    public class CustomAdapter extends ArrayAdapter {
    
            public static final int TYPE_ODD = 0;
            public static final int TYPE_EVEN = 1;
            public static final int TYPE_WHITE = 2;
            public static final int TYPE_BLACK = 3;
    
            private ListViewItem[] objects;
    
            @Override
            public int getViewTypeCount() {
                return 4;
            }
    
            @Override
            public int getItemViewType(int position) {
                return objects[position].getType();
            }
    
            public CustomAdapter(Context context, int resource, ListViewItem[] objects) {
                super(context, resource, objects);
                this.objects = objects;
            }
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
    
                ViewHolder viewHolder = null;
                ListViewItem listViewItem = objects[position];
                int listViewItemType = getItemViewType(position);
    
    
                if (convertView == null) {
    
                    if (listViewItemType == TYPE_EVEN) {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_even, null);
                    } else if (listViewItemType == TYPE_ODD) {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_odd, null);
                    } else if (listViewItemType == TYPE_WHITE) {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_white, null);
                    } else {
                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.type_black, null);
                    }
    
                    TextView textView = (TextView) convertView.findViewById(R.id.text);
                    viewHolder = new ViewHolder(textView);
    
                    convertView.setTag(viewHolder);
    
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }
    
                viewHolder.getText().setText(listViewItem.getText());
    
                return convertView;
            }
    
        }
    

    And our activity is something like this:

    private ListView listView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_main); // here, you can create a single layout with a listview
    
            listView = (ListView) findViewById(R.id.listview);
    
            final ListViewItem[] items = new ListViewItem[40];
    
            for (int i = 0; i < items.length; i++) {
                if (i == 4) {
                    items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE);
                } else if (i == 9) {
                    items[i] = new ListViewItem("Black " + i, CustomAdapter.TYPE_BLACK);
                } else if (i % 2 == 0) {
                    items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN);
                } else {
                    items[i] = new ListViewItem("ODD " + i, CustomAdapter.TYPE_ODD);
                }
            }
    
            CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
            listView.setAdapter(customAdapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                    Toast.makeText(getBaseContext(), items[i].getText(), Toast.LENGTH_SHORT).show();
                }
            });
    
        }
    }
    

    now create a listview inside mainactivity.xml like this

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.example.shivnandan.gygy.MainActivity">
    
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">
    
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />
    
        </android.support.design.widget.AppBarLayout>
    
        <include layout="@layout/content_main" />
    
        <ListView
            android:layout_width="match_parent"
    
            android:layout_height="match_parent"
    
            android:id="@+id/listView"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
    
    
            android:layout_marginTop="100dp" />
    
    </android.support.design.widget.CoordinatorLayout>
    

    What is the method for converting radians to degrees?

    radians = degrees * (pi/180)
    
    degrees = radians * (180/pi)
    

    As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion here

    How to customize the configuration file of the official PostgreSQL Docker image?

    I was also using the official image (FROM postgres) and I was able to change the config by executing the following commands.

    The first thing is to locate the PostgreSQL config file. This can be done by executing this command in your running database.

    SHOW config_file;
    

    I my case it returns /data/postgres/postgresql.conf.

    The next step is to find out what is the hash of your running PostgreSQL docker container.

    docker ps -a
    

    This should return a list of all the running containers. In my case it looks like this.

    ...
    0ba35e5427d9    postgres    "docker-entrypoint.s…" ....
    ...
    

    Now you have to switch to the bash inside your container by executing:

    docker exec -it 0ba35e5427d9 /bin/bash
    

    Inside the container check if the config is at the correct path and display it.

    cat /data/postgres/postgresql.conf
    

    I wanted to change the max connections from 100 to 1000 and the shared buffer from 128MB to 3GB. With the sed command I can do a search and replace with the corresponding variables ins the config.

    sed -i -e"s/^max_connections = 100.*$/max_connections = 1000/" /data/postgres/postgresql.conf
    sed -i -e"s/^shared_buffers = 128MB.*$/shared_buffers = 3GB/" /data/postgres/postgresql.conf
    

    The last thing we have to do is to restart the database within the container. Find out which version you of PostGres you are using.

    cd /usr/lib/postgresql/
    ls 
    

    In my case its 12 So you can now restart the database by executing the following command with the correct version in place.

    su - postgres -c "PGDATA=$PGDATA /usr/lib/postgresql/12/bin/pg_ctl -w restart"
    

    Zip folder in C#

    using DotNetZip (available as nuget package):

    public void Zip(string source, string destination)
    {
        using (ZipFile zip = new ZipFile
        {
            CompressionLevel = CompressionLevel.BestCompression
        })
        {
            var files = Directory.GetFiles(source, "*",
                SearchOption.AllDirectories).
                Where(f => Path.GetExtension(f).
                    ToLowerInvariant() != ".zip").ToArray();
    
            foreach (var f in files)
            {
                zip.AddFile(f, GetCleanFolderName(source, f));
            }
    
            var destinationFilename = destination;
    
            if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
            {
                destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
            }
    
            zip.Save(destinationFilename);
        }
    }
    
    private string GetCleanFolderName(string source, string filepath)
    {
        if (string.IsNullOrWhiteSpace(filepath))
        {
            return string.Empty;
        }
    
        var result = filepath.Substring(source.Length);
    
        if (result.StartsWith("\\"))
        {
            result = result.Substring(1);
        }
    
        result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);
    
        return result;
    }
    

    Usage:

    Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");
    

    Or

    Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");
    

    How to zip a whole folder using PHP

    I tried with the code below and it is working. The code is self explanatory, please let me know if you have any questions.

    <?php
    class FlxZipArchive extends ZipArchive 
    {
     public function addDir($location, $name) 
     {
           $this->addEmptyDir($name);
           $this->addDirDo($location, $name);
     } 
     private function addDirDo($location, $name) 
     {
        $name .= '/';
        $location .= '/';
        $dir = opendir ($location);
        while ($file = readdir($dir))
        {
            if ($file == '.' || $file == '..') continue;
            $do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
            $this->$do($location . $file, $name . $file);
        }
     } 
    }
    ?>
    
    <?php
    $the_folder = '/path/to/folder/to/be/zipped';
    $zip_file_name = '/path/to/zip/archive.zip';
    $za = new FlxZipArchive;
    $res = $za->open($zip_file_name, ZipArchive::CREATE);
    if($res === TRUE) 
    {
        $za->addDir($the_folder, basename($the_folder));
        $za->close();
    }
    else{
    echo 'Could not create a zip archive';
    }
    ?>
    

    How do I use the built in password reset/change views with my own templates

    If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

    The b-list has a good introduction to context processors.

    Edit (I seem to have been confused about what the actual question was):

    You'll notice that password_reset takes a named parameter called template_name:

    def password_reset(request, is_admin_site=False, 
                template_name='registration/password_reset_form.html',
                email_template_name='registration/password_reset_email.html',
                password_reset_form=PasswordResetForm, 
                token_generator=default_token_generator,
                post_reset_redirect=None):
    

    Check password_reset for more information.

    ... thus, with a urls.py like:

    from django.conf.urls.defaults import *
    from django.contrib.auth.views import password_reset
    
    urlpatterns = patterns('',
         (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
         ...
    )
    

    django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

    Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

    In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

    Split bash string by newline characters

    Another way:

    x=$'Some\nstring'
    readarray -t y <<<"$x"
    

    Or, if you don't have bash 4, the bash 3.2 equivalent:

    IFS=$'\n' read -rd '' -a y <<<"$x"
    

    You can also do it the way you were initially trying to use:

    y=(${x//$'\n'/ })
    

    This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

    IFS=$'\n' y=(${x//$'\n'/ })
    

    ...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

    IFS=$'\n' y=($x)
    

    This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

    C++ where to initialize static const

    In a translation unit within the same namespace, usually at the top:

    // foo.h
    struct foo
    {
        static const std::string s;
    };
    
    // foo.cpp
    const std::string foo::s = "thingadongdong"; // this is where it lives
    
    // bar.h
    namespace baz
    {
        struct bar
        {
            static const float f;
        };
    }
    
    // bar.cpp
    namespace baz
    {
        const float bar::f = 3.1415926535;
    }
    

    Using colors with printf

    This is a small program to get different color on terminal.

    #include <stdio.h>
    
    #define KNRM  "\x1B[0m"
    #define KRED  "\x1B[31m"
    #define KGRN  "\x1B[32m"
    #define KYEL  "\x1B[33m"
    #define KBLU  "\x1B[34m"
    #define KMAG  "\x1B[35m"
    #define KCYN  "\x1B[36m"
    #define KWHT  "\x1B[37m"
    
    int main()
    {
        printf("%sred\n", KRED);
        printf("%sgreen\n", KGRN);
        printf("%syellow\n", KYEL);
        printf("%sblue\n", KBLU);
        printf("%smagenta\n", KMAG);
        printf("%scyan\n", KCYN);
        printf("%swhite\n", KWHT);
        printf("%snormal\n", KNRM);
    
        return 0;
    }
    

    bootstrap 3 tabs not working properly

    In my case, I have two elements with the same id. I could not notice the cause of problem for a long time, because the first such element was hidden.

    How would I access variables from one class to another?

    we can access/pass arguments/variables from one class to another class using object reference.

    #Class1
    class Test:
        def __init__(self):
            self.a = 10
            self.b = 20
            self.add = 0
    
        def calc(self):
            self.add = self.a+self.b
    
    #Class 2
    class Test2:
        def display(self):
            print('adding of two numbers: ',self.add)
    #creating object for Class1
    obj = Test()
    #invoking calc method()
    obj.calc()
    #passing class1 object to class2
    Test2.display(obj)
    

    How can I list all cookies for the current page with Javascript?

    var x = document.cookie; 
    window.alert(x);
    

    This displays every cookie the current site has access to. If you for example have created two cookies "username=Frankenstein" and "username=Dracula", these two lines of code will display "username=Frankenstein; username=Dracula". However, information such as expiry date will not be shown.

    'typeid' versus 'typeof' in C++

    C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.

    typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.

    Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.

    Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

    What does the "static" modifier after "import" mean?

    See Documentation

    The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

    So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

    Storing Objects in HTML5 localStorage

    A minor improvement on a variant:

    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    }
    
    Storage.prototype.getObject = function(key) {
        var value = this.getItem(key);
        return value && JSON.parse(value);
    }
    

    Because of short-circuit evaluation, getObject() will immediately return null if key is not in Storage. It also will not throw a SyntaxError exception if value is "" (the empty string; JSON.parse() cannot handle that).

    Export HTML page to PDF on user click using JavaScript

    This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

    change it to:

    $(function () {
    
        var specialElementHandlers = {
            '#editor': function (element,renderer) {
                return true;
            }
        };
     $('#cmd').click(function () {
            var doc = new jsPDF();
            doc.fromHTML(
                $('#target').html(), 15, 15, 
                { 'width': 170, 'elementHandlers': specialElementHandlers }, 
                function(){ doc.save('sample-file.pdf'); }
            );
    
        });  
    });
    

    and it will work.

    how to align img inside the div to the right?

    <style type="text/css">
    >> .imgTop {
    >>  display: block;
    >>  text-align: right;
    >>  }
    >> </style>
    
    <img class="imgTop" src="imgName.gif" alt="image description" height="100" width="100">
    

    Why is it OK to return a 'vector' from a function?

    Can we guarantee it will not die?

    As long there is no reference returned, it's perfectly fine to do so. words will be moved to the variable receiving the result.

    The local variable will go out of scope. after it was moved (or copied).

    What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

    Directly from the Windows.h header file:

    #ifndef WIN32_LEAN_AND_MEAN
        #include <cderr.h>
        #include <dde.h>
        #include <ddeml.h>
        #include <dlgs.h>
        #ifndef _MAC
            #include <lzexpand.h>
            #include <mmsystem.h>
            #include <nb30.h>
            #include <rpc.h>
        #endif
        #include <shellapi.h>
        #ifndef _MAC
            #include <winperf.h>
            #include <winsock.h>
        #endif
        #ifndef NOCRYPT
            #include <wincrypt.h>
            #include <winefs.h>
            #include <winscard.h>
        #endif
    
        #ifndef NOGDI
            #ifndef _MAC
                #include <winspool.h>
                #ifdef INC_OLE1
                    #include <ole.h>
                #else
                    #include <ole2.h>
                #endif /* !INC_OLE1 */
            #endif /* !MAC */
            #include <commdlg.h>
        #endif /* !NOGDI */
    #endif /* WIN32_LEAN_AND_MEAN */
    

    if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

    Also, from Microsoft's support page:

    To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

    VC_EXTRALEAN
    WIN32_LEAN_AND_MEAN

    You can use them to reduce the size of the Win32 header files.

    Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

    ERROR 1064 (42000): You have an error in your SQL syntax;

    Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.

    How to get child element by class name?

    Here is how I did it using the YUI selectors. Thanks to Hank Gay's suggestion.

    notes = YAHOO.util.Dom.getElementsByClassName('four','span','test');
    

    where four = classname, span = the element type/tag name, and test = the parent id.

    Java - How to find the redirected url of a url?

    You need to cast the URLConnection to HttpURLConnection and instruct it to not follow the redirects by setting HttpURLConnection#setInstanceFollowRedirects() to false. You can also set it globally by HttpURLConnection#setFollowRedirects().

    You only need to handle redirects yourself then. Check the response code by HttpURLConnection#getResponseCode(), grab the Location header by URLConnection#getHeaderField() and then fire a new HTTP request on it.

    Textarea that can do syntax highlighting on the fly?

    Here is the response I've done to a similar question (Online Code Editor) on programmers:

    First, you can take a look to this article:
    Wikipedia - Comparison of JavaScript-based source code editors.

    For more, here is some tools that seem to fit with your request:

    • EditArea - Demo as FileEditor who is a Yii Extension - (Apache Software License, BSD, LGPL)

      Here is EditArea, a free javascript editor for source code. It allow to write well formated source code with line numerotation, tab support, search & replace (with regexp) and live syntax highlighting (customizable).

    • CodePress - Demo of Joomla! CodePress Plugin - (LGPL) - It doesn't work in Chrome and it looks like development has ceased.

      CodePress is web-based source code editor with syntax highlighting written in JavaScript that colors text in real time while it's being typed in the browser.

    • CodeMirror - One of the many demo - (MIT-style license + optional commercial support)

      CodeMirror is a JavaScript library that can be used to create a relatively pleasant editor interface for code-like content - computer programs, HTML markup, and similar. If a mode has been written for the language you are editing, the code will be coloured, and the editor will optionally help you with indentation

    • Ace Ajax.org Cloud9 Editor - Demo - (Mozilla tri-license (MPL/GPL/LGPL))

      Ace is a standalone code editor written in JavaScript. Our goal is to create a web based code editor that matches and extends the features, usability and performance of existing native editors such as TextMate, Vim or Eclipse. It can be easily embedded in any web page and JavaScript application. Ace is developed as the primary editor for Cloud9 IDE and the successor of the Mozilla Skywriter (Bespin) Project.

    Mongod complains that there is no /data/db folder

    Your command will have created the directory structure in the current folder, not the root directory of your computer (which is what the missing / is).

    The first command was right, but because you are trying to create a folder in /, which is a protected directory, you need to prefix it with sudo, which is short for "superuser do". You'll then be asked for your password.

    So the full command would be:

    $ sudo mkdir -p /data/db
    

    maven "cannot find symbol" message unhelpful

    I had the same problem. The reason was that I had two JAR files were not added through the Maven dependency, so when I ran mvn compile, the console display the error error:

    Symbol cannot be found,Class...".

    To fix it:

    1. Remove the JAR files from build path
    2. Add to build path
    3. Run mvn compile

    How can I assign the output of a function to a variable using bash?

    You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

    VAR=$(scan)
    

    Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

    Preserving trailing Newlines:

    One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

    function scan2 () {
        local nl=$'\x0a';  # that's just \n
        echo "output${nl}${nl}" # 2 in the string + 1 by echo
    }
    
    # append a character to the total output.
    # and strip it with %% parameter expansion.
    VAR=$(scan2; echo "x"); VAR="${VAR%%x}"
    
    echo "${VAR}---"
    

    prints (3 newlines kept):

    output
    
    
    ---
    

    Use an output parameter: avoiding the subshell (and preserving newlines)

    If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.

    function scan3() {
        local -n outvar=$1    # -n makes it a nameref.
        local nl=$'\x0a'
        outvar="output${nl}${nl}"  # two total. quotes preserve newlines
    }
    
    VAR="some prior value which will get overwritten"
    
    # you pass the name of the variable. VAR will be modified.
    scan3 VAR
    
    # newlines are also preserved.
    echo "${VAR}==="
    

    prints:

    output
    
    ===
    

    This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.

    Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"

    This is relevant. https://stackoverflow.com/a/38997681/5556676

    Difference between static memory allocation and dynamic memory allocation

    Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.

    Open a Web Page in a Windows Batch FIle

    You can use the start command to do much the same thing as ShellExecute. For example

     start "" http://www.stackoverflow.com
    

    This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

    Python loop for inside lambda

    Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

    x = lambda x: sys.stdout.write("\n".join(x) + "\n")
    

    Deciding between HttpClient and WebClient

    Unpopular opinion from 2020:

    When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

    1. The modern implementation comes with async/awaitable task-based methods
    2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
    3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

    How can I convert a DOM element to a jQuery element?

    var elm = document.createElement("div");
    var jelm = $(elm);//convert to jQuery Element
    var htmlElm = jelm[0];//convert to HTML Element
    

    How to start MySQL server on windows xp

    Type

    C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console
    

    to start the sql server and then test the client connection.

    How to get the row number from a datatable?

    If you need the index of the item you're working with then using a foreach loop is the wrong method of iterating over the collection. Change the way you're looping so you have the index:

    for(int i = 0; i < dt.Rows.Count; i++)
    {
        // your index is in i
        var row = dt.Rows[i];
    }
    

    Making button go full-width?

    In Bootstrap 5, the class btn-block doesn't work anymore. But instead, you can add the class w-100 to the button to make it as wide as its container.

    _x000D_
    _x000D_
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="row"><div class=" col-5 ">
                <a class="btn btn-outline-primary w-100  " href="# "><span>Button 1</span></a> 
    </div><div class="col-5 ">
    
                <a class=" btn btn-primary w-100 weiss " href="# "><span>Button 2</span></a> 
    </div></div>
    _x000D_
    _x000D_
    _x000D_

    /usr/bin/ld: cannot find

    When you make the call to gcc it should say

    g++ -Wall -I/home/alwin/Development/Calculator/ -L/opt/lib main.cpp -lcalc -o calculator
    
    not -libcalc.so 
    

    I have a similar problem with auto-generated makes.

    You can create a soft link from your compile directory to the library directory. Then the library becomes "local".

    cd /compile/directory
    
    ln -s  /path/to/libcalc.so libcalc.so
    

    matching query does not exist Error in Django

    In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

    user = UniversityDetails.objects.get(email=email)
    

    is email a str, or a None? or an int?

    How to split the filename from a full path in batch?

    I don't know that much about batch files but couldn't you have a pre-made batch file copied from the home directory to the path you have that would return a list of the names of the files then use that name?

    Here is a link I think might be helpful in making the pre-made batch file.

    http://www.ericphelps.com/batch/lists/filelist.htm

    How to download file from database/folder using php

    I have changed to your code with little modification will works well. Here is the code:

    butangDonload.php

    <?php
    $file = "logo_ldg.png"; //Let say If I put the file name Bang.png
    echo "<a href='download1.php?nama=".$file."'>download</a> ";
    ?>
    

    download.php

    <?php
    $name= $_GET['nama'];
    
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($name));
        ob_clean();
        flush();
        readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
        exit;
    ?>
    

    Here you need to show the path from where the file to be download. i.e. will just give the file name but need to give the file path for reading that file. So, it should be replaced by I have tested by using your code and modifying also will works.

    How to get last inserted id?

    There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:

    <Your DataTable Class> tblData = new <Your DataTable Class>();
    <Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();
    
    /*** Initialize and update Table Data Here ***/
    
    /*** Make sure to call the EndEdit() method ***/
    /*** of any Binding Sources before update ***/
    <YourBindingSource>.EndEdit();
    
    //Update the Dataset
    tblAdpt.Update(tblData);
    
    //Get the New ID from the Table Adapter
    long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;
    

    Hope this Helps ...

    Match line break with regular expression

    You could search for:

    <li><a href="#">[^\n]+
    

    And replace with:

    $0</a>
    

    Where $0 is the whole match. The exact semantics will depend on the language are you using though.


    WARNING: You should avoid parsing HTML with regex. Here's why.

    Writing Unicode text to a text file?

    In case of writing in python3

    >>> a = u'bats\u00E0'
    >>> print a
    batsà
    >>> f = open("/tmp/test", "w")
    >>> f.write(a)
    >>> f.close()
    >>> data = open("/tmp/test").read()
    >>> data
    'batsà'
    

    In case of writing in python2:

    >>> a = u'bats\u00E0'
    >>> f = open("/tmp/test", "w")
    >>> f.write(a)
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)
    

    To avoid this error you would have to encode it to bytes using codecs "utf-8" like this:

    >>> f.write(a.encode("utf-8"))
    >>> f.close()
    

    and decode the data while reading using the codecs "utf-8":

    >>> data = open("/tmp/test").read()
    >>> data.decode("utf-8")
    u'bats\xe0'
    

    And also if you try to execute print on this string it will automatically decode using the "utf-8" codecs like this

    >>> print a
    batsà
    

    Less than or equal to

    In batch, the > is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /? help):

    where compare-op may be one of:
    
        EQU - equal
        NEQ - not equal
        LSS - less than
        LEQ - less than or equal
        GTR - greater than
        GEQ - greater than or equal
    

    That should explain what you want. The only other compare-op is == which can be switched with the if not parameter. Other then that rely on these three letter ones.

    How to check if a service is running on Android?

    Got it!

    You MUST call startService() for your service to be properly registered and passing BIND_AUTO_CREATE will not suffice.

    Intent bindIntent = new Intent(this,ServiceTask.class);
    startService(bindIntent);
    bindService(bindIntent,mConnection,0);
    

    And now the ServiceTools class:

    public class ServiceTools {
        private static String LOG_TAG = ServiceTools.class.getName();
    
        public static boolean isServiceRunning(String serviceClassName){
            final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);
            final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
    
            for (RunningServiceInfo runningServiceInfo : services) {
                if (runningServiceInfo.service.getClassName().equals(serviceClassName)){
                    return true;
                }
            }
            return false;
         }
    }
    

    Excel formula is only showing the formula rather than the value within the cell in Office 2010

    Add an = at the beginning. That makes it a function rather than an entry.

    Iterating through a variable length array

    Arrays have an implicit member variable holding the length:

    for(int i=0; i<myArray.length; i++) {
        System.out.println(myArray[i]);
    }
    

    Alternatively if using >=java5, use a for each loop:

    for(Object o : myArray) {
        System.out.println(o);
    }
    

    SQL MAX of multiple columns?

    SELECT 
        CASE 
            WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1 
            WHEN Date2 >= Date3 THEN Date2 
            ELSE Date3
        END AS MostRecentDate 
    

    This is slightly easier to write out and skips evaluation steps as the case statement is evaluated in order.

    Can an AJAX response set a cookie?

    For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).

    Open a facebook link by native Facebook app on iOS

    This will open the URL in Safari:

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]];
    

    For the iphone, you can launch the Facebook app if installed by using a url starting with fb://

    More information can be found here: http://iphonedevtools.com/?p=302 also here: http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

    Stolen from the above site:

    fb://profile – Open Facebook app to the user’s profile
    fb://friends – Open Facebook app to the friends list
    fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
    fb://feed – Open Facebook app to the News Feed
    fb://events – Open Facebook app to the Events page
    fb://requests – Open Facebook app to the Requests list
    fb://notes - Open Facebook app to the Notes page
    fb://albums – Open Facebook app to Photo Albums list
    

    To launch the above URLs:

    NSURL *theURL = [NSURL URLWithString:@"fb://<insert function here>"];
    [[UIApplication sharedApplication] openURL:theURL];
    

    How to linebreak an svg text within javascript?

    I think this does what you want:

    function ShowTooltip(evt, mouseovertext){
        // Make tooltip text        
        var tooltip_text = tt.childNodes.item(1);
        var words = mouseovertext.split("\\\n");
        var max_length = 0;
    
        for (var i=0; i<3; i++){
            tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
            length = tooltip_text.childNodes.item(i).getComputedTextLength();
            if (length > max_length) {max_length = length;}
        }
    
        var x = evt.clientX + 14 + max_length/2;
        var y = evt.clientY + 29;
        tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")
    
        // Make tooltip background
        bg.setAttributeNS(null,"width", max_length+15);
        bg.setAttributeNS(null,"height", words.length*15+6);
        bg.setAttributeNS(null,"x",evt.clientX+8);
        bg.setAttributeNS(null,"y",evt.clientY+14);
    
        // Show everything
        tt.setAttributeNS(null,"visibility","visible");
        bg.setAttributeNS(null,"visibility","visible");
    }
    

    It splits the text on \\\n and for each puts each fragment in a tspan. Then it calculates the size of the box required based on the longest length of text and the number of lines. You will also need to change the tooltip text element to contain three tspans:

    <g id="tooltip" visibility="hidden">
        <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
    </g>
    

    This assumes that you never have more than three lines. If you want more than three lines you can add more tspans and increase the length of the for loop.

    Trying to use Spring Boot REST to Read JSON String from POST

    To further work with array of maps, the followings could help:

    @RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
    public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {
    
      List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
      maps.addAll(payload);
    
    }
    

    Can jQuery read/write cookies to a browser?

    I have managed to write a script allowing the user to choose his/her language, using the cookie script from Klaus Hartl. It took me a few hours work, and I hope I can help others.

    S3 limit to objects in a bucket

    "You can store as many objects as you want within a bucket, and write, read, and delete objects in your bucket. Objects can be up to 5 terabytes in size."

    from http://aws.amazon.com/s3/details/ (as of Mar 4th 2015)

    What is the difference between iterator and iterable and how to use them?

    Consider an example having 10 apples. When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.

    By implementing iterator, we can get any apple, apple in next boxes etc.

    So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.

    Set a div width, align div center and text align left

    Set auto margins on the inner div:

    <div id="header" style="width:864px;">
        <div id="centered" style="margin: 0 auto; width:855px;"></div>
    </div>
    

    Alternatively, text align center the parent, and force text align left on the inner div:

    <div id="header" style="width:864px;text-align: center;">
        <div id="centered" style="text-align: left; width:855px;"></div>
    </div>
    

    Does C# have an equivalent to JavaScript's encodeURIComponent()?

    HttpUtility.HtmlEncode / Decode
    HttpUtility.UrlEncode / Decode

    You can add a reference to the System.Web assembly if it's not available in your project

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

    It seems that the original test case is wrong.

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

    Let's take the following html as an example:

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

    And the jquery bit:

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

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

    Failed to serialize the response in Web API with Json

    in my case, it was fixed when I removed the virtual keyword before my navigation properties, I mean the reference tables. so I changed

    public virtual MembershipType MembershipType { get; set; }
    

    to:

    public MembershipType MembershipType { get; set; }
    

    What is “assert” in JavaScript?

    As mentioned by T.J., There is no assert in JavaScript. However, there is a node module named assert, which is used mostly for testing. so, you might see code like:

    const assert = require('assert');
    assert(5 > 7);
    

    How to identify object types in java

    You forgot the .class:

    if (value.getClass() == Integer.class) {
        System.out.println("This is an Integer");
    } 
    else if (value.getClass() == String.class) {
        System.out.println("This is a String");
    }
    else if (value.getClass() == Float.class) {
        System.out.println("This is a Float");
    }
    

    Note that this kind of code is usually the sign of a poor OO design.

    Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:

    "foo".getClass() == Object.class
    

    is false, whereas

    "foo" instanceof Object
    

    is true.

    Whether one or the other must be used depends on your requirements.

    Understanding string reversal via slicing

    I would do it like this:

    variable = "string"
    message = ""
    for b in variable:
        message = b+message
    print (message)
    

    and it prints: gnirts

    Forbidden You don't have permission to access / on this server

    Found my solution on Apache/2.2.15 (Unix).

    And Thanks for answer from @QuantumHive:

    First: I finded all

    Order allow,deny
    Deny from all
    

    instead of

    Order allow,deny
    
    Allow from all
    

    and then:

    I setted

    #
    # Control access to UserDir directories.  The following is an example
    # for a site where these directories are restricted to read-only.
    #
    #<Directory /var/www/html>
    #    AllowOverride FileInfo AuthConfig Limit
    #    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    #    <Limit GET POST OPTIONS>
    #        Order allow,deny
    #        Allow from all
    #    </Limit>
    #    <LimitExcept GET POST OPTIONS>
    #        Order deny,allow
    #        Deny from all
    #    </LimitExcept>
    #</Directory>
    

    Remove the previous "#" annotation to

    #
    # Control access to UserDir directories.  The following is an example
    # for a site where these directories are restricted to read-only.
    #
    <Directory /var/www/html>
        AllowOverride FileInfo AuthConfig Limit
        Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
        <Limit GET POST OPTIONS>
            Order allow,deny
            Allow from all
        </Limit>
        <LimitExcept GET POST OPTIONS>
            Order deny,allow
            Deny from all
        </LimitExcept>
    </Directory>
    

    ps. my WebDir is: /var/www/html

    Convert python long/int to fixed size byte array

    I haven't done any benchmarks, but this recipe "works for me".

    The short version: use '%x' % val, then unhexlify the result. The devil is in the details, though, as unhexlify requires an even number of hex digits, which %x doesn't guarantee. See the docstring, and the liberal inline comments for details.

    from binascii import unhexlify
    
    def long_to_bytes (val, endianness='big'):
        """
        Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
        convert ``val``, a :func:`long`, to a byte :func:`str`.
    
        :param long val: The value to pack
    
        :param str endianness: The endianness of the result. ``'big'`` for
          big-endian, ``'little'`` for little-endian.
    
        If you want byte- and word-ordering to differ, you're on your own.
    
        Using :ref:`string formatting` lets us use Python's C innards.
        """
    
        # one (1) hex digit per four (4) bits
        width = val.bit_length()
    
        # unhexlify wants an even multiple of eight (8) bits, but we don't
        # want more digits than we need (hence the ternary-ish 'or')
        width += 8 - ((width % 8) or 8)
    
        # format width specifier: four (4) bits per hex digit
        fmt = '%%0%dx' % (width // 4)
    
        # prepend zero (0) to the width, to zero-pad the output
        s = unhexlify(fmt % val)
    
        if endianness == 'little':
            # see http://stackoverflow.com/a/931095/309233
            s = s[::-1]
    
        return s
    

    ...and my nosetest unit tests ;-)

    class TestHelpers (object):
        def test_long_to_bytes_big_endian_small_even (self):
            s = long_to_bytes(0x42)
            assert s == '\x42'
    
            s = long_to_bytes(0xFF)
            assert s == '\xff'
    
        def test_long_to_bytes_big_endian_small_odd (self):
            s = long_to_bytes(0x1FF)
            assert s == '\x01\xff'
    
            s = long_to_bytes(0x201FF)
            assert s == '\x02\x01\xff'
    
        def test_long_to_bytes_big_endian_large_even (self):
            s = long_to_bytes(0xab23456c8901234567)
            assert s == '\xab\x23\x45\x6c\x89\x01\x23\x45\x67'
    
        def test_long_to_bytes_big_endian_large_odd (self):
            s = long_to_bytes(0x12345678901234567)
            assert s == '\x01\x23\x45\x67\x89\x01\x23\x45\x67'
    
        def test_long_to_bytes_little_endian_small_even (self):
            s = long_to_bytes(0x42, 'little')
            assert s == '\x42'
    
            s = long_to_bytes(0xFF, 'little')
            assert s == '\xff'
    
        def test_long_to_bytes_little_endian_small_odd (self):
            s = long_to_bytes(0x1FF, 'little')
            assert s == '\xff\x01'
    
            s = long_to_bytes(0x201FF, 'little')
            assert s == '\xff\x01\x02'
    
        def test_long_to_bytes_little_endian_large_even (self):
            s = long_to_bytes(0xab23456c8901234567, 'little')
            assert s == '\x67\x45\x23\x01\x89\x6c\x45\x23\xab'
    
        def test_long_to_bytes_little_endian_large_odd (self):
            s = long_to_bytes(0x12345678901234567, 'little')
            assert s == '\x67\x45\x23\x01\x89\x67\x45\x23\x01'
    

    Python: Get the first character of the first string in a list?

    Try mylist[0][0]. This should return the first character.

    Using cURL with a username and password?

    You can use command like,

    curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext
    

    Then HTTP password will be triggered.

    Reference: http://www.asempt.com/article/how-use-curl-http-password-protected-site

    Multiple Order By with LINQ

    You can use the ThenBy and ThenByDescending extension methods:

    foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
    

    Get Folder Size from Windows Command Line

    So here is a solution for both your requests in the manner you originally asked for. It will give human readability filesize without the filesize limits everyone is experiencing. Compatible with Win Vista or newer. XP only available if Robocopy is installed. Just drop a folder on this batch file or use the better method mentioned below.

    @echo off
    setlocal enabledelayedexpansion
    set "vSearch=Files :"
    
    For %%i in (%*) do (
        set "vSearch=Files :"
        For /l %%M in (1,1,2) do ( 
            for /f "usebackq tokens=3,4 delims= " %%A in (`Robocopy "%%i" "%%i" /E /L /NP /NDL /NFL ^| find "!vSearch!"`) do (
                if /i "%%M"=="1" (
                    set "filecount=%%A"
                    set "vSearch=Bytes :"
                ) else (
                    set "foldersize=%%A%%B"
                )
            )
        )
        echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!
        REM remove the word "REM" from line below to output to txt file
        REM echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!>>Folder_FileCountandSize.txt
    )
    pause
    

    To be able to use this batch file conveniently put it in your SendTo folder. This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.

    To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.

    explorer C:\Users\%username%\AppData\Roaming\Microsoft\Windows\SendTo
    
    

    Django return redirect() with parameters

    Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

    Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

    /link/mybackend/?field1=value1&field2=value2&field3=value3
    

    and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

    So your urlconf would be:

    url(r'^link/(?P<backend>\w+?)/$', my_function)
    

    and the view would look like:

    def my_function(request, backend):
       data = request.GET
    

    and the reverse would be (after importing urllib):

    return "%s?%s" % (redirect('my_function', args=(backend,)),
                      urllib.urlencode(form.cleaned_data))
    

    Edited after comment

    The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

    If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

    That said, if all you want to do is store the data, then just put it in the session:

    request.session['temp_data'] = form.cleaned_data
    

    LaTeX package for syntax highlighting of code in various languages

    I recommend Pygments. It accepts a piece of code in any language and outputs syntax highlighted LaTeX code. It uses fancyvrb and color packages to produce its output. I personally prefer it to the listing package. I think fancyvrb creates much prettier results.

    Pure CSS multi-level drop-down menu

    <div class="example" align="center">
        <div class="menuholder">
            <ul class="menu slide">
                <li><a href="index.php?id=1" class="blue">Home</a></li>
            <li><a href="index.php?id=14" class="blue">About Us</a></li>
                <li><a href="index.php?id=4" class="blue">Mens</a>
                    <div class="subs">
                        <dl>
                            <dd><a href="index.php?id=15">Coats & Jackets</a></dd>
                            <dd><a href="index.php?id=22">Chinos</a></dd>
                            <dd><a href="index.php?id=23">Jeans</a></dd>
                            <dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
                            <dd><a href="index.php?id=25">Linen</a></dd>
                        </dl>
                        <dl>
                            <dd><a href="index.php?id=26">Polo Shirts</a></dd>
                            <dd><a href="index.php?id=16">Shirts Casual</a></dd>
                            <dd><a href="index.php?id=27">Shirts Formal</a></dd>
                            <dd><a href="index.php?id=28">Shorts</a></dd>
                            <dd><a href="index.php?id=18">Sportswear</a></dd>
                        </dl>
                        <dl>
                            <dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
                            <dd><a href="index.php?id=20">Trousers Casual</a></dd>
                            <dd><a href="index.php?id=29">Trousers Formal</a></dd>
                            <dd><a href="index.php?id=30">Nightwear</a></dd>
                            <dd><a href="index.php?id=17">Socks</a></dd>
                        </dl>
                        <dl>
                            <dd><a href="index.php?id=21">Underwear</a></dd>
                            <dd><a href="index.php?id=31">Swimwear</a></dd>
                        </dl>
                    </div>
                </li>
                <!--menu-->
                            <li><a href="index.php?id=5" class="blue">Ladie's</a>
                    <div class="subs">
                        <dl>
                              <dd><a href="index.php?id=32">Coats & Jackets</a></dd>
                              <dd><a href="index.php?id=33">Dresses</a></dd>
                              <dd><a href="index.php?id=34">Jeans</a></dd>
                              <dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
                              <dd><a href="index.php?id=36">Jumpsuits</a></dd>
                        </dl>
                        <dl>
                            <dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
                              <dd><a href="index.php?id=38">Linen</a></dd>
                              <dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
                              <dd><a href="index.php?id=40">Maternity Wear</a></dd>
                              <dd><a href="index.php?id=41">Nightwear</a></dd>
                        </dl>
                        <dl>
                         <dd><a href="index.php?id=42">Shorts</a></dd>
                              <dd><a href="index.php?id=43">Skirts</a></dd>
                              <dd><a href="index.php?id=44">Sportswear</a></dd>
                              <dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
                              <dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
                        </dl>
                        <dl>
                              <dd><a href="index.php?id=47">Thermals</a></dd>
                              <dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
                              <dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
                              <dd><a href="index.php?id=50">Socks</a></dd>
                        </dl>
                    </div>
                </li><!--menu end-->
                            <!--menu-->
                            <li><a href="index.php?id=7" class="blue">Girls</a>
                    <div class="subs">
                        <dl>
                                <dd><a href="index.php?id=51">Coats & Jackets</a></dd>
                              <dd><a href="index.php?id=52">Dresses</a></dd>
                              <dd><a href="index.php?id=53">Jeans</a></dd>
                              <dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
                              <dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
                        </dl>
                        <dl>
                                    <dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
                                  <dd><a href="index.php?id=57">Leggings</a></dd>
                                  <dd><a href="index.php?id=58">Nightwear</a></dd>
                                  <dd><a href="index.php?id=59">Shorts</a></dd>
                                  <dd><a href="index.php?id=60">Skirts</a></dd>
                        </dl>
                        <dl>
                                  <dd><a href="index.php?id=61">Swimwear</a></dd>
                                  <dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
                                  <dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
                                  <dd><a href="index.php?id=64">Socks</a></dd>
                                  <dd><a href="index.php?id=65">Underwear</a></dd>
                        </dl>
                        <dl>
    
                        </dl>
                    </div>
                </li><!--menu end-->
                                <!--menu-->
                            <li><a href="index.php?id=8" class="blue">Boys</a>
                    <div class="subs">
                        <dl>
                            <dd><a href="index.php?id=66">Coats & Jackets</a></dd>
                              <dd><a href="index.php?id=67">Jeans</a></dd>
                              <dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
                              <dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
                              <dd><a href="index.php?id=70">Nightwear</a></dd>
                        </dl>
                        <dl>
                                <dd><a href="index.php?id=71">Shirts</a></dd>
                              <dd><a href="index.php?id=72">Shorts</a></dd>
                              <dd><a href="index.php?id=73">Sportswear</a></dd>
                              <dd><a href="index.php?id=74">Swimwear</a></dd>
                              <dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
                        </dl>
                        <dl>
                              <dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
                              <dd><a href="index.php?id=77">Socks</a></dd>
                              <dd><a href="index.php?id=78">Underwear</a></dd>
                        </dl>
                        <dl>
    
                        </dl>
                    </div>
                </li><!--menu end-->
                <!--menu-->
                 <li><a href="index.php?id=9" class="blue">Toddlers</a>
                    <div class="subs">
                        <dl>
                          <dd><a href="index.php?id=79">Newborn</a></dd>
                          <dd><a href="index.php?id=80">0-2 Years</a></dd>
                        </dl>                 
                    </div>
                </li><!--menu end-->
                <!--menu-->
                 <li><a href="index.php?id=10" class="blue">Accessories</a>
                    <div class="subs">
                        <dl>
                              <dd><a href="index.php?id=81">Shoes</a></dd>
                              <dd><a href="index.php?id=82">Ties</a></dd>
                              <dd><a href="index.php?id=83">Caps</a></dd>
                              <dd><a href="index.php?id=84">Belts</a></dd>
                        </dl>                 
                    </div>
                </li><!--menu end-->
                <li><a href="index.php?id=13" class="blue">Contact Us</a></li>
            </ul>
            <div class="back"></div>
            <div class="shadow"></div>
        </div>
        <div style="clear:both"></div>
    </div>
    

    CSS 3 Coding- Copy and Paste

    <style>
    
    body{margin:0px;}
    .example {
        width:980px;
        height:40px;
        margin:0px auto;
     position:absolute;
     margin-bottom:60px;
     top:95px;
    }
    
    .menuholder {
        float:left;
        font:normal bold 11px/35px verdana, sans-serif;
        overflow:hidden;
        position:relative;
    }
    .menuholder .shadow {
        -moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
        -o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
        -webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
        background:#888;
        box-shadow:0 0 20px rgba(0, 0, 0, 1);
        height:10px;
        left:5%;
        position:absolute;
        top:-9px;
        width:100%;
        z-index:100;
    }
    .menuholder .back {
        -moz-transition-duration:.4s;
        -o-transition-duration:.4s;
        -webkit-transition-duration:.4s;
        background-color:rgba(0, 0, 0, 0.88);
        height:0;
        width:980px; /*100%*/
    }
    .menuholder:hover div.back {
        height:280px;
    }
    ul.menu {
        display:block;
        float:left;
        list-style:none;
        margin:0;
        padding:0 125px;
        position:relative;
    }
    ul.menu li {
        float:left;
        margin:0 10px 0 0;
    }
    ul.menu li > a {
        -moz-border-radius:0 0 10px 10px;
        -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
        -moz-transition:all 0.3s ease-in-out;
        -o-border-radius:0 0 10px 10px;
        -o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
        -o-transition:all 0.3s ease-in-out;
        -webkit-border-bottom-left-radius:10px;
        -webkit-border-bottom-right-radius:10px;
        -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
        -webkit-transition:all 0.3s ease-in-out;
        border-radius:0 0 10px 10px;
        box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
        color:#eee;
        display:block;
        padding:0 10px;
        text-decoration:none;
        transition:all 0.3s ease-in-out;
    }
    ul.menu li a.red {
        background:#a00;
    }
    ul.menu li a.orange {
        background:#da0;
    }
    ul.menu li a.yellow {
        background:#aa0;
    }
    ul.menu li a.green {
        background:#060;
    }
    ul.menu li a.blue {
        background:#073263;
    }
    ul.menu li a.violet {
        background:#682bc2;
    }
    .menu li div.subs {
        left:0;
        overflow:hidden;
        position:absolute;
        top:35px;
        width:0;
    }
    .menu li div.subs dl {
        -moz-transition-duration:.2s;
        -o-transition-duration:.2s;
        -webkit-transition-duration:.2s;
        float:left;
        margin:0 130px 0 0;
        overflow:hidden;
        padding:40px 0 5% 2%;
        width:0;
    }
    .menu dt {
        color:#fc0;
        font-family:arial, sans-serif;
        font-size:12px;
        font-weight:700;
        height:20px;
        line-height:20px;
        margin:0;
        padding:0 0 0 10px;
        white-space:nowrap;
    }
    .menu dd {
        margin:0;
        padding:0;
        text-align:left;
    }
    .menu dd a {
        background:transparent;
        color:#fff;
        font-size:12px;
        height:20px;
        line-height:20px;
        padding:0 0 0 10px;
        text-align:left;
        white-space:nowrap;
        width:80px;
    }
    .menu dd a:hover {
        color:#fc0;
    }
    .menu li:hover div.subs dl {
        -moz-transition-delay:0.2s;
        -o-transition-delay:0.2s;
        -webkit-transition-delay:0.2s;
        margin-right:2%;
        width:21%;
    }
    ul.menu li:hover > a,ul.menu li > a:hover {
        background:#aaa;
        color:#fff;
        padding:10px 10px 0;
    }
    ul.menu li a.red:hover,ul.menu li:hover a.red {
        background:#c00;
    }
    ul.menu li a.orange:hover,ul.menu li:hover a.orange {
        background:#fc0;
    }
    ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
        background:#cc0;
    }
    ul.menu li a.green:hover,ul.menu li:hover a.green {
        background:#080;
    }
    ul.menu li a.blue:hover,ul.menu li:hover a.blue {
        background:#00c;
    }
    ul.menu li a.violet:hover,ul.menu li:hover a.violet {
    background:#8a2be2;
    }
    .menu li:hover div.subs,.menu li a:hover div.subs {
        width:100%;
    }
    

    What does if __name__ == "__main__": do?

    You can checkup for the special variable __name__ with this simple example:

    create file1.py

    if __name__ == "__main__":
        print("file1 is being run directly")
    else:
        print("file1 is being imported")
    

    create file2.py

    import file1 as f1
    
    print("__name__ from file1: {}".format(f1.__name__))
    print("__name__ from file2: {}".format(__name__))
    
    if __name__ == "__main__":
        print("file2 is being run directly")
    else:
        print("file2 is being imported")
    

    Execute file2.py

    output:

    file1 is being imported
    __name__ from file1: file1
    __name__ from file2: __main__
    file2 is being run directly
    

    MVVM: Tutorial from start to finish?

    A while ago I was in a similar situation (allthough I had a little WPF knowledge already), so I started a community wiki. There are a lot of great ressources there:

    What applications could I study to understand (Data)Model-View-ViewModel?

    AmazonS3 putObject with InputStream length example

    I've created a library that uses multipart uploads in the background to avoid buffering everything in memory and also doesn't write to disk: https://github.com/alexmojaki/s3-stream-upload

    Add a default value to a column through a migration

    For Rails 4+, use change_column_default

    def change
      change_column_default :table, :column, value
    end
    

    Chrome hangs after certain amount of data transfered - waiting for available socket

    Explanation:

    This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

    Solution 1:

    You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

    Solution 2:

    If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

    Solution 3: Force-open Sockets (Not recommended)

    If you must, you can force-open the sockets in your browser (In Chrome only):

    1. Go to the address bar and type chrome://net-internals.
    2. Select Sockets from the menu.
    3. Click on the Flush socket pools button.

    This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

    powershell is missing the terminator: "

    In my specific case of the same issue, it was caused by not having the Powershell script saved with an encoding of Windows-1252 or UFT-8 WITH BOM.

    OpenCV get pixel channel value from Mat image

    The below code works for me, for both accessing and changing a pixel value.

    For accessing pixel's channel value :

    for (int i = 0; i < image.cols; i++) {
        for (int j = 0; j < image.rows; j++) {
            Vec3b intensity = image.at<Vec3b>(j, i);
            for(int k = 0; k < image.channels(); k++) {
                uchar col = intensity.val[k]; 
            }   
        }
    }
    

    For changing a pixel value of a channel :

    uchar pixValue;
    for (int i = 0; i < image.cols; i++) {
        for (int j = 0; j < image.rows; j++) {
            Vec3b &intensity = image.at<Vec3b>(j, i);
            for(int k = 0; k < image.channels(); k++) {
                // calculate pixValue
                intensity.val[k] = pixValue;
            }
         }
    }
    

    `

    Source : Accessing pixel value

    Where can I find decent visio templates/diagrams for software architecture?

    There should be templates already included in Visio 2007 for software architecture but you might want to check out Visio 2007 templates.

    Selecting data frame rows based on partial string match in a column

    LIKE should work in sqlite:

    require(sqldf)
    df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
    sqldf("select * from df where name LIKE '%er%'")
        name id
    1 robert  2
    2  peter  3
    

    Laravel assets url

    You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

    Ex. you can retrieve assets/images/image.png in your view as following:

    <img src="{{asset('assets/images/image.png')}}">

    Can I set max_retries for requests.request?

    This will not only change the max_retries but also enable a backoff strategy which makes requests to all http:// addresses sleep for a period of time before retrying (to a total of 5 times):

    import requests
    from urllib3.util.retry import Retry
    from requests.adapters import HTTPAdapter
    
    s = requests.Session()
    
    retries = Retry(total=5,
                    backoff_factor=0.1,
                    status_forcelist=[ 500, 502, 503, 504 ])
    
    s.mount('http://', HTTPAdapter(max_retries=retries))
    
    s.get('http://httpstat.us/500')
    

    As per documentation for Retry: if the backoff_factor is 0.1, then sleep() will sleep for [0.1s, 0.2s, 0.4s, ...] between retries. It will also force a retry if the status code returned is 500, 502, 503 or 504.

    Various other options to Retry allow for more granular control:

    • total – Total number of retries to allow.
    • connect – How many connection-related errors to retry on.
    • read – How many times to retry on read errors.
    • redirect – How many redirects to perform.
    • method_whitelist – Set of uppercased HTTP method verbs that we should retry on.
    • status_forcelist – A set of HTTP status codes that we should force a retry on.
    • backoff_factor – A backoff factor to apply between attempts.
    • raise_on_redirect – Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range.
    • raise_on_status – Similar meaning to raise_on_redirect: whether we should raise an exception, or return a response, if status falls in status_forcelist range and retries have been exhausted.

    NB: raise_on_status is relatively new, and has not made it into a release of urllib3 or requests yet. The raise_on_status keyword argument appears to have made it into the standard library at most in python version 3.6.

    To make requests retry on specific HTTP status codes, use status_forcelist. For example, status_forcelist=[503] will retry on status code 503 (service unavailable).

    By default, the retry only fires for these conditions:

    • Could not get a connection from the pool.
    • TimeoutError
    • HTTPException raised (from http.client in Python 3 else httplib). This seems to be low-level HTTP exceptions, like URL or protocol not formed correctly.
    • SocketError
    • ProtocolError

    Notice that these are all exceptions that prevent a regular HTTP response from being received. If any regular response is generated, no retry is done. Without using the status_forcelist, even a response with status 500 will not be retried.

    To make it behave in a manner which is more intuitive for working with a remote API or web server, I would use the above code snippet, which forces retries on statuses 500, 502, 503 and 504, all of which are not uncommon on the web and (possibly) recoverable given a big enough backoff period.

    EDITED: Import Retry class directly from urllib3.

    Conversion failed when converting from a character string to uniqueidentifier

    this fails:

     DECLARE @vPortalUID NVARCHAR(32)
     SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
     DECLARE @nPortalUID AS UNIQUEIDENTIFIER
     SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
     PRINT @nPortalUID
    

    this works

     DECLARE @vPortalUID NVARCHAR(36)
     SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
     DECLARE @nPortalUID AS UNIQUEIDENTIFIER
     SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
     PRINT @nPortalUID
    

    the difference is NVARCHAR(36), your input parameter is too small!

    How do you give iframe 100% height

    The problem with iframes not getting 100% height is not because they're unwieldy. The problem is that for them to get 100% height they need their parents to have 100% height. If one of the iframe's parents is not 100% tall the iframe won't be able to go beyond that parent's height.

    So the best possible solution would be:

    html, body, iframe { height: 100%; }
    

    …given the iframe is directly under body. If the iframe has a parent between itself and the body, the iframe will still get the height of its parent. One must explicitly set the height of every parent to 100% as well (if that's what one wants).

    Tested in:

    Chrome 30, Firefox 24, Safari 6.0.5, Opera 16, IE 7, 8, 9 and 10

    PS: I don't mean to be picky but the solution marked as correct doesn't work on Firefox 24 at the time of this writing, but worked on Chrome 30. Haven't tested on other browsers though. I came across the error on Firefox because the page I was testing had very little content... It could be it's my meager markup or the CSS reset altering the output, but if I experienced this error I guess the accepted answer doesn't work in every situation.

    Update 2021

    @Zeni suggested this in 2015:

    iframe { height: 100vh }
    

    ...and indeed it does the trick!

    Careful with positioning as it can potentially break the effect. Test thoroughly, you might not need positioning depending of what you're trying to achieve.

    C++ sorting and keeping track of indexes

    You could sort std::pair instead of just ints - first int is original data, second int is original index. Then supply a comparator that only sorts on the first int. Example:

    Your problem instance: v = [5 7 8]
    New problem instance: v_prime = [<5,0>, <8,1>, <7,2>]
    

    Sort the new problem instance using a comparator like:

    typedef std::pair<int,int> mypair;
    bool comparator ( const mypair& l, const mypair& r)
       { return l.first < r.first; }
    // forgetting the syntax here but intent is clear enough
    

    The result of std::sort on v_prime, using that comparator, should be:

    v_prime = [<5,0>, <7,2>, <8,1>]
    

    You can peel out the indices by walking the vector, grabbing .second from each std::pair.

    How to get the body's content of an iframe in Javascript?

    Using JQuery, try this:

    $("#id_description_iframe").contents().find("body").html()
    

    jQuery selector first td of each row

    Use:

    $("tr").find("td:first");
    

    js fiddle - this example has .text() on the end to show that it is returning the elements.

    Alternatively, you can use:

    $("td:first-child");
    

    .find() - jQuery API Documentation

    How can I save a base64-encoded image to disk?

    Below function to save files, just pass your base64 file, it return filename save it in DB.

    import fs from 'fs';
     const uuid = require('uuid/v1');
    
    /*Download the base64 image in the server and returns the filename and path of image.*/
    function saveImage(baseImage) {
        /*path of the folder where your project is saved. (In my case i got it from config file, root path of project).*/
        const uploadPath = "/home/documents/project";
        //path of folder where you want to save the image.
        const localPath = `${uploadPath}/uploads/images/`;
        //Find extension of file
        const ext = baseImage.substring(baseImage.indexOf("/")+1, baseImage.indexOf(";base64"));
        const fileType = baseImage.substring("data:".length,baseImage.indexOf("/"));
        //Forming regex to extract base64 data of file.
        const regex = new RegExp(`^data:${fileType}\/${ext};base64,`, 'gi');
        //Extract base64 data.
        const base64Data = baseImage.replace(regex, "");
        const filename = `${uuid()}.${ext}`;
    
        //Check that if directory is present or not.
        if(!fs.existsSync(`${uploadPath}/uploads/`)) {
            fs.mkdirSync(`${uploadPath}/uploads/`);
        }
        if (!fs.existsSync(localPath)) {
            fs.mkdirSync(localPath);
        }
        fs.writeFileSync(localPath+filename, base64Data, 'base64');
        return filename;
    }
    

    How to access the request body when POSTing using Node.js and Express?

    Express 4.0 and above:

    $ npm install --save body-parser

    And then in your node app:

    const bodyParser = require('body-parser');
    app.use(bodyParser);
    

    Express 3.0 and below:

    Try passing this in your cURL call:

    --header "Content-Type: application/json"

    and making sure your data is in JSON format:

    {"user":"someone"}

    Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:

    var express = require('express');
    var app = express.createServer();
    
    app.use(express.bodyParser());
    
    app.post('/', function(req, res){
        console.dir(req.body);
        res.send("test");
    }); 
    
    app.listen(3000);
    

    This other question might also help: How to receive JSON in express node.js POST request?

    If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681

    Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

    You can use the fromstring() method for this:

    arr = np.array([1, 2, 3, 4, 5, 6])
    ts = arr.tostring()
    print(np.fromstring(ts, dtype=int))
    
    >>> [1 2 3 4 5 6]
    

    Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain.

    Note on fromstring from numpy 1.14 onwards:

    sep : str, optional

    The string separating numbers in the data; extra whitespace between elements is also ignored.

    Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.

    How to store the hostname in a variable in a .bat file?

    Why not so?:

    set host=%COMPUTERNAME%
    echo %host%
    

    How to split a string into an array of characters in Python?

    from itertools import chain
    
    string = 'your string'
    chain(string)
    

    similar to list(string) but returns a generator that is lazily evaluated at point of use, so memory efficient.

    How do I redirect a user when a button is clicked?

    It has been my experience that ASP MVC really does not like traditional use of button so much. Instead I use:

      <input type="button" class="addYourCSSClassHere" value="WordsOnButton" onclick="window.location= '@Url.Action( "ActionInControllerHere", "ControllerNameHere")'" />
    

    How I can delete in VIM all text from current line to end of file?

    Go to the first line from which you would like to delete, and press the keys dG

    How to delete a module in Android Studio

    In Android studio v1.0.2

    Method 1

    Go to project structure, File -> Project Structure..., as the following picture show, click - icon to remove the module.enter image description here

    Method 2

    Edit the file settings.gradle and remove the entry you are going to delete. e.g. edit the file from include ':app', ':apple' to include ':app'.

    That will work in most of the situation, however finally you have to delete the module from disk manually if you don't need it anymore.

    WebDriver - wait for element using Java

    We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

    Awaitility.await()
            .atMost(timeout)
            .ignoreException(NoSuchElementException.class)
            .ignoreExceptionsMatching(
                Matchers.allOf(
                    Matchers.instanceOf(WebDriverException.class),
                    Matchers.hasProperty(
                        "message",
                        Matchers.containsString("is not clickable at point")
                    )
                )
            ).until(
                () -> {
                    this.driver.findElement(locator).click();
                    return true;
                },
                Matchers.is(true)
            );
    

    Combine GET and POST request methods in Spring

    @RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
            @RequestParam(required = false) String parameter1,
            @RequestParam(required = false) String parameter2, 
            BindingResult result, HttpServletRequest request) 
            throws ParseException {
    
        LONG CODE and SAME LONG CODE with a minor difference
    }
    

    if @RequestParam(required = true) then you must pass parameter1,parameter2

    Use BindingResult and request them based on your conditions.

    The Other way

    @RequestMapping(value = "/books", method = RequestMethod.GET)
    public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
        two @RequestParam parameters, HttpServletRequest request) throws ParseException {
    
        myMethod();
    
    }
    
    
    @RequestMapping(value = "/books", method = RequestMethod.POST)
    public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
            BindingResult result) throws ParseException {
    
        myMethod();
    
        do here your minor difference
    }
    
    private returntype myMethod(){
        LONG CODE
    }
    

    plot.new has not been called yet

    As a newbie, I faced the same 'problem'.

    In newbie terms : when you call plot(), the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R. However, some commands, like identify(), act on open/active graph windows. When identify() cannot find an open/active graph window, it gives this error message.

    However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify() etc.

    How to view the assembly behind the code using Visual C++?

    Red Gate's .NET Reflector is a pretty awesome tool that has helped me out more than a few times. The plus side of this utility outside of easily showing you MSIL is that you can analyze a lot of third-party DLLs and have the Reflector take care of converting MSIL to C# and VB.

    I'm not promising the code will be as clear as source but you shouldn't have much trouble following it.

    Why are my CSS3 media queries not working on mobile devices?

    For me I had indicated max-height instead of max-width.

    If that is you, go change it !

        @media screen and (max-width: 350px) {    // Not max-height
            .letter{
                font-size:20px;
            }
        }
    

    Byte Array in Python

    In Python 3, we use the bytes object, also known as str in Python 2.

    # Python 3
    key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
    
    # Python 2
    key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
    

    I find it more convenient to use the base64 module...

    # Python 3
    key = base64.b16decode(b'130000000800')
    
    # Python 2
    key = base64.b16decode('130000000800')
    

    You can also use literals...

    # Python 3
    key = b'\x13\0\0\0\x08\0'
    
    # Python 2
    key = '\x13\0\0\0\x08\0'
    

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

    Generally speaking:

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

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

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

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


    In your specific code samples:

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

    if any(foobars) == big_foobar:
    

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

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

    What you want instead is:

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

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

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

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

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

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

    Some examples:

    In [1]: any(x > 5 for x in range(4))
    Out[1]: False
    
    In [2]: all(isinstance(x, int) for x in range(10))
    Out[2]: True
    
    In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
    Out[3]: True
    
    In [4]: all([True, True, True, False, True])
    Out[4]: False
    

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

    undefined offset PHP error

    Undefined offset means there's an empty array key for example:

    $a = array('Felix','Jon','Java');
    
    // This will result in an "Undefined offset" because the size of the array
    // is three (3), thus, 0,1,2 without 3
    echo $a[3];
    

    You can solve the problem using a loop (while):

    $i = 0;
    while ($row = mysqli_fetch_assoc($result)) {
        // Increase count by 1, thus, $i=1
        $i++;
    
        $groupname[$i] = base64_decode(base64_decode($row['groupname']));
    
        // Set the first position of the array to null or empty
        $groupname[0] = "";
    }
    

    How to execute an Oracle stored procedure via a database link

    check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

    one needs to use something like

    cmd.CommandText = "BEGIN foo@v; END;" 
    

    worked for me in vb.net, c#

    What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

    AssemblyVersion

    Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion is required.

    I use the format: major.minor. This would result in:

    [assembly: AssemblyVersion("1.0")]
    

    If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.

    AssemblyFileVersion

    Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion, but are generated from different builds.

    In Windows, it can be viewed in the file properties.

    The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.

    I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:

    [assembly: AssemblyFileVersion("1.3.2.254")]
    

    Be aware that System.Version names these parts as major.minor.build.revision!

    AssemblyInformationalVersion

    The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.

    The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used.

    I use the format: major.minor[.patch] [revision as string]. This would result in:

    [assembly: AssemblyInformationalVersion("1.0 RC1")]
    

    AttributeError: 'list' object has no attribute 'encode'

    You need to do encode on tmp[0], not on tmp.

    tmp is not a string. It contains a (Unicode) string.

    Try running type(tmp) and print dir(tmp) to see it for yourself.

    Linker command failed with exit code 1 - duplicate symbol __TMRbBp

    I had removed files from Compile Sources in Build Phases in Targets. I added main.m and it worked.

    How can I find the number of years between two dates?

    // int year =2000;  int month =9 ;    int day=30;
    
        public int getAge (int year, int month, int day) {
    
                GregorianCalendar cal = new GregorianCalendar();
                int y, m, d, noofyears;         
    
                y = cal.get(Calendar.YEAR);// current year ,
                m = cal.get(Calendar.MONTH);// current month 
                d = cal.get(Calendar.DAY_OF_MONTH);//current day
                cal.set(year, month, day);// here ur date 
                noofyears = y - cal.get(Calendar.YEAR);
                if ((m < cal.get(Calendar.MONTH))
                                || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                                .get(Calendar.DAY_OF_MONTH)))) {
                        --noofyears;
                }
                if(noofyears < 0)
                        throw new IllegalArgumentException("age < 0");
                 System.out.println(noofyears);
                return noofyears;
    

    Reading an Excel file in PHP

    It depends on how you want to use the data in the excel file. If you want to import it into mysql, you could simply save it as a CSV formatted file and then use fgetcsv to parse it.

    Bootstrap 3 Slide in Menu / Navbar on Mobile

    Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

    _x000D_
    _x000D_
    $('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
      $navMenuCont = $($(this).data('target'));_x000D_
      $navMenuCont.animate({_x000D_
        'width': 'toggle'_x000D_
      }, 350);_x000D_
      $(".menu-overlay").fadeIn(500);_x000D_
    });_x000D_
    _x000D_
    $(".menu-overlay").click(function(event) {_x000D_
      $(".navbar-toggle").trigger("click");_x000D_
      $(".menu-overlay").fadeOut(500);_x000D_
    });_x000D_
    _x000D_
    // if ($(window).width() >= 767) {_x000D_
    //     $('ul.nav li.dropdown').hover(function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
    //     }, function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
    //     });_x000D_
    _x000D_
    //     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
    //     }, function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
    //     });_x000D_
    _x000D_
    _x000D_
    //     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    //         event.preventDefault();_x000D_
    //         event.stopPropagation();_x000D_
    //         $(this).parent().siblings().removeClass('open');_x000D_
    //         $(this).parent().toggleClass('open');_x000D_
    //         $('b', this).toggleClass("caret caret-up");_x000D_
    //     });_x000D_
    // }_x000D_
    _x000D_
    // $(window).resize(function() {_x000D_
    //     if( $(this).width() >= 767) {_x000D_
    //         $('ul.nav li.dropdown').hover(function() {_x000D_
    //             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
    //         }, function() {_x000D_
    //             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
    //         });_x000D_
    //     }_x000D_
    // });_x000D_
    _x000D_
    var windowWidth = $(window).width();_x000D_
    if (windowWidth > 767) {_x000D_
      // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
      //     event.preventDefault();_x000D_
      //     event.stopPropagation();_x000D_
      //     $(this).parent().siblings().removeClass('open');_x000D_
      //     $(this).parent().toggleClass('open');_x000D_
      //     $('b', this).toggleClass("caret caret-up");_x000D_
      // });_x000D_
    _x000D_
      $('ul.nav li.dropdown').hover(function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
      }, function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
      });_x000D_
    _x000D_
      $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
      }, function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
      });_x000D_
    _x000D_
    _x000D_
      $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
        event.preventDefault();_x000D_
        event.stopPropagation();_x000D_
        $(this).parent().siblings().removeClass('open');_x000D_
        $(this).parent().toggleClass('open');_x000D_
        // $('b', this).toggleClass("caret caret-up");_x000D_
      });_x000D_
    }_x000D_
    if (windowWidth < 767) {_x000D_
      $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
        event.preventDefault();_x000D_
        event.stopPropagation();_x000D_
        $(this).parent().siblings().removeClass('open');_x000D_
        $(this).parent().toggleClass('open');_x000D_
        // $('b', this).toggleClass("caret caret-up");_x000D_
      });_x000D_
    }_x000D_
    _x000D_
    // $('.dropdown a').append('Some text');
    _x000D_
    @media only screen and (max-width: 767px) {_x000D_
      #slide-navbar-collapse {_x000D_
        position: fixed;_x000D_
        top: 0;_x000D_
        left: 15px;_x000D_
        z-index: 999999;_x000D_
        width: 280px;_x000D_
        height: 100%;_x000D_
        background-color: #f9f9f9;_x000D_
        overflow: auto;_x000D_
        bottom: 0;_x000D_
        max-height: inherit;_x000D_
      }_x000D_
      .menu-overlay {_x000D_
        display: none;_x000D_
        background-color: #000;_x000D_
        bottom: 0;_x000D_
        left: 0;_x000D_
        opacity: 0.5;_x000D_
        filter: alpha(opacity=50);_x000D_
        /* IE7 & 8 */_x000D_
        position: fixed;_x000D_
        right: 0;_x000D_
        top: 0;_x000D_
        z-index: 49;_x000D_
      }_x000D_
      .navbar-fixed-top {_x000D_
        position: initial !important;_x000D_
      }_x000D_
      .navbar-nav .open .dropdown-menu {_x000D_
        background-color: #ffffff;_x000D_
      }_x000D_
      ul.nav.navbar-nav li {_x000D_
        border-bottom: 1px solid #eee;_x000D_
      }_x000D_
      .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
      .navbar-nav .open .dropdown-menu>li>a {_x000D_
        padding: 10px 20px 10px 15px;_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    .dropdown-submenu {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    .dropdown-submenu .dropdown-menu {_x000D_
      top: 0;_x000D_
      left: 100%;_x000D_
      margin-top: -1px;_x000D_
    }_x000D_
    _x000D_
    li.dropdown a {_x000D_
      display: block;_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    li.dropdown>a:before {_x000D_
      content: "\f107";_x000D_
      font-family: FontAwesome;_x000D_
      position: absolute;_x000D_
      right: 6px;_x000D_
      top: 5px;_x000D_
      font-size: 15px;_x000D_
    }_x000D_
    _x000D_
    li.dropdown-submenu>a:before {_x000D_
      content: "\f107";_x000D_
      font-family: FontAwesome;_x000D_
      position: absolute;_x000D_
      right: 6px;_x000D_
      top: 10px;_x000D_
      font-size: 15px;_x000D_
    }_x000D_
    _x000D_
    ul.dropdown-menu li {_x000D_
      border-bottom: 1px solid #eee;_x000D_
    }_x000D_
    _x000D_
    .dropdown-menu {_x000D_
      padding: 0px;_x000D_
      margin: 0px;_x000D_
      border: none !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown.open {_x000D_
      border-bottom: 0px !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown-submenu.open {_x000D_
      border-bottom: 0px !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown-submenu>a {_x000D_
      font-weight: bold !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown>a {_x000D_
      font-weight: bold !important;_x000D_
    }_x000D_
    _x000D_
    .navbar-default .navbar-nav>li>a {_x000D_
      font-weight: bold !important;_x000D_
      padding: 10px 20px 10px 15px;_x000D_
    }_x000D_
    _x000D_
    li.dropdown>a:before {_x000D_
      content: "\f107";_x000D_
      font-family: FontAwesome;_x000D_
      position: absolute;_x000D_
      right: 6px;_x000D_
      top: 9px;_x000D_
      font-size: 15px;_x000D_
    }_x000D_
    _x000D_
    @media (min-width: 767px) {_x000D_
      li.dropdown-submenu>a {_x000D_
        padding: 10px 20px 10px 15px;_x000D_
      }_x000D_
      li.dropdown>a:before {_x000D_
        content: "\f107";_x000D_
        font-family: FontAwesome;_x000D_
        position: absolute;_x000D_
        right: 3px;_x000D_
        top: 12px;_x000D_
        font-size: 15px;_x000D_
      }_x000D_
    }
    _x000D_
    <!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    _x000D_
      <head>_x000D_
        <title>Bootstrap Example</title>_x000D_
        <meta charset="utf-8">_x000D_
        <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
    _x000D_
      </head>_x000D_
    _x000D_
      <body>_x000D_
        <nav class="navbar navbar-default navbar-fixed-top">_x000D_
          <div class="container-fluid">_x000D_
            <!-- Brand and toggle get grouped for better mobile display -->_x000D_
            <div class="navbar-header">_x000D_
              <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                        <span class="sr-only">Toggle navigation</span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
              <a class="navbar-brand" href="#">Brand</a>_x000D_
            </div>_x000D_
            <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
            <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
              <ul class="nav navbar-nav">_x000D_
                <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
                <li><a href="#">Link</a></li>_x000D_
                <li class="dropdown">_x000D_
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">Action</a></li>_x000D_
                    <li><a href="#">Another action</a></li>_x000D_
                    <li><a href="#">Something else here</a></li>_x000D_
                    <li><a href="#">Separated link</a></li>_x000D_
                    <li><a href="#">One more separated link</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li class="dropdown-submenu">_x000D_
                          <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                          <ul class="dropdown-menu">_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                          </ul>_x000D_
                        </li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                <li><a href="#">Link</a></li>_x000D_
              </ul>_x000D_
              <ul class="nav navbar-nav navbar-right">_x000D_
                <li><a href="#">Link</a></li>_x000D_
                <li class="dropdown">_x000D_
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">Action</a></li>_x000D_
                    <li><a href="#">Another action</a></li>_x000D_
                    <li><a href="#">Something else here</a></li>_x000D_
                    <li><a href="#">Separated link</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </div>_x000D_
            <!-- /.navbar-collapse -->_x000D_
          </div>_x000D_
          <!-- /.container-fluid -->_x000D_
        </nav>_x000D_
        <div class="menu-overlay"></div>_x000D_
        <div class="col-md-12">_x000D_
          <h1>Resize the window to see the result</h1>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
        </div>_x000D_
    _x000D_
      </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Reference JS fiddle

    MySQL delete multiple rows in one query conditions unique to each row

    Took a lot of googling but here is what I do in Python for MySql when I want to delete multiple items from a single table using a list of values.

    #create some empty list
    values = []
    #continue to append the values you want to delete to it
    #BUT you must ensure instead of a string it's a single value tuple
    values.append(([Your Variable],))
    #Then once your array is loaded perform an execute many
    cursor.executemany("DELETE FROM YourTable WHERE ID = %s", values)
    

    Display a message in Visual Studio's output window when not debug mode?

    The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).

    This works with Debug.WriteLine and Console.WriteLine.

    Dynamically Add C# Properties at Runtime

    Thanks @Clint for the great answer:

    Just wanted to highlight how easy it was to solve this using the Expando Object:

        var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
        foreach (var property in properties) {
            dynamicObject.Add(property.Key,property.Value);
        }
    

    How to retrieve raw post data from HttpServletRequest in java

    The request body is available as byte stream by HttpServletRequest#getInputStream():

    InputStream body = request.getInputStream();
    // ...
    

    Or as character stream by HttpServletRequest#getReader():

    Reader body = request.getReader();
    // ...
    

    Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

    How to check command line parameter in ".bat" file?

    The short answer - use square brackets:

    if [%1]==[] goto :blank
    

    or (when you need to handle quoted args, see the Edit below):

    if [%~1]==[] goto :blank
    

    Why? you might ask. Well, just as Jeremiah Willcock mentioned: http://ss64.com/nt/if.html - they use that! OK, but what's wrong with the quotes?

    Again, short answer: they are "magical" - sometimes double (double) quotes get converted to a single (double) quote. And they need to match, for a start.

    Consider this little script:

    @rem argq.bat
    @echo off
    
    :loop 
    if "%1"=="" goto :done
    echo %1
    shift
    goto :loop
    
    :done
    echo Done.
    

    Let's test it:

    C:\> argq bla bla
    bla
    bla
    Done.
    

    Seems to work. But now, lets switch to second gear:

    C:\> argq "bla bla"
    bla""=="" was unexpected at this time.
    

    Boom This didn't evaluate to true, neither did it evaluate to false. The script DIED. If you were supposed to turn off the reactor somewhere down the line, well - tough luck. You now will die like Harry Daghlian.

    You may think - OK, the arguments can't contain quotes. If they do, this happens. Wrong Here's some consolation:

    C:\> argq ""bla bla""
    ""bla
    bla""
    Done.
    

    Oh yeah. Don't worry - sometimes this will work.

    Let's try another script:

    @rem args.bat
    @echo off
    
    :loop 
    if [%1]==[] goto :done
    echo %1
    shift
    goto :loop
    
    :done
    echo Done.
    

    You can test yourself, that it works OK for the above cases. This is logical - quotes have nothing to do with brackets, so there's no magic here. But what about spicing the args up with brackets?

    D:\>args ]bla bla[
    ]bla
    bla[
    Done.
    
    D:\>args [bla bla]
    [bla
    bla]
    Done.
    

    No luck there. The brackets just can't choke cmd.exe's parser.

    Let's go back to the evil quotes for a moment. The problem was there, when the argument ended with a quote:

    D:\>argq "bla1 bla2"
    bla2""=="" was unexpected at this time.
    

    What if I pass just:

    D:\>argq bla2"
    The syntax of the command is incorrect.
    

    The script won't run at all. Same for args.bat:

    D:\>args bla2"
    The syntax of the command is incorrect.
    

    But what do I get, when the number of "-characters "matches" (i.e. - is even), in such a case:

    D:\>args bla2" "bla3
    bla2" "bla3
    Done.
    

    NICE - I hope you learned something about how .bat files split their command line arguments (HINT: *It's not exactly like in bash). The above argument contains a space. But the quotes are not stripped automatically.

    And argq? How does it react to that? Predictably:

    D:\>argq bla2" "bla3
    "bla3"=="" was unexpected at this time.
    

    So - think before you say: "Know what? Just use quotes. [Because, to me, this looks nicer]".

    Edit

    Recently, there were comments about this answer - well, sqare brackets "can't handle" passing quoted arguments and treating them just as if they weren't quoted.

    The syntax:

    if "%~1"=="" (...)
    

    Is not some newly found virtue of the double quotes, but a display of a neat feature of stripping quotes from the argument variable, if the first and last character is a double quote.

    This "technology" works just as well with square brackets:

    if [%~1]==[] (...)
    

    It was a useful thing to point this out, so I also upvote the new answer.

    Finally, double quote fans, does an argument of the form "" exist in your book, or is it blank? Just askin' ;)

    ALTER COLUMN in sqlite

    While it is true that the is no ALTER COLUMN, if you only want to rename the column, drop the NOT NULL constraint, or change the data type, you can use the following set of dangerous commands:

    PRAGMA writable_schema = 1;
    UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';
    PRAGMA writable_schema = 0;
    

    You will need to either close and reopen your connection or vacuum the database to reload the changes into the schema.

    For example:

    Y:\> **sqlite3 booktest**  
    SQLite version 3.7.4  
    Enter ".help" for instructions  
    Enter SQL statements terminated with a ";"  
    sqlite> **create table BOOKS ( title TEXT NOT NULL, publication_date TEXT NOT 
    NULL);**  
    sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
    Error: BOOKS.publication_date may not be NULL  
    sqlite> **PRAGMA writable_schema = 1;**  
    sqlite> **UPDATE SQLITE_MASTER SET SQL = 'CREATE TABLE BOOKS ( title TEXT NOT 
    NULL, publication_date TEXT)' WHERE NAME = 'BOOKS';**  
    sqlite> **PRAGMA writable_schema = 0;**  
    sqlite> **.q**  
    
    Y:\> **sqlite3 booktest**  
    SQLite version 3.7.4  
    Enter ".help" for instructions  
    Enter SQL statements terminated with a ";"  
    sqlite> **insert into BOOKS VALUES ("NULLTEST",null);**  
    sqlite> **.q**  
    

    REFERENCES FOLLOW:


    pragma writable_schema
    When this pragma is on, the SQLITE_MASTER tables in which database can be changed using ordinary UPDATE, INSERT, and DELETE statements. Warning: misuse of this pragma can easily result in a corrupt database file.

    [alter table](From http://www.sqlite.org/lang_altertable.html)
    SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

    ALTER TABLE SYNTAX

    HTML5 pattern for formatting input box to take date mm/dd/yyyy?

    Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD

    <input type="text"  placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control "  name="eventDate" id="" required autofocus autocomplete="nope">
    

    I got this solution from http://html5pattern.com/Dates. Hope it may help someone.

    Remove local git tags that are no longer on the remote repository

    The same answer as @Richard W but for Windows (PowerShell)

    git tag | foreach-object -process { git tag -d $_ }
    git fetch -t
    

    how to use DEXtoJar

    1. Download latest dex2jar from here -> dex2jar
    2. Run this command on linux -> sh d2j-dex2jar.sh classes.dex
    3. Download java decompiler from here - > JD-GUI
    4. Drag and drop the classes-dex2jar.jar file to JD-GUI