Programs & Examples On #Extreme feedback devices

VS Code - Search for text in all files in a directory

Select your folder, Press ? + ? + F Don't know about windows but this works for mac :)

Mocking Extension Methods with Moq

You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (, a free tool from Microsoft that implements a different approach. Here is the description of the tool:

Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.

Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.

You can use Moles with any testing framework (it's independent about that).

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Upgrade pip as follows:

curl | python

Note: You may need to use sudo python above if not in a virtual environment.

What's happening: sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.

(Note that upgrading pip via pip install --upgrade pip will also not upgrade it correctly. It is a chicken-and-egg issue)

This thread explains it (thanks to this Twitter post):

Mac users who use pip and PyPI:

If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:

curl | python

and we recommend you do that by April 8th.

Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes:

Also, the Python status page:

Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC

Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC

Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:

pip install --upgrade setuptools

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

How to start MySQL server on windows xp

The error complains about localhost rather than permissions and the current practice in MySQL is to have a bind-address specifying localhost only in a configuration file.

So I don't think it's a password problem - except that you say you 'unzipped' MySQL.

Is that enough installation? What did you download?

Was there any installation step which allowed you to define a root password?

And, as NawaMan said, is the server running?

Find integer index of rows with NaN in pandas dataframe

And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:

df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])

   0  1  2    3    4  5
0  0  1  3  4.0  NaN  2
1  3  5  6  NaN  3.0  3

(array([0, 1]), array([4, 3]))

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td


    <td data-rel='$'>$</td>


table tr td[data-rel='$'] {
    background-color: #333;
    color: white;

Please try these example.

table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
<table border="1">_x000D_
        <td data-content='$'>$</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td data-content='$'>$</td>_x000D_

counting number of directories in a specific directory

Best way to navigate to your drive and simply execute

ls -lR | grep ^d | wc -l

and to Find all folders in total, including subdirectories?

find /mount/point -type d | wc -l

...or find all folders in the root directory (not including subdirectories)?

find /mount/point -maxdepth 1 -type d | wc -l


"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I got this error:

System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

when the port was used by another program.

Git: force user and password prompt

None of those worked for me. I was trying to clone a directory from a private git server and entered my credentials false and then it wouldn't let me try different credentials on subsequent tries, it just errored out immediately with an authentication error.

What did work was specifying the user name (mike-wise)in the url like this:

   git clone https://[email protected]/someuser/somerepo.git

Move to another EditText when Soft Keyboard Next is clicked on Android

Simple way :

  • Auto move cursor to next edittext
  • If edittext is last input -> hidden keyboard

Add this to edittext field in .xml file


how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:


--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way

No warnings

Automate scp file transfer using a shell script

The command scp can be used like a traditional UNIX cp. SO if you do :

scp -r myDirectory/ mylogin@host:TargetDirectory

will work

using stored procedure in entity framework

After importing stored procedure, you can create object of stored procedure pass the parameter like function

using (var entity = new FunctionsContext())
   var DBdata = entity.GetFunctionByID(5).ToList<Functions>();

or you can also use SqlQuery

using (var entity = new FunctionsContext())
    var Parameter = new SqlParameter {
                     ParameterName = "FunctionId",
                     Value = 5

    var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();

How to write a CSS hack for IE 11?

I found this helpful

<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false) { ?>
<?php } ?>

Add this under your <head> document

How to set a selected option of a dropdown list control using angular JS

i see here already wrote good answers, but sometime to write the same in other form can be helpful

<div ng-app ng-controller="MyCtrl">
  <select ng-model="referral.organization" ng-options="c for c in organizations"></select>

<script type='text/javascript'>
  function MyCtrl($scope) {
    $scope.organizations = ['a', 'b', 'c', 'd', 'e'];
    $scope.referral = {
      organization: $scope.organizations[2]

How to order a data frame by one descending and one ascending column?

In @dudusan's example, you could also reverse the order of I1, and then sort ascending:

> rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
+   2   3   5   52  43  61  6   b
+   6   4   3   72  NA  59  1   a
+   1   5   6   55  48  60  6   f
+   2   4   4   65  64  58  2   b
+   1   5   6   55  48  60  6   c"), header = TRUE)
> f=factor(rum$I1)   
> levels(f) <- sort(levels(f), decreasing = TRUE)
> rum[order(as.character(f), rum$I2), ]
  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

This seems a bit shorter, you don't reverse the order of I2 twice.

Apache Prefork vs Worker MPM

Prefork and worker are two type of MPM apache provides. Both have their merits and demerits.

By default mpm is prefork which is thread safe.

Prefork MPM uses multiple child processes with one thread each and each process handles one connection at a time.

Worker MPM uses multiple child processes with many threads each. Each thread handles one connection at a time.

For more details you can visit and

Shortest way to check for null and assign another value if not

Try this:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();

You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:

this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();

But this example only works since a possible value for this.approved_by is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.

How do I upgrade to Python 3.6 with conda?

Best method I found:

source activate old_env
conda env export > old_env.yml

Then process it with something like this:

with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
    for line in fin:
        if 'py35' in line:  # replace by the version you want to supersede
            line = line[:line.rfind('=')] + '\n'

then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

conda env create -f new_env.yml

you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

I wish there was a built-in, easier way...

HTML button onclick event

"button" value="Add Students" onclick="window.location.href='Students.html';"> 
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"> 
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">

How to make use of ng-if , ng-else in angularJS

There is no directive for ng-else

You can use ng-if to achieve if(){..} else{..} in angularJs.

For your current situation,

<div ng-if=" == 5">
<!-- If block -->
<div ng-if=" != 5">
<!-- Your Else Block -->

jQuery checkbox event handling

$('#myform input:checkbox').click(

Parsing JSON with Unix tools

Here is a simple approach for Node.js-ready environment:

curl -L > json
chmod +x json
echo '{"hello":{"hi":"there"}}' | ./json "hello.hi"

bash: npm: command not found?

If you have already installed nodejs and still getting this error. npm: command not found..

run this

apt-get install -y npm

How can I combine two commits into one commit?

  1. Checkout your branch and count quantity of all your commits.
  2. Open git bash and write: git rebase -i HEAD~<quantity of your commits> (i.e. git rebase -i HEAD~5)
  3. In opened txt file change pick keyword to squash for all commits, except first commit (which is on the top). For top one change it to reword (which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc then save by entering wq! and press enter.
  4. Provide Comment.
  5. Open Git and make "Fetch all" to see new changes.


How do I show/hide a UIBarButtonItem?

For Swift 3 and Swift 4 you can do this to hide the UIBarButtomItem:

self.deleteButton.isEnabled = false
self.deleteButton.tintColor = UIColor.clear

And to show the UIBarButtonItem:

self.deleteButton.isEnabled = true
self.deleteButton.tintColor =

On the tintColor you must have to specify the origin color you are using for the UIBarButtomItem

What is the difference between class and instance methods?

Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

How to replace multiple white spaces with one white space

You can try this:

    /// <summary>
    /// Remove all extra spaces and tabs between words in the specified string!
    /// </summary>
    /// <param name="str">The specified string.</param>
    public static string RemoveExtraSpaces(string str)
        str = str.Trim();
        StringBuilder sb = new StringBuilder();
        bool space = false;
        foreach (char c in str)
            if (char.IsWhiteSpace(c) || c == (char)9) { space = true; }
            else { if (space) { sb.Append(' '); }; sb.Append(c); space = false; };
        return sb.ToString();

List names of all tables in a SQL Server 2012 schema

SELECT AS [Schema], AS [Table]
FROM sys.schemas t1
INNER JOIN sys.tables t2
ON t2.schema_id = t1.schema_id

How to programmatically send a 404 response with Express/Node?

According to the site I'll post below, it's all how you set up your server. One example they show is this:

var http = require("http");
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    route(handle, pathname, response);

  console.log("Server has started.");

exports.start = start;

and their route function:

function route(handle, pathname, response) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");

exports.route = route;

This is one way.

From another site, they create a page and then load it. This might be more of what you're looking for.

fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});

Can't connect Nexus 4 to adb: unauthorized

Use a different USB cable. Some cables may not have all pins connected or whatnot, and while they work for image transfer, the debugging/adb does not work.

The bottom line: I kid you not. A cable which works for my phone (adb works) does NOT work for my tablet - the device is always offline or unauthorized and tablet pops out no dialog. I tried multiple reboots, settings, I went berserk in the process and cursed the bloody Android. Then accidentally I plugged in the cable which came with the tablet and suddenly it worked. My fascination with Android is definitely gone. What a stupid piece of junk.

SQL Insert Multiple Rows

Wrap each row of values to be inserted in brackets/parenthesis (value1, value2, value3) and separate the brackets/parenthesis by comma for as many as you wish to insert into the table.

  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

How to format a QString?

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.

How to set combobox default value?

You can do something like this:

    public myform()
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();

    private void Form1_Load(object sender, EventArgs e)
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

CodeIgniter Active Record not equal

$this->db->where('emailsToCampaigns.campaignId !=' , $campaignId);

This should work (which you have tried)

To debug you might place this code just after you execute your query to see what exact SQL it is producing, this might give you clues, you might add that to the question to allow for further help.

$this->db->get();              // your query executing

echo '<pre>';                  // to preserve formatting
die($this->db->last_query());  // halt execution and print last ran query.

What does -> mean in Python function definitions?

It's a function annotation.

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

Disable and later enable all table indexes in Oracle

From here:

alter session set skip_unusable_indexes = true;

alter index your_index unusable;

do import...

alter index your_index rebuild [online];

git: undo all working dir changes including new files

I thought it was (warning: following will wipe out everything)

$ git reset --hard HEAD
$ git clean -fd

The reset to undo changes. The clean to remove any untracked files and directories.

How to get 'System.Web.Http, Version=

Uninstalling and re-installing the NuGet package worked for me.

  1. Remove any old reference from the project.

Execute this in the Package Manager Console:

  1. UnInstall-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
  2. Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3

Extract a single (unsigned) integer from a string

try this,use preg_replace

$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;


If list index exists, do X

It can be done simply using the following code:

if index < len(my_list):
    print(index, 'exists in the list')
    print(index, "doesn't exist in the list")

Pip error: Microsoft Visual C++ 14.0 is required

On Windows, I strongly recommand installing latest Visual Stuido Community, it's free, you will maybe miss some build tools if you only install vc_redist, so you can easily install package by pip instead of wheel, it save lot of time

OSError: [Errno 2] No such file or directory while using python subprocess in Django

No such file or directory can be also raised if you are trying to put a file argument to Popen with double-quotes.

For example:

call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']

In this case, you need to remove double-quotes.

call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']

Error to run Android Studio

Widows 7 64 bit.

  1. JAVA_HOME point to my JRE (NOT JDK) directory
  2. Coping of tools.jar from JDK\lib directory to ANDROIDSTUDIO\lib directory solve the problem

Problems installing the devtools package

As per damienfrancois's suggestion, I installed libcurl4-gnutls-dev and the problem was solved.

EDIT (@dardisco)

In your shell:

apt-get -y build-dep libcurl4-gnutls-dev
apt-get -y install libcurl4-gnutls-dev

Concatenate a NumPy array to another NumPy array

You may use numpy.append()...

import numpy

B = numpy.array([3])
A = numpy.array([1, 2, 2])
B = numpy.append( B , A )

print B

> [3 1 2 2]

This will not create two separate arrays but will append two arrays into a single dimensional array.

Member '<method>' cannot be accessed with an instance reference

I know this is an old thread, but I just spent 3 hours trying to figure out what my issue was. I ordinarily know what this error means, but you can run into this in a more subtle way as well. My issue was my client class (the one calling a static method from an instance class) had a property of a different type but named the same as the static method. The error reported by the compiler was the same as reported here, but the issue was basically name collision.

For anyone else getting this error and none of the above helps, try fully qualifying your instance class with the namespace name. ..() so the compiler can see the exact name you mean.

Using Google Text-To-Speech in Javascript

You can use the SpeechSynthesisUtterance with a function like say:

function say(m) {
  var msg = new SpeechSynthesisUtterance();
  var voices = window.speechSynthesis.getVoices();
  msg.voice = voices[10];
  msg.voiceURI = "native";
  msg.volume = 1;
  msg.rate = 1;
  msg.pitch = 0.8;
  msg.text = m;
  msg.lang = 'en-US';

Then you only need to call say(msg) when using it.

Update: Look at Google's Developer Blog that is about Voice Driven Web Apps Introduction to the Web Speech API.

How to change line color in EditText


        android:background="#03f94e" />

**it one of doing with view **

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

You must enable the transaction support (<tx:annotation-driven> or @EnableTransactionManagement) and declare the transactionManager and it should work through the SessionFactory.

You must add @Transactional into your @Repository

With @Transactional in your @Repository Spring is able to apply transactional support into your repository.

Your Student class has no the @javax.persistence.* annotations how @Entity, I am assuming the Mapping Configuration for that class has been defined through XML.

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

How to download PDF automatically using js?

  1. for second point, get a full path to pdf file into some java variable. e.g.

e.g. you're using php and $filepath contains pdf file path.

so you can write javascript like to to emulate download dialog box.

<script language="javascript">
    window.location.href = '<?php echo $filepath; ?>';

Above code sends browser to pdf file by its url "". So at last, browser will show download dialog box to where to save this file on your machine.

Multi-dimensional arrays in Bash

Bash does not support multidimensional arrays, nor hashes, and it seems that you want a hash that values are arrays. This solution is not very beautiful, a solution with an xml file should be better :

array=('d1=(v1 v2 v3)' 'd2=(v1 v2 v3)')
for elt in "${array[@]}";do eval $elt;done
echo "d1 ${#d1[@]} ${d1[@]}"
echo "d2 ${#d2[@]} ${d2[@]}"

EDIT: this answer is quite old, since since bash 4 supports hash tables, see also this answer for a solution without eval.

jquery - disable click

assuming your using click events, just unbind that one.


if (current = 1){ 

EDIT: Are you currently binding a click event to your list somewhere? Based on your comment above, I'm wondering if this is really what you're doing? How are you enabling the click? Is it just an anchor(<a> tag) ? A little more explicit information will help us answer your question.


Did some playing around with the :eq() operator.

As I should have expected it is a 0 based index operator. So if you want to turn of the second element in your selection, where your selection is

$("#navigation a")

you would simply add :eq(1) (the second index) and then .unbind("click") So:

if(current == 1){
    $("#navigation a:eq(1)").unbind("click");

Ought to do the trick.

Hope this helps!

How to empty the message in a text area with jquery?


Explanation (from @BalusC):
textarea is an input element with a value. You actually want to "empty" the value. So as for every other input element (input, select, textarea) you need to use element.val('');.

Also see docs

How to concat string + i?

according to this it looks like you have to set "N" before trying to use it and it looks like it needs to be an int not string? Don't know much bout MatLab but just what i gathered from that site..hope it helps :)

git pull from master into the development branch

The steps you listed will work, but there's a longer way that gives you more options:

git checkout dmgr2      # gets you "on branch dmgr2"
git fetch origin        # gets you up to date with origin
git merge origin/master

The fetch command can be done at any point before the merge, i.e., you can swap the order of the fetch and the checkout, because fetch just goes over to the named remote (origin) and says to it: "gimme everything you have that I don't", i.e., all commits on all branches. They get copied to your repository, but named origin/branch for any branch named branch on the remote.

At this point you can use any viewer (git log, gitk, etc) to see "what they have" that you don't, and vice versa. Sometimes this is only useful for Warm Fuzzy Feelings ("ah, yes, that is in fact what I want") and sometimes it is useful for changing strategies entirely ("whoa, I don't want THAT stuff yet").

Finally, the merge command takes the given commit, which you can name as origin/master, and does whatever it takes to bring in that commit and its ancestors, to whatever branch you are on when you run the merge. You can insert --no-ff or --ff-only to prevent a fast-forward, or merge only if the result is a fast-forward, if you like.

When you use the sequence:

git checkout dmgr2
git pull origin master

the pull command instructs git to run git fetch, and then the moral equivalent of git merge origin/master. So this is almost the same as doing the two steps by hand, but there are some subtle differences that probably are not too concerning to you. (In particular the fetch step run by pull brings over only origin/master, and it does not update the ref in your repo:1 any new commits winds up referred-to only by the special FETCH_HEAD reference.)

If you use the more-explicit git fetch origin (then optionally look around) and then git merge origin/master sequence, you can also bring your own local master up to date with the remote, with only one fetch run across the network:

git fetch origin
git checkout master
git merge --ff-only origin/master
git checkout dmgr2
git merge --no-ff origin/master

for instance.

1This second part has been changed—I say "fixed"—in git 1.8.4, which now updates "remote branch" references opportunistically. (It was, as the release notes say, a deliberate design decision to skip the update, but it turns out that more people prefer that git update it. If you want the old remote-branch SHA-1, it defaults to being saved in, and thus recoverable from, the reflog. This also enables a new git 1.9/2.0 feature for finding upstream rebases.)

PHP: trying to create a new line with "\n"

This answer was so obvious and it took me forever to figure out:

echo "foo

I know that looks like it's wrapping. It's not. What I did is I literally hit return halfway through the string, between foo and bar. It creates a new line in the HTML source and makes your PHP look horrible. This was in Linux/Apache.

How to convert an enum type variable to a string?

The naive solution, of course, is to write a function for each enumeration that performs the conversion to string:

enum OS_type { Linux, Apple, Windows };

inline const char* ToString(OS_type v)
    switch (v)
        case Linux:   return "Linux";
        case Apple:   return "Apple";
        case Windows: return "Windows";
        default:      return "[Unknown OS_type]";

This, however, is a maintenance disaster. With the help of the Boost.Preprocessor library, which can be used with both C and C++ code, you can easily take advantage of the preprocessor and let it generate this function for you. The generation macro is as follows:

#include <boost/preprocessor.hpp>

    case elem : return BOOST_PP_STRINGIZE(elem);

#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators)                \
    enum name {                                                               \
        BOOST_PP_SEQ_ENUM(enumerators)                                        \
    };                                                                        \
    inline const char* ToString(name v)                                       \
    {                                                                         \
        switch (v)                                                            \
        {                                                                     \
            BOOST_PP_SEQ_FOR_EACH(                                            \
                name,                                                         \
                enumerators                                                   \
            )                                                                 \
            default: return "[Unknown " BOOST_PP_STRINGIZE(name) "]";         \
        }                                                                     \

The first macro (beginning with X_) is used internally by the second. The second macro first generates the enumeration, then generates a ToString function that takes an object of that type and returns the enumerator name as a string (this implementation, for obvious reasons, requires that the enumerators map to unique values).

In C++ you could implement the ToString function as an operator<< overload instead, but I think it's a bit cleaner to require an explicit "ToString" to convert the value to string form.

As a usage example, your OS_type enumeration would be defined as follows:


While the macro looks at first like it is a lot of work, and the definition of OS_type looks rather foreign, remember that you have to write the macro once, then you can use it for every enumeration. You can add additional functionality to it (e.g., a string-form to enum conversion) without too much trouble, and it completely solves the maintenance problem, since you only have to provide the names once, when you invoke the macro.

The enumeration can then be used as if it were defined normally:

#include <iostream>

int main()
    OS_type t = Windows;
    std::cout << ToString(t) << " " << ToString(Apple) << std::endl;

The code snippets in this post, beginning with the #include <boost/preprocessor.hpp> line, can be compiled as posted to demonstrate the solution.

This particular solution is for C++ as it uses C++-specific syntax (e.g., no typedef enum) and function overloading, but it would be straightforward to make this work with C as well.

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print( + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

SMTP connect() failed PHPmailer - PHP

if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account. // turn it on

Cannot execute RUN mkdir in a Dockerfile

Apart from the previous use cases, you can also use Docker Compose to create directories in case you want to make new dummy folders on docker-compose up:

  - .:/ftp/
  - /ftp/node_modules
  - /ftp/files

How do I create a link to add an entry to a calendar?

You can have the program create an .ics (iCal) version of the calendar and then you can import this .ics into whichever calendar program you'd like: Google, Outlook, etc.

I know this post is quite old, so I won't bother inputting any code. But please comment on this if you'd like me to provide an outline of how to do this.

Arguments to main in C

The signature of main is:

int main(int argc, char **argv);

argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

So, if you ran your program like this:

./program hello world


  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Template/HTML File (component.ts)

 <option *ngFor="let v of values" [value]="v" (ngModelChange)="onChange($event)">  

Typescript File (component.ts)

values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }

    console.log(cityEvent); // It will display the select city data

(ngModelChange) is the @Output of the ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive

Cannot perform runtime binding on a null reference, But it is NOT a null reference

Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.

What is the "__v" field in Mongoose

Well, I can't see Tony's I have to handle it myself...

If you don't need version_key, you can just:

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default:}
}, {
    versionKey: false // You should be aware of the outcome after set to false

Setting the versionKey to false means the document is no longer versioned.

This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.

Since the array is now smaller, it may accidentally access the wrong subdocument in the array.

The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.

More information can be found at:

How do I wrap text in a pre tag?

I combined @richelectron and @user1433454 answers.
It works very well and preserves the text formatting.

<pre  style="white-space: pre-wrap; word-break: keep-all;">


What is a C++ delegate?

Windows Runtime equivalent of a function object in standard C++. One can use the whole function as a parameter (actually that is a function pointer). It is mostly used in conjunction with events. The delegate represents a contract that event handlers much fulfill. It facilitate how a function pointer can work for.

Creating a list of pairs in java

If you want multiplicities, you can put it in map that maps pair to ammount. This way there will only be one pair of given values, but it can represent multiple occurances.

Then if you have lot of repeatet values and want to perform some operation on all values, you can save lot of computations.

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

std::string formatting like sprintf

For Visual C:

std::wstring stringFormat(const wchar_t* fmt, ...)
    if (!fmt) {
        return L"";

    std::vector<wchar_t> buff;
    size_t size = wcslen(fmt) * 2;
    va_list ap;
    va_start(ap, fmt);
    while (true) {
        int ret = _vsnwprintf_s(, size, _TRUNCATE, fmt, ap);
        if (ret != -1)
        else {
            size *= 2;
    return std::wstring(;

Firebug-like debugger for Google Chrome

This doesn't answer your question but, in case you missed it, Chris Pederick's Web Developer is now available for Chrome:

sqlite copy data from one table to another

INSERT INTO Destination SELECT * FROM Source;

See SQL As Understood By SQLite: INSERT for a formal definition.

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

How to calculate combination and permutation in R?

It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.

Reading specific columns from a text file in python

You have a space delimited file, so use the module designed for reading delimited values files, csv.

import csv

with open('path/to/file.txt') as inf:
    reader = csv.reader(inf, delimiter=" ")
    second_col = list(zip(*reader))[1]
    # In Python2, you can omit the `list(...)` cast

The zip(*iterable) pattern is useful for converting rows to columns or vice versa. If you're reading a file row-wise...

>>> testdata = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]]

>>> for line in testdata:
...     print(line)

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

...but need columns, you can pass each row to the zip function

>>> testdata_columns = zip(*testdata)
# this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])

>>> for line in testdata_columns:
...     print(line)

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

lvalue required as left operand of assignment error when using C++

It is just a typo(I guess)-


instead of p +1=p; is required .

As name suggest lvalue expression should be left-hand operand of the assignment operator.

How to get maximum value from the Collection (for example ArrayList)?

This question is almost a year old but I have found that if you make a custom comparator for objects you can use Collections.max for an array list of objects.

import java.util.Comparator;

public class compPopulation implements Comparator<Country> {
    public int compare(Country a, Country b) {
        if (a.getPopulation() > b.getPopulation())
            return -1; // highest value first
        if (a.getPopulation() == b.Population())
            return 0;
        return 1;
ArrayList<Country> X = new ArrayList<Country>();
// create some country objects and put in the list
Country ZZ = Collections.max(X, new compPopulation());

How do I use regex in a SQLite query?

A hacky way to solve it without regex is where ',' || x || ',' like '%,3,%'

Difference between readFile() and readFileSync()

'use strict'
var fs = require("fs");

 * implementation of readFileSync
var data = fs.readFileSync('input.txt');
console.log("Program Ended");

 * implementation of readFile 
fs.readFile('input.txt', function (err, data) {
    if (err) return console.error(err);

console.log("Program Ended");

For better understanding run the above code and compare the results..

Cannot create Maven Project in eclipse

For me the solution was a bit simpler, I just had to clean the repository : .m2/repository/org/apache/maven/archetypes

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Its just that you need multiple When for a single case to behave it like if.. Elseif else..

   Case when 1=1       //if
    When 1=1              //else if
    When .....              //else if
    Else                      //else

Pass in an array of Deferreds to $.when()

I want to propose other one with using $.each:

  1. We may to declare ajax function like:

    function ajaxFn(someData) {
        this.someData = someData;
        var that = this;
        return function () {
            var promise = $.Deferred();
                method: "POST",
                url: "url",
                data: that.someData,
                success: function(data) {
                error: function(data) {
            return promise;
  2. Part of code where we creating array of functions with ajax to send:

    var arrayOfFn = [];
    for (var i = 0; i < someDataArray.length; i++) {
        var ajaxFnForArray = new ajaxFn(someDataArray[i]);
  3. And calling functions with sending ajax:

        $.each(arrayOfFn, function(index, value) {
    ).then(function() {

Repeat rows of a data.frame

A clean dplyr solution, taken from here

df <- tibble(x = 1:2, y = c("a", "b"))
df %>% slice(rep(1:n(), each = 2))

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

diff and then grep for the edit type you want.

diff -u A1 A2 | grep -E "^\+"

no module named urllib.parse (How should I install it?)

pip install -U websocket 

I just use this to fix my problem

jQuery validation plugin: accept only alphabetical characters?

Be careful,

jQuery.validator.addMethod("lettersonly", function(value, element) 
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please"); 

[a-z, " "] by adding the comma and quotation marks, you are allowing spaces, commas and quotation marks into the input box.

For spaces + text, just do this:

jQuery.validator.addMethod("lettersonly", function(value, element) 
return this.optional(element) || /^[a-z ]+$/i.test(value);
}, "Letters and spaces only please");

[a-z ] this allows spaces aswell as text only.


also the message "Letters and spaces only please" is not required, if you already have a message in messages:

        required: "Enter your first name",
        minlength: jQuery.format("Enter at least (2) characters"),
        maxlength:jQuery.format("First name too long more than (80) characters"),
        lettersonly:jQuery.format("letters only mate")


How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
    display: block;

Now you can set the scroll to the body of the table:

table tbody 
   overflow: auto;
   height: 100px;

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

    width: 72px;

You should also set a static width for <td>. This solves the issue of the unaligned columns.

    width: 72px;

Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:


I hope this is what you meant.



If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

Java 8: merge lists with stream API

Alternative: Stream.concat()


How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _

In case you have some more complex formula it will be handy

Remove quotes from String in Python

The easiest way is:

s = '"sajdkasjdsaasdasdasds"' 
import json
s = json.loads(s)

How to find nth occurrence of character in a string?

If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf, otherwise, here's an implementation:

public static int ordinalIndexOf(String str, String substr, int n) {
    int pos = str.indexOf(substr);
    while (--n > 0 && pos != -1)
        pos = str.indexOf(substr, pos + 1);
    return pos;

This post has been rewritten as an article here.

Beginner Python Practice?

You may want to take a look at Pyschools, the website has quite a lot of practice questions on Python Programming.

How to resolve "gpg: command not found" error during RVM installation?

On my clean macOS 10.15.7, I needed to brew link gnupg && brew unlink gnupg first and then used Ashish's answer to use gpg instead of gpg2. I also had to chown a few directories. before the un/link.

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

How can I measure the actual memory usage of an application or process?

ps -eo size,pid,user,command --sort -size | \
    awk '{ hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' |\
    cut -d "" -f2 | cut -d "-" -f1

Use this as root and you can get a clear output for memory usage by each process.


     0.00 Mb COMMAND 
  1288.57 Mb /usr/lib/firefox
   821.68 Mb /usr/lib/chromium/chromium 
   762.82 Mb /usr/lib/chromium/chromium 
   588.36 Mb /usr/sbin/mysqld 
   547.55 Mb /usr/lib/chromium/chromium 
   523.92 Mb /usr/lib/tracker/tracker
   476.59 Mb /usr/lib/chromium/chromium 
   446.41 Mb /usr/bin/gnome
   421.62 Mb /usr/sbin/libvirtd 
   405.11 Mb /usr/lib/chromium/chromium 
   302.60 Mb /usr/lib/chromium/chromium 
   291.46 Mb /usr/lib/chromium/chromium 
   284.56 Mb /usr/lib/chromium/chromium 
   238.93 Mb /usr/lib/tracker/tracker
   223.21 Mb /usr/lib/chromium/chromium 
   197.99 Mb /usr/lib/chromium/chromium 
   194.07 Mb conky 
   191.92 Mb /usr/lib/chromium/chromium 
   190.72 Mb /usr/bin/mongod 
   169.06 Mb /usr/lib/chromium/chromium 
   155.11 Mb /usr/bin/gnome
   136.02 Mb /usr/lib/chromium/chromium 
   125.98 Mb /usr/lib/chromium/chromium 
   103.98 Mb /usr/lib/chromium/chromium 
    93.22 Mb /usr/lib/tracker/tracker
    89.21 Mb /usr/lib/gnome
    80.61 Mb /usr/bin/gnome
    77.73 Mb /usr/lib/evolution/evolution
    76.09 Mb /usr/lib/evolution/evolution
    72.21 Mb /usr/lib/gnome
    69.40 Mb /usr/lib/evolution/evolution
    68.84 Mb nautilus
    68.08 Mb zeitgeist
    60.97 Mb /usr/lib/tracker/tracker
    59.65 Mb /usr/lib/evolution/evolution
    57.68 Mb apt
    55.23 Mb /usr/lib/gnome
    53.61 Mb /usr/lib/evolution/evolution
    53.07 Mb /usr/lib/gnome
    52.83 Mb /usr/lib/gnome
    51.02 Mb /usr/lib/udisks2/udisksd 
    50.77 Mb /usr/lib/evolution/evolution
    50.53 Mb /usr/lib/gnome
    50.45 Mb /usr/lib/gvfs/gvfs
    50.36 Mb /usr/lib/packagekit/packagekitd 
    50.14 Mb /usr/lib/gvfs/gvfs
    48.95 Mb /usr/bin/Xwayland :1024 
    46.21 Mb /usr/bin/gnome
    42.43 Mb /usr/bin/zeitgeist
    42.29 Mb /usr/lib/gnome
    41.97 Mb /usr/lib/gnome
    41.64 Mb /usr/lib/gvfs/gvfsd
    41.63 Mb /usr/lib/gvfs/gvfsd
    41.55 Mb /usr/lib/gvfs/gvfsd
    41.48 Mb /usr/lib/gvfs/gvfsd
    39.87 Mb /usr/bin/python /usr/bin/chrome
    37.45 Mb /usr/lib/xorg/Xorg vt2 
    36.62 Mb /usr/sbin/NetworkManager 
    35.63 Mb /usr/lib/caribou/caribou 
    34.79 Mb /usr/lib/tracker/tracker
    33.88 Mb /usr/sbin/ModemManager 
    33.77 Mb /usr/lib/gnome
    33.61 Mb /usr/lib/upower/upowerd 
    33.53 Mb /usr/sbin/gdm3 
    33.37 Mb /usr/lib/gvfs/gvfsd
    33.36 Mb /usr/lib/gvfs/gvfs
    33.23 Mb /usr/lib/gvfs/gvfs
    33.15 Mb /usr/lib/at
    33.15 Mb /usr/lib/at
    30.03 Mb /usr/lib/colord/colord 
    29.62 Mb /usr/lib/apt/methods/https 
    28.06 Mb /usr/lib/zeitgeist/zeitgeist
    27.29 Mb /usr/lib/policykit
    25.55 Mb /usr/lib/gvfs/gvfs
    25.55 Mb /usr/lib/gvfs/gvfs
    25.23 Mb /usr/lib/accountsservice/accounts
    25.18 Mb /usr/lib/gvfs/gvfsd 
    25.15 Mb /usr/lib/gvfs/gvfs
    25.15 Mb /usr/lib/gvfs/gvfs
    25.12 Mb /usr/lib/gvfs/gvfs
    25.10 Mb /usr/lib/gnome
    25.10 Mb /usr/lib/gnome
    25.07 Mb /usr/lib/gvfs/gvfsd 
    24.99 Mb /usr/lib/gvfs/gvfs
    23.26 Mb /usr/lib/chromium/chromium 
    22.09 Mb /usr/bin/pulseaudio 
    19.01 Mb /usr/bin/pulseaudio 
    18.62 Mb (sd
    18.46 Mb (sd
    18.30 Mb /sbin/init 
    18.17 Mb /usr/sbin/rsyslogd 
    17.50 Mb gdm
    17.42 Mb gdm
    17.09 Mb /usr/lib/dconf/dconf
    17.09 Mb /usr/lib/at
    17.06 Mb /usr/lib/gvfs/gvfsd
    16.98 Mb /usr/lib/at
    16.91 Mb /usr/lib/gdm3/gdm
    16.86 Mb /usr/lib/gvfs/gvfsd
    16.86 Mb /usr/lib/gdm3/gdm
    16.85 Mb /usr/lib/dconf/dconf
    16.85 Mb /usr/lib/dconf/dconf
    16.73 Mb /usr/lib/rtkit/rtkit
    16.69 Mb /lib/systemd/systemd
    13.13 Mb /usr/lib/chromium/chromium 
    13.13 Mb /usr/lib/chromium/chromium 
    10.92 Mb anydesk 
     8.54 Mb /sbin/lvmetad 
     7.43 Mb /usr/sbin/apache2 
     6.82 Mb /usr/sbin/apache2 
     6.77 Mb /usr/sbin/apache2 
     6.73 Mb /usr/sbin/apache2 
     6.66 Mb /usr/sbin/apache2 
     6.64 Mb /usr/sbin/apache2 
     6.63 Mb /usr/sbin/apache2 
     6.62 Mb /usr/sbin/apache2 
     6.51 Mb /usr/sbin/apache2 
     6.25 Mb /usr/sbin/apache2 
     6.22 Mb /usr/sbin/apache2 
     3.92 Mb bash 
     3.14 Mb bash 
     2.97 Mb bash 
     2.95 Mb bash 
     2.93 Mb bash 
     2.91 Mb bash 
     2.86 Mb bash 
     2.86 Mb bash 
     2.86 Mb bash 
     2.84 Mb bash 
     2.84 Mb bash 
     2.45 Mb /lib/systemd/systemd
     2.30 Mb (sd
     2.28 Mb /usr/bin/dbus
     1.84 Mb /usr/bin/dbus
     1.46 Mb ps 
     1.21 Mb openvpn hackthebox.ovpn 
     1.16 Mb /sbin/dhclient 
     1.16 Mb /sbin/dhclient 
     1.09 Mb /lib/systemd/systemd 
     0.98 Mb /sbin/mount.ntfs /dev/sda3 /media/n0bit4/Data 
     0.97 Mb /lib/systemd/systemd 
     0.96 Mb /lib/systemd/systemd 
     0.89 Mb /usr/sbin/smartd 
     0.77 Mb /usr/bin/dbus
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.76 Mb su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.75 Mb sudo su 
     0.74 Mb /usr/bin/dbus
     0.71 Mb /usr/lib/apt/methods/http 
     0.68 Mb /bin/bash /usr/bin/mysqld_safe 
     0.68 Mb /sbin/wpa_supplicant 
     0.66 Mb /usr/bin/dbus
     0.61 Mb /lib/systemd/systemd
     0.54 Mb /usr/bin/dbus
     0.46 Mb /usr/sbin/cron 
     0.45 Mb /usr/sbin/irqbalance 
     0.43 Mb logger 
     0.41 Mb awk { hr=$1/1024 ; printf("%13.2f Mb ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" } 
     0.40 Mb /usr/bin/ssh
     0.34 Mb /usr/lib/chromium/chrome
     0.32 Mb cut 
     0.32 Mb cut 
     0.00 Mb [kthreadd] 
     0.00 Mb [ksoftirqd/0] 
     0.00 Mb [kworker/0:0H] 
     0.00 Mb [rcu_sched] 
     0.00 Mb [rcu_bh] 
     0.00 Mb [migration/0] 
     0.00 Mb [lru
     0.00 Mb [watchdog/0] 
     0.00 Mb [cpuhp/0] 
     0.00 Mb [cpuhp/1] 
     0.00 Mb [watchdog/1] 
     0.00 Mb [migration/1] 
     0.00 Mb [ksoftirqd/1] 
     0.00 Mb [kworker/1:0H] 
     0.00 Mb [cpuhp/2] 
     0.00 Mb [watchdog/2] 
     0.00 Mb [migration/2] 
     0.00 Mb [ksoftirqd/2] 
     0.00 Mb [kworker/2:0H] 
     0.00 Mb [cpuhp/3] 
     0.00 Mb [watchdog/3] 
     0.00 Mb [migration/3] 
     0.00 Mb [ksoftirqd/3] 
     0.00 Mb [kworker/3:0H] 
     0.00 Mb [kdevtmpfs] 
     0.00 Mb [netns] 
     0.00 Mb [khungtaskd] 
     0.00 Mb [oom_reaper] 
     0.00 Mb [writeback] 
     0.00 Mb [kcompactd0] 
     0.00 Mb [ksmd] 
     0.00 Mb [khugepaged] 
     0.00 Mb [crypto] 
     0.00 Mb [kintegrityd] 
     0.00 Mb [bioset] 
     0.00 Mb [kblockd] 
     0.00 Mb [devfreq_wq] 
     0.00 Mb [watchdogd] 
     0.00 Mb [kswapd0] 
     0.00 Mb [vmstat] 
     0.00 Mb [kthrotld] 
     0.00 Mb [ipv6_addrconf] 
     0.00 Mb [acpi_thermal_pm] 
     0.00 Mb [ata_sff] 
     0.00 Mb [scsi_eh_0] 
     0.00 Mb [scsi_tmf_0] 
     0.00 Mb [scsi_eh_1] 
     0.00 Mb [scsi_tmf_1] 
     0.00 Mb [scsi_eh_2] 
     0.00 Mb [scsi_tmf_2] 
     0.00 Mb [scsi_eh_3] 
     0.00 Mb [scsi_tmf_3] 
     0.00 Mb [scsi_eh_4] 
     0.00 Mb [scsi_tmf_4] 
     0.00 Mb [scsi_eh_5] 
     0.00 Mb [scsi_tmf_5] 
     0.00 Mb [bioset] 
     0.00 Mb [kworker/1:1H] 
     0.00 Mb [kworker/3:1H] 
     0.00 Mb [kworker/0:1H] 
     0.00 Mb [kdmflush] 
     0.00 Mb [bioset] 
     0.00 Mb [kdmflush] 
     0.00 Mb [bioset] 
     0.00 Mb [jbd2/sda5
     0.00 Mb [ext4
     0.00 Mb [kworker/2:1H] 
     0.00 Mb [kauditd] 
     0.00 Mb [bioset] 
     0.00 Mb [drbd
     0.00 Mb [irq/27
     0.00 Mb [i915/signal:0] 
     0.00 Mb [i915/signal:1] 
     0.00 Mb [i915/signal:2] 
     0.00 Mb [ttm_swap] 
     0.00 Mb [cfg80211] 
     0.00 Mb [kworker/u17:0] 
     0.00 Mb [hci0] 
     0.00 Mb [hci0] 
     0.00 Mb [kworker/u17:1] 
     0.00 Mb [iprt
     0.00 Mb [iprt
     0.00 Mb [kworker/1:0] 
     0.00 Mb [kworker/3:0] 
     0.00 Mb [kworker/0:0] 
     0.00 Mb [kworker/2:0] 
     0.00 Mb [kworker/u16:0] 
     0.00 Mb [kworker/u16:2] 
     0.00 Mb [kworker/3:2] 
     0.00 Mb [kworker/2:1] 
     0.00 Mb [kworker/1:2] 
     0.00 Mb [kworker/0:2] 
     0.00 Mb [kworker/2:2] 
     0.00 Mb [kworker/0:1] 
     0.00 Mb [scsi_eh_6] 
     0.00 Mb [scsi_tmf_6] 
     0.00 Mb [usb
     0.00 Mb [bioset] 
     0.00 Mb [kworker/3:1] 
     0.00 Mb [kworker/u16:1] 

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:

apt-get update
apt-get install php5-suhosin

Now you can edit /etc/php5/conf.d/suhosin.ini and set:

suhosin.memory_limit = 1G

Then using ini_set will work in a script:

ini_set('memory_limit', '256M');

Spring MVC 4: "application/json" Content Type is not being set correctly

As other people have commented, because the return type of your method is String Spring won't feel need to do anything with the result.

If you change your signature so that the return type is something that needs marshalling, that should help:

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public Map<String, Object> bar() {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("test", "jsonRestExample");
    return map;

Using the Jersey client to do a POST operation

Also you can try this:

MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

Datatables: Cannot read property 'mData' of undefined

Having <thead> and <tbody> with the same numbers of <th> and <td> solved my problem.

Sending the bearer token with axios

The second parameter of is data (not config). config is the third parameter. Please see this for details:

Difference between staticmethod and classmethod

staticmethod has no access to attibutes of the object, of the class, or of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object).

classmethod has no access to attributes of the object. It however can access attributes of the class and of parent classes in the inheritance hierarchy. It can be called at the class directly (without creating an object). If called at the object then it is the same as normal method which doesn't access self.<attribute(s)> and accesses self.__class__.<attribute(s)> only.

Think we have a class with b=2, we will create an object and re-set this to b=4 in it. Staticmethod cannot access nothing from previous. Classmethod can access .b==2 only, via cls.b. Normal method can access both: .b==4 via self.b and .b==2 via self.__class__.b.

We could follow the KISS style (keep it simple, stupid): Don't use staticmethods and classmethods, don't use classes without instantiating them, access only the object's attributes self.attribute(s). There are languages where the OOP is implemented that way and I think it is not bad idea. :)

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;

How to modify values of JsonObject / JsonArray directly?

Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S

System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"

obj.addProperty("DebugLogId", "YYY");

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);

Android: java.lang.SecurityException: Permission Denial: start Intent

I was running into the same issue and wanted to avoid adding the intent filter as you described. After some digging, I found an xml attribute android:exported that you should add to the activity you would like to be called.

It is by default set to false if no intent filter added to your activity, but if you do have an intent filter it gets set to true.

here is the documentation

tl;dr: addandroid:exported="true" to your activity in your AndroidManifest.xml file and avoid adding the intent-filter :)

Change/Get check state of CheckBox

You need to retrieve the checkbox before using it.

Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.

For example:

function checkAddress()
    var chkBox = document.getElementById('checkAddress');
    if (chkBox.checked)
        // ..

And your HTML would then look like this:

<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>

(Also changed the onchange to onclick. Doesn't work quite well in IE :).

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Use a special character \b, which matches empty string at the beginning or at the end of a word:

print re.sub(r'\b[uU]\b', 'you', text)

spaces are not a reliable solution because there are also plenty of other punctuation marks, so an abstract character \b was invented to indicate a word's beginning or end.

How to add a delay for a 2 or 3 seconds


Or with using statements:


I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

Using a dictionary to count the items in a list

I always thought that for a task that trivial, I wouldn't want to import anything. But i may be wrong, depending on collections.Counter being faster or not.

items = "Whats the simpliest way to add the list items to a dictionary "

stats = {}
for i in items:
    if i in stats:
        stats[i] += 1
        stats[i] = 1

# bonus
for i in sorted(stats, key=stats.get):
    print("%d×'%s'" % (stats[i], i))

I think this may be preferable to using count(), because it will only go over the iterable once, whereas count may search the entire thing on every iteration. I used this method to parse many megabytes of statistical data and it always was reasonably fast.

submitting a form when a checkbox is checked

Yes, this is possible.

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
    <input type="submit" name="submit" value="Search" />

By adding onchange="document.getElementById('formName').submit()" to each checkbox, you'll submit any time a checkbox is changed.

If you're OK with jQuery, it's even easier (and unobtrusive):

    $("#formname").on("change", "input:checkbox", function(){

For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on() method.

Data truncation: Data too long for column 'logo' at row 1

Use data type LONGBLOB instead of BLOB in your database table.

Write-back vs Write-Through caching?

The benefit of write-through to main memory is that it simplifies the design of the computer system. With write-through, the main memory always has an up-to-date copy of the line. So when a read is done, main memory can always reply with the requested data.

If write-back is used, sometimes the up-to-date data is in a processor cache, and sometimes it is in main memory. If the data is in a processor cache, then that processor must stop main memory from replying to the read request, because the main memory might have a stale copy of the data. This is more complicated than write-through.

Also, write-through can simplify the cache coherency protocol because it doesn't need the Modify state. The Modify state records that the cache must write back the cache line before it invalidates or evicts the line. In write-through a cache line can always be invalidated without writing back since memory already has an up-to-date copy of the line.

One more thing - on a write-back architecture software that writes to memory-mapped I/O registers must take extra steps to make sure that writes are immediately sent out of the cache. Otherwise writes are not visible outside the core until the line is read by another processor or the line is evicted.

How to try convert a string to a Guid

new Guid(string)

You could also look at using a TypeConverter.

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

javascript : sending custom parameters with but its not working

You can use this but there remains a security issue

<script type="text/javascript">
function fnc1()
    var a=window.location.href;


<input type="button" onclick="fnc1()" />
<input type="text" id="atext"  />

How to clean up R memory (without the need to restart my PC)?

Maybe you can try to use the function gc(). A call of gc() causes a garbage collection to take place. It can be useful to call gc() after a large object has been removed, as this may prompt R to return memory to the operating system. gc() also return a summary of the occupy memory.

What causing this "Invalid length for a Base-64 char array"

Try this:

public string EncodeBase64(string data)
    string s = data.Trim().Replace(" ", "+");
    if (s.Length % 4 > 0)
        s = s.PadRight(s.Length + 4 - s.Length % 4, '=');
    return Encoding.UTF8.GetString(Convert.FromBase64String(s));

Difference between arguments and parameters in Java

In java, there are two types of parameters, implicit parameters and explicit parameters. Explicit parameters are the arguments passed into a method. The implicit parameter of a method is the instance that the method is called from. Arguments are simply one of the two types of parameters.

How to check a Long for null in java

If it is Long you can check if it's null unless you go for long (as primitive data types cant be null while Long instance is a object)

Long num; _x000D_
if(num == null) return;

For some context, you can also prefer using Optional with it to make it somehow beautiful for some use cases. Refer @RequestParam in Spring MVC handling optional parameters

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

Native Documents (in which I have an interest) makes a viewer (and editor) specifically for Word documents (both legacy binary .doc and modern docx formats). It does so without lossy conversion to HTML. Here's how to get started

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:



Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.





The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files


Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.


The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.


rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.


Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.


The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el


The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:


There is a rst mode for the Jed programmers editor.


gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.


Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).


Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.


The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.


PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.


The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.


NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.


Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.


TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.


Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.


PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)


here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:


MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.


MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.


Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.


rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.


Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services


An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks


WordPreSt reStructuredText plugin for WordPress. (PHP)


reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)


Pelican is a static blog generator that supports writing articles in ReST. (Python)


Hyde is a static website generator that supports ReST. (Python)


Acrylamid is a static blog generator that supports writing articles in ReST. (Python)


Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.


Yozuch is a static blog generator written in Python.


T-SQL substring - separating first and last name

validate last name is blank

(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    then  person.fullName 
    ELSE SUBSTRING(person.fullName, 1, CHARINDEX(' ', person.fullName)) end) as first_name,  
(CASE WHEN 0 = CHARINDEX(' ', person.fullName) 
    THEN ''  
    ELSE SUBSTRING(person.fullName,CHARINDEX(' ', person.fullName), LEN(person.fullName) )end) last_name

FROM person

How to initialize a private static const map in C++?

The C++11 standard introduced uniform initialization which makes this much simpler if your compiler supports it:

class myClass {
    static map<int,int> myMap;

map<int,int> myClass::myMap = {
   {1, 2},
   {3, 4},
   {5, 6}

See also this section from Professional C++, on unordered_maps.

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(

Javascript event handler with parameters

It is an old question but a common one. So let me add this one here.

With arrow function syntax you can achieve it more succinct way since it is lexically binded and can be chained.

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or keywords.

const event_handler = (event, arg) => console.log(event, arg);
el.addEventListener('click', (event) => event_handler(event, 'An argument'));

If you need to clean up the event listener:

// Let's use use good old function sytax
function event_handler(event, arg) {
  console.log(event, arg);

// Assign the listener callback to a variable
var doClick = (event) => event_handler(event, 'An argument'); 

el.addEventListener('click', doClick);

// Do some work...

// Then later in the code, clean up
el.removeEventListener('click', doClick);

Here is crazy one-liner:

// You can replace console.log with some other callback function
el.addEventListener('click', (event) => ((arg) => console.log(event, arg))('An argument'));

More docile version: More appropriate for any sane work.

el.addEventListener('click', (event) => ((arg) => {
  console.log(event, arg);
})('An argument'));

Amazon Interview Question: Design an OO parking lot

In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".

Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.

The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)

License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.

finding and replacing elements in a list

Try using a list comprehension and the ternary operator.

>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]

Counting null and non-null values in a single query

I created the table in postgres 10 and both of the following worked:

select count(*) from us


select count(a is null) from us

Pass entire form as data in jQuery Ajax function

serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.

Suppose that we have a form with this id : "myform".

the better solution is to make a FormData and send it:

    var myform = document.getElementById("myform");
    var fd = new FormData(myform );
        url: "example.php",
        data: fd,
        cache: false,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (dataofconfirm) {
            // do something with the result

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.


    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>


@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";

Spring URI Template Documentation

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

Reloading module giving NameError: name 'reload' is not defined

To expand on the previously written answers, if you want a single solution which will work across Python versions 2 and 3, you can use the following:

    reload  # Python 2.7
except NameError:
        from importlib import reload  # Python 3.4+
    except ImportError:
        from imp import reload  # Python 3.0 - 3.3

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

PHP Warning: Invalid argument supplied for foreach()

Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.

Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.

Basic, basic debugging.

Use curly braces to initialize a Set in Python

From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

ByRef argument type mismatch in Excel VBA

Something is wrong with that string try like this:

Worksheets(data_sheet).Range("C2").Value = ProcessString(CStr(last_name))

How can I install a local gem?

you can also use the full filename to your gem file:

gem install /full/path/to/your.gem

this works as well -- it's probably the easiest way

What is the most "pythonic" way to iterate over a list in chunks?

Since nobody's mentioned it yet here's a zip() solution:

>>> def chunker(iterable, chunksize):
...     return zip(*[iter(iterable)]*chunksize)

It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk if it isn't.


>>> s = '1234567890'
>>> chunker(s, 3)
[('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9')]
>>> chunker(s, 4)
[('1', '2', '3', '4'), ('5', '6', '7', '8')]
>>> chunker(s, 5)
[('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')]

Or using itertools.izip to return an iterator instead of a list:

>>> from itertools import izip
>>> def chunker(iterable, chunksize):
...     return izip(*[iter(iterable)]*chunksize)

Padding can be fixed using @??O?????'s answer:

>>> from itertools import chain, izip, repeat
>>> def chunker(iterable, chunksize, fillvalue=None):
...     it   = chain(iterable, repeat(fillvalue, chunksize-1))
...     args = [it] * chunksize
...     return izip(*args)

Ant if else condition?

The if attribute does not exist for <copy>. It should be applied to the <target>.

Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

<target name="prepare-copy" description="copy file based on condition"
    depends="prepare-copy-true, prepare-copy-false">

<target name="prepare-copy-true" description="copy file based on condition"
    <echo>Get file based on condition being true</echo>
    <copy file="${some.dir}/true" todir="." />

<target name="prepare-copy-false" description="copy file based on false condition" 
    <echo>Get file based on condition being false</echo>
    <copy file="${some.dir}/false" todir="." />

If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

increment date by one month

              $selectdata ="select fromd,tod  from register where username='$username'";

            $stdate=date('Y', strtotime($startdate));  

            $enddate=date('Y', strtotime($endate));  

            $years = range ($stdate,$enddate);
            echo '<select name="years" class="form-control">';
            echo '<option>SELECT</option>';
            foreach($years as $year)
              {   echo '<option value="'.$year.'"> '.$year.' </option>';  }
                echo '</select>'; ?>

Two submit buttons in one form

An even better solution consists of using button tags to submit the form:

    <button type="submit" name="action" value="update">Update</button>
    <button type="submit" name="action" value="delete">Delete</button>

The HTML inside the button (e.g. ..>Update<.. is what is seen by the user; because there is HTML provided, the value is not user-visible; it is only sent to server. This way there is no inconvenience with internationalization and multiple display languages (in the former solution, the label of the button is also the value sent to the server).

how to avoid extra blank page at end while printing?

You could maybe add

.print:last-child {
     page-break-after: auto;

so the last print element will not get the extra page break.

Do note that the :last-child selector is not supported in IE8, if you're targetting that wretch of a browser.

Selecting with complex criteria from pandas.DataFrame

And remember to use parenthesis!

Keep in mind that & operator takes a precedence over operators such as > or < etc. That is why

4 < 5 & 6 > 4

evaluates to False. Therefore if you're using pd.loc, you need to put brackets around your logical statements, otherwise you get an error. That's why do:

df.loc[(df['A'] > 10) & (df['B'] < 15)]

instead of

df.loc[df['A'] > 10 & df['B'] < 15]

which would result in

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

How to Apply Corner Radius to LinearLayout

try this, for Programmatically to set a background with radius to LinearLayout or any View.

 private Drawable getDrawableWithRadius() {

    GradientDrawable gradientDrawable   =   new GradientDrawable();
    gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
    return gradientDrawable;

LinearLayout layout = new LinearLayout(this);

Java Try and Catch IOException Problem

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);

   if(lines > 0) {
     // Do rest of program.

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I got this issue solved in the 'Windows' way. After checking all my settings, cleaning the solution and rebuilding it, I simply close the solution and reopened it. Then it worked, so VS probably didn't get rid of some stuff during cleaning. When logical solutions don't work, I usually turn to illogical (or seemingly illogical) ones. Windows doesn't let me down. :)

Change collations of all columns of all tables in SQL Server

I always prefer pure SQL so :

SELECT 'ALTER TABLE [' + l.schema_n + '].[' 
       + l.table_name + '] ALTER COLUMN [' 
       + l.column_name + '] ' + l.data_type + '(' 
       + Cast(l.new_max_length AS NVARCHAR(100)) 
       + ') COLLATE ' + l.dest_collation_name + ';', 
FROM   (SELECT Row_number() 
                 OVER ( 
                   ORDER BY c.column_id) AS row_id, 
               Schema_name(o.schema_id)  schema_n, 
               ta.NAME                   table_name, 
               c.NAME                    column_name, 
               t.NAME                    data_type, 
                 WHEN c.max_length = -1 
                       OR ( c.max_length > 4000 ) THEN 4000 
                 ELSE c.max_length 
               END                       new_max_length, 
               'French_CI_AS'            dest_collation_name 
        FROM   sys.columns c 
               INNER JOIN sys.tables ta 
                       ON c.object_id = ta.object_id 
               INNER JOIN sys.objects o 
                       ON c.object_id = o.object_id 
               JOIN sys.types t 
                 ON c.system_type_id = t.system_type_id 
               LEFT OUTER JOIN sys.index_columns ic 
                            ON ic.object_id = c.object_id 
                               AND ic.column_id = c.column_id 
               LEFT OUTER JOIN sys.indexes i 
                            ON ic.object_id = i.object_id 
                               AND ic.index_id = i.index_id 
        WHERE  1 = 1 
               AND c.collation_name = 'SQL_Latin1_General_CP1_CI_AS' 
       --'French_CI_AS'-- ALTER DONE YET OLD VALUE :'SQL_Latin1_General_CP1_CI_AS' 
       ) l 
ORDER  BY l.column_id;

default web page width - 1024px or 980px?

This is a bit of an open ended question since screen sizes are changing all the time and what might have been correct two years ago would likely be out of date now.

I use Twitter Bootstrap 3 at present and it uses a fluid grid system designed to work at sizes ranging from mobile/very small all the way up to the huge wide screen monitors that are now available.

Currently the upper default in BS3 is 1200px which translates to a container width of 1144px after taking account of margins and padding of the grids elements.

In my experience, modern designers are working to a width of around 1366px for desktop. All recent designs I've been given to implement have been 1366px.

Note also that you can customise the BS3 grid quite heavily. For example we will use a 32 column grid with 4px gutter in our sites/designs going forwards.

Ultimately the decision on page width needs to be made based on your website analytics and the screen sizes that your visitors typically use.

Complex numbers usage in python

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
>>> y=complex(3,4)
>>> print y
>>> z=x+y
>>> print x
>>> print z
>>> z=x*y
>>> print z
>>> z=x/y
>>> print z
>>> print x.conjugate()
>>> print x.imag
>>> print x.real
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y

Generate PDF from HTML using pdfMake in Angularjs

Okay, I figured this out.

  1. You will need html2canvas and pdfmake. You do NOT need to do any injection in your app.js to either, just include in your script tags

  2. On the div that you want to create the PDF of, add an ID name like below:

     <div id="exportthis">
  3. In your Angular controller use the id of the div in your call to html2canvas:

  4. change the canvas to an image using toDataURL()

  5. Then in your docDefinition for pdfmake assign the image to the content.

  6. The completed code in your controller will look like this:

           html2canvas(document.getElementById('exportthis'), {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    var docDefinition = {
                        content: [{
                            image: data,
                            width: 500,

I hope this helps someone else. Happy coding!

Simplest way to throw an error/exception with a custom message in Swift 2?

Check this cool version out. The idea is to implement both String and ErrorType protocols and use the error's rawValue.

enum UserValidationError: String, Error {
  case noFirstNameProvided = "Please insert your first name."
  case noLastNameProvided = "Please insert your last name."
  case noAgeProvided = "Please insert your age."
  case noEmailProvided = "Please insert your email."


do {
  try User.define(firstName,
                  lastName: lastName,
                  age: age,
                  email: email,
                  gender: gender,
                  location: location,
                  phone: phone)
catch let error as User.UserValidationError {

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library:


How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

How to loop through all elements of a form jQuery

What happens, if you do this way:-

$('#new_user_form input, #new_user_form select').each(function(key, value) {


What is the reason behind "non-static method cannot be referenced from a static context"?

The method you are trying to call is an instance-level method; you do not have an instance.

static methods belong to the class, non-static methods belong to instances of the class.

Using setImageDrawable dynamically to set image in an ImageView

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following


CSS fill remaining width

This can be achieved by wrapping the image and search bar in their own container and floating the image to the left with a specific width.

This takes the image out of the "flow" which means that any items rendered in normal flow will not adjust their positioning to take account of this.

To make the "in flow" searchBar appear correctly positioned to the right of the image you give it a left padding equal to the width of the image plus a gutter.

The effect is to make the image a fixed width while the rest of the container block is fluidly filled up by the search bar.

<div class="container">
  <img src="img/logo.png"/>
  <div id="searchBar">
    <input type="text" />

and the css

.container {
  width: 100%;

.container img {
  width: 50px;
  float: left;

.searchBar {
  padding-left: 60px;

jQuery multiple conditions within if statement


if (!(i == 'InvKey' || i == 'PostDate')) {


if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

How to create an alert message in jsp page after submit process is complete

So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.

In test.jsp

Create a javascript

<script type="text/javascript">
function alertName(){
alert("Form has been submitted");

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to

Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.

To do that i would highly recommendation to use session!

So what you want to do is in your servlet:

session.setAttribute("getAlert", "Yes");//Just initialize a random variable.

than in the test.jsp


 <script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
    if (Msg != "null") {
 function alertName(){
 alert("Form has been submitted");

and than at the bottom

<script type="text/javascript"> window.onload = alertName; </script>

So everytime you submit that form a session will be pass on! If session is not null the function will run!

Creating a JSON array in C#

new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}

Parsing JSON from XmlHttpRequest.responseJSON

Use nsIJSON if this is for a FF extension:

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");'GET', BITLY_CREATE_API + encodeURIComponent(url) + BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};

parseJSON: function(req, url) {
if (req.status == 200) {
  var jsonResponse = Components.classes[";1"]
  var bitlyUrl = jsonResponse.results[url].shortUrl;

For a webpage, just use JSON.parse instead of Components.classes[";1"].createInstance(Components.interfaces.nsIJSON.decode

How do I fix the indentation of selected lines in Visual Studio

I like Ctrl+K, Ctrl+D, which indents the whole document.

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

How can you detect the version of a browser?

I use this to get de Name and number (int) of the version of the actual browser:

function getInfoBrowser() {_x000D_
    var ua = navigator.userAgent, tem,_x000D_
    M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];_x000D_
    if (/trident/i.test(M[1])) {_x000D_
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];_x000D_
        return { name: 'Explorer', version: parseInt((tem[1] || '')) };_x000D_
    if (M[1] === 'Chrome') {_x000D_
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);_x000D_
        if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[1]) }; }_x000D_
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];_x000D_
    if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);_x000D_
    return {_x000D_
        name: M[0],_x000D_
        version: parseInt(M[1])_x000D_
function getBrowser(){_x000D_
  let info = getInfoBrowser();_x000D_
<script src=""></script>_x000D_
<input type="button" onclick="getBrowser();" value="Get Info Browser"/>_x000D_
Name: <span id="i-name"></span><br/>_x000D_
Version: <span id="i-version"></span>

This run in

Chrome ; Firefox ; Safari ; Internet Explorer (>= 9) ; Opera ; Edge

For me.

How do I improve ASP.NET MVC application performance?

One super easy thing to do is to think asynchronously when accessing the data you want for the page. Whether reading from a web service, file, data base or something else, use the async model as much as possible. While it won't necessarily help any one page be faster it will help your server perform better overall.

HTML Table different number of columns in different rows

On the realisation that you're unfamiliar with colspan, I presumed you're also unfamiliar with rowspan, so I thought I'd throw that in for free.

One important point to note, when using rowspan: the following tr elements must contain fewer td elements, because of the cells using rowspan in the previous row (or previous rows).

table {_x000D_
  border: 1px solid #000;_x000D_
  border-collapse: collapse;_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
      <th colspan="2">Column one and two</th>_x000D_
      <th>Column three</th>_x000D_
      <td rowspan="2" colspan="2">A large cell</td>_x000D_
      <td>a smaller cell</td>_x000D_
      <!-- note that this row only has _one_ td, since the preceding row_x000D_
                     takes up some of this row -->_x000D_
      <td>Another small cell</td>_x000D_

How can I create a blank/hardcoded column in a sql query?

The answers above are correct, and what I'd consider the "best" answers. But just to be as complete as possible, you can also do this directly in CF using queryAddColumn.


Again, it's more efficient to do it at the database level... but it's good to be aware of as many alternatives as possible (IMO, of course) :)

How to redirect output of an already running process


Dupx is a simple *nix utility to redirect standard output/input/error of an already running process.


I've often found myself in a situation where a process I started on a remote system via SSH takes much longer than I had anticipated. I need to break the SSH connection, but if I do so, the process will die if it tries to write something on stdout/error of a broken pipe. I wish I could suspend the process with ^Z and then do a

bg %1 >/tmp/stdout 2>/tmp/stderr 

Unfortunately this will not work (in shells I know).

Command CompileSwift failed with a nonzero exit code in Xcode 10

You're most likely not reading the entire error message. If you look above the "Command CompileSwift failed with a nonzero exit code" message you should find some specification like this:

enter image description here

In this example I had two files with the same name. Once I fixed it everything worked as it should.

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

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

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

Try this

Building executable jar with maven?

If you don't want execute assembly goal on package, you can use next command:

mvn package assembly:single

Here package is keyword.

MVC 4 client side validation not working

I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.

How do I rotate the Android emulator display?

For Mac you can use fn + Left control + F12.

How to force browser to download file?

This is from a php script which solves the problem perfectly with every browser I've tested (FF since 3.5, IE8+, Chrome)

header("Content-Disposition: attachment; filename=\"".$fname_local."\"");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fname));

So as far as I can see, you're doing everything correctly. Have you checked your browser settings?

Redis - Connect to Remote Server

Setting tcp-keepalive to 60 (it was set to 0) in server's redis configuration helped me resolve this issue.

How to make a query with group_concat in sql server

This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,

CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500) 

    DECLARE @SchoolName varchar(500)                        

    SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', ' 
    FROM maskdetails MD WITH (NOLOCK)       
    AND MD.MaskId=@MaskId

    RETURN @SchoolName


And then your final query will be like

SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on = m.schoolid 
ORDER BY m.maskname ;

Note: You may have to change the function, as I don't know the complete table structure.

How do I set up Vim autoindentation properly for editing Python files?

Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.

In vim type

:help vimrc

and check your path to the _vimrc/.vimrc file with

:echo $HOME

:echo $VIM

Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.

:help source

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

You could disable the warnings temporarily in places where they appear by using

#pragma warning(push)
#pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent
// deprecated code here
#pragma warning(pop)

so you don't disable all warnings, which can be harmful at times.

Convert LocalDate to LocalDateTime or java.sql.Timestamp

Depending on your timezone, you may lose a few minutes (1650-01-01 00:00:00 becomes 1649-12-31 23:52:58)

Use the following code to avoid that

new Timestamp(localDateTime.getYear() - 1900, localDateTime.getMonthOfYear() - 1, localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), fractional);

How to evaluate a math expression given in string form?

You can also try the BeanShell interpreter:

Interpreter interpreter = new Interpreter();
interpreter.eval("result = (7+21*6)/(32-27)");

Where can I set path to make.exe on Windows?

Or you can just run power-shell command to append extra folder to the existing path:

$env:Path += ";C:\temp\terraform" 

LINQ: Select an object and change some properties without creating a new object

We often run into this where we want to include a the index value and first and last indicators in a list without creating a new object. This allows you to know the position of the item in your list, enumeration, etc. without having to modify the existing class and then knowing whether you're at the first item in the list or the last.

foreach (Item item in this.Items
    .Select((x, i) => {
    x.ListIndex = i;
    x.IsFirst = i == 0;
    x.IsLast = i == this.Items.Count-1;
    return x;

You can simply extend any class by using:

public abstract class IteratorExtender {
    public int ListIndex { get; set; }
    public bool IsFirst { get; set; } 
    public bool IsLast { get; set; } 

public class Item : IteratorExtender {}

Looking to understand the iOS UIViewController lifecycle

There's a lot of outdated and incomplete information here. For iOS 6 and newer only:

  1. loadView[a]
  2. viewDidLoad[a]
  3. viewWillAppear
  4. viewWillLayoutSubviews is the first time bounds are finalized
  5. viewDidLayoutSubviews
  6. viewDidAppear
  7. * viewWillLayoutSubviews[b]
  8. * viewDidLayoutSubviews[b]


(a) - If you manually nil out your view during didReceiveMemoryWarning, loadView and viewDidLoad will be called again. That is, by default loadView and viewDidLoad only gets called once per view controller instance.

(b) May be called an additional 0 or more times.

What's the difference between UTF-8 and UTF-8 without BOM?

What's different between UTF-8 and UTF-8 without BOM?

Short answer: In UTF-8, a BOM is encoded as the bytes EF BB BF at the beginning of the file.

Long answer:

Originally, it was expected that Unicode would be encoded in UTF-16/UCS-2. The BOM was designed for this encoding form. When you have 2-byte code units, it's necessary to indicate which order those two bytes are in, and a common convention for doing this is to include the character U+FEFF as a "Byte Order Mark" at the beginning of the data. The character U+FFFE is permanently unassigned so that its presence can be used to detect the wrong byte order.

UTF-8 has the same byte order regardless of platform endianness, so a byte order mark isn't needed. However, it may occur (as the byte sequence EF BB FF) in data that was converted to UTF-8 from UTF-16, or as a "signature" to indicate that the data is UTF-8.

Which is better?

Without. As Martin Cote answered, the Unicode standard does not recommend it. It causes problems with non-BOM-aware software.

A better way to detect whether a file is UTF-8 is to perform a validity check. UTF-8 has strict rules about what byte sequences are valid, so the probability of a false positive is negligible. If a byte sequence looks like UTF-8, it probably is.

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.


The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

Please add a @Pipe/@Directive/@Component annotation. Error

If you are exporting another class in that module, make sure that it is not in between @Component and your ClassComponent. For example:

@Component({ ... })

export class ExampleClass{}

export class ComponentClass{}  --> this will give this error.


export class ExampleClass{}

@Component ({ ... })

export class ComponentClass{}

How do I block comment in Jupyter notebook?

Try using the / from the numeric keyboard. Ctrl + / in Chrome wasn't working for me, but when I used the /(division symbol) from the numeric it worked.