Programs & Examples On #Qlineedit

QLineEdit is a component of the Qt library which is basically a text editor that has only one line, and which allows one to make inputting and editing of text. A related class is QTextEdit which allows multi-line, rich text editing.

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()

        self.pb = QPushButton()

        layout = QFormLayout()

        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost

app = QApplication(sys.argv)
form = Form()

Set QLineEdit to accept only numbers

If you're using QT Creator 5.6 you can do that like this:

#include <QIntValidator>

ui->myLineEditName->setValidator( new QIntValidator);

I recomend you put that line after ui->setupUi(this);

I hope this helps.

Auto select file in Solution Explorer from its open tab

If you're using the ReSharper plugin, you can do that using the Shift + Alt + L shortcut or navigate via menu as shown.

Enter image description here

How to determine the longest increasing subsequence using dynamic programming?

Here is a Scala implementation of the O(n^2) algorithm:

object Solve {
  def longestIncrSubseq[T](xs: List[T])(implicit ord: Ordering[T]) = {
    xs.foldLeft(List[(Int, List[T])]()) {
      (sofar, x) =>
        if (sofar.isEmpty) List((1, List(x)))
        else {
          val resIfEndsAtCurr = (sofar, xs).zipped map {
            (tp, y) =>
              val len = tp._1
              val seq = tp._2
              if (ord.lteq(y, x)) {
                (len + 1, x :: seq) // reversely recorded to avoid O(n)
              } else {
                (1, List(x))
          sofar :+ resIfEndsAtCurr.maxBy(_._1)

  def main(args: Array[String]) = {
      0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)))

How to Detect Browser Window /Tab Close Event?

You can't detect it with javascript.

Only events that do detect page unloading/closing are window.onbeforeunload and window.unload. Neither of these events can tell you the way that you closed the page.

Check if SQL Connection is Open or Closed

This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {

if (_databaseConnection.State == ConnectionState.Closed) {

Why does find -exec mv {} ./target/ + not work?

no, the difference between + and \; should be reversed. + appends the files to the end of the exec command then runs the exec command and \; runs the command for each file.

The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+ should be find . -type f -iname '*.cpp' -exec mv {} ./test/ + no need to escape it or terminate the +

xargs I haven't used in a long time but I think works like +.

javascript regex : only english letters allowed

let res = /^[a-zA-Z]+$/.test('sfjd');

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

One line if statement not working

From what I know

3 one-liners

  1. a = 10 if <condition>


a = 10 if true # a = 10
b = 10 if false # b = nil
  1. a = 10 unless <condition>


a = 10 unless false # a = 10
b = 10 unless true # b = nil
  1. a = <condition> ? <a> : <b>


a = true ? 10 : 100 # a = 10
a = false ? 10 : 100 # a = 100

I hope it helps.

Can you hide the controls of a YouTube embed without enabling autoplay?

Autoplay works only with /v/ instead of /embed/, so change the src to:


Updating to latest version of CocoaPods?

Below are steps to update cocoapods :

  1. Open terminal (Shortcut : Press cmd + space tab to open Spotlight then text in terminal)
  2. Use command sudo gem install cocoapods. This will ask for system password due to security concern thereafter it installs gems

Screenshot 1

  1. Now, set up pod using pod setup command. This will setup cocoapods master repo.

Screenshot 2

  1. You can check the version of cocoapods using pod --version command.

Screenshot 3

Convert Date/Time for given Timezone - java

Understanding how computer time works is very important. With that said I agree that if an API is created to help you process computer time like real time then it should work in such a way that allows you to treat it like real time. For the most part this is the case but there are some major oversights which do need attention.

Anyway I digress!! If you have your UTC offset (better to work in UTC than GMT offsets) you can calculate the time in milliseconds and add that to your timestamp. Note that an SQL Timestamp may vary from a Java timestamp as the way the elapse from the epoch is calculated is not always the same - dependant on database technologies and also operating systems.

I would advise you to use System.currentTimeMillis() as your time stamps as these can be processed more consistently in java without worrying about converting SQL Timestamps to java Date objects etc.

To calculate your offset you can try something like this:

Long gmtTime =1317951113613L; // 2.32pm NZDT
Long timezoneAlteredTime = 0L;

if (offset != 0L) {
    int multiplier = (offset*60)*(60*1000);
    timezoneAlteredTime = gmtTime + multiplier;
} else {
    timezoneAlteredTime = gmtTime;

Calendar calendar = new GregorianCalendar();

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");


String newZealandTime = formatter.format(calendar.getTime());

I hope this is helpful!

Convert String (UTF-16) to UTF-8 in C#

If you want a UTF8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the followed:

public static string Utf16ToUtf8(string utf16String)
    * Every .NET string will store text with the UTF16 encoding, *
    * known as Encoding.Unicode. Other encodings may exist as    *
    * Byte-Array or incorrectly stored with the UTF16 encoding.  *
    *                                                            *
    * UTF8 = 1 bytes per char                                    *
    *    ["100" for the ansi 'd']                                *
    *    ["206" and "186" for the russian '?']                   *
    *                                                            *
    * UTF16 = 2 bytes per char                                   *
    *    ["100, 0" for the ansi 'd']                             *
    *    ["186, 3" for the russian '?']                          *
    *                                                            *
    * UTF8 inside UTF16                                          *
    *    ["100, 0" for the ansi 'd']                             *
    *    ["206, 0" and "186, 0" for the russian '?']             *
    *                                                            *
    * We can use the convert encoding function to convert an     *
    * UTF16 Byte-Array to an UTF8 Byte-Array. When we use UTF8   *
    * encoding to string method now, we will get a UTF16 string. *
    *                                                            *
    * So we imitate UTF16 by filling the second byte of a char   *
    * with a 0 byte (binary 0) while creating the string.        *

    // Storage for the UTF8 string
    string utf8String = String.Empty;

    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Fill UTF8 bytes inside UTF8 string
    for (int i = 0; i < utf8Bytes.Length; i++)
        // Because char always saves 2 bytes, fill char with 0
        byte[] utf8Container = new byte[2] { utf8Bytes[i], 0 };
        utf8String += BitConverter.ToChar(utf8Container, 0);

    // Return UTF8
    return utf8String;

In my case the DLL request is a UTF8 string too, but unfortunately the UTF8 string must be interpreted with UTF16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 has to be converted to the UTF16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf16ToUtf8(string utf16String)
    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Return UTF8 bytes as ANSI string
    return Encoding.Default.GetString(utf8Bytes);

Or the Native-Method:

private static extern Int32 WideCharToMultiByte(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPWStr)] String lpWideCharStr, Int32 cchWideChar, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpMultiByteStr, Int32 cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);

public static string Utf16ToUtf8(string utf16String)
    Int32 iNewDataLen = WideCharToMultiByte(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf16String, utf16String.Length, null, 0, IntPtr.Zero, IntPtr.Zero);
    if (iNewDataLen > 1)
        StringBuilder utf8String = new StringBuilder(iNewDataLen);
        WideCharToMultiByte(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf16String, -1, utf8String, utf8String.Capacity, IntPtr.Zero, IntPtr.Zero);

        return utf8String.ToString();
        return String.Empty;

If you need it the other way around, see Utf8ToUtf16. Hope I could be of help.

How do I get the last inserted ID of a MySQL table in PHP?

Use mysqli as mysql is depricating

$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* close connection */

What does "var" mean in C#?

Did you ever hated to write such variable initializers?

XmlSerializer xmlSerializer = new XmlSerialzer(typeof(int))

So, starting with C# 3.0, you can replace it with

var xmlSerializer = new XmlSerialzer(typeof(int))

One notice: Type is resolved during compilation, so no problems with performance. But Compiler should be able to detect type during build step, so code like var xmlSerializer; won't compile at all.

"Unable to find remote helper for 'https'" during git clone

CentOS Minimal usually install version 1.8 git by yum install gitcommand.

The best way is to build & install it from source code. Current version is 2.18.0.

  1. Download the source code from or curl -o git-2.18.0.tar.gz

  2. Unzip by tar -zxf git-2.18.0.tar.gz && cd git-2.18.0

  3. Install the dependency package by executing yum install autoconf curl-devel expat-devel gettext-devel openssl-devel perl-devel zlib-devel asciidoc xmlto openjade perl* texinfo

  4. Install docbook2X, it's not in the rpm repository. Download and install by

    $ curl -o docbook2X-0.8.8-17.el7.x86_64.rpm $ rpm -Uvh docbook2X-0.8.8-17.el7.x86_64.rpm

And make a unix link name:

ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi
  1. Compile and install, reference to

    $ make configure $ ./configure --prefix=/usr $ make all doc info $ sudo make install install-doc install-html install-info

  2. Reboot your server (If not, you may encounter Unable to find remote helper for 'https' error)

    $ reboot now

  3. Test:

    $ git clone $ cd v-labs $ touch test.txt $ git add . $ git commit -m "test git install" $ git push -u

UTF-8 problems while reading CSV file with fgetcsv

Try putting this into the top of your file (before any other output):


header('Content-Type: text/html; charset=UTF-8');


sequelize findAll sort order in nodejs

In sequelize you can easily add order by clauses.

exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        // Add order conditions here....
        order: [
            ['id', 'DESC'],
            ['name', 'ASC'],
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']

See how I've added the order array of objects?

order: [
      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order


You might have to order the objects once they've been recieved inside the .then() promise. Checkout this question about ordering an array of objects based on a custom order:

How do I sort an array of objects based on the ordering of another array?

Python function to convert seconds into minutes, hours, and days

def normalize_seconds(seconds: int) -> tuple:
    (days, remainder) = divmod(seconds, 86400)
    (hours, remainder) = divmod(remainder, 3600)
    (minutes, seconds) = divmod(remainder, 60)

    return namedtuple("_", ("days", "hours", "minutes", "seconds"))(days, hours, minutes, seconds)

How to make the 'cut' command treat same sequental delimiters as one?

With versions of cut I know of, no, this is not possible. cut is primarily useful for parsing files where the separator is not whitespace (for example /etc/passwd) and that have a fixed number of fields. Two separators in a row mean an empty field, and that goes for whitespace too.

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:


By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

|                      0 |                       0 |                   12345 |

But the keywords return their corresponding INT representation:

|    1 |     0 |

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Starting iPhone app development in Linux?

You will never get your app approved by Apple if it is not developed using Xcode. Never. And if you do hack the SDK to develop on Linux and Apple finds out, don't be surprised when you are served. I am a member of the ADC and the iPhone developer program. Trust, Apple is VERY serious about this.

Don't take the risk, Buy a Macbook or Mac mini (yes a mini can run Xcode - though slowly - boost the RAM if you go with the mini). Also, while I've seen OS X hacked to run on VMware I've never seen anyone running Xcode on VM. So good luck. And I'd check the EULA before you go through the trouble.

PS: After reading the above, yes I agree If you do hack the SDK and develop on Linux at least do the final packaging on a Mac. And submit it via a Mac. Apple doesn't run through the code line by line so i doubt they'd catch that. But man, that's a lot of if's and work. Be fun to do though. :)

Run JavaScript in Visual Studio Code

Follow these steps in VS code.[performed in windows os]

  1. Create new file

  2. Write javascript codes in it

  3. Save file as filename.js

  4. Go to Debugging menu

  5. Click on Start debugging

  6. or simply press F5

screenshot of starting debugging

screenshot of output of js code in terminal

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
    using (var httpClient = new HttpClient())
        using (var content = new FormUrlEncodedContent(postData))
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);


TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Calling functions in a DLL from C++

When the DLL was created an import lib is usually automatically created and you should use that linked in to your program along with header files to call it but if not then you can manually call windows functions like LoadLibrary and GetProcAddress to get it working.

Is there any "font smoothing" in Google Chrome?

I will say before all that this will not always works, i have tested this with sans-serif font and external fonts like open sans

Sometimes, when you use huge fonts, try to approximate to font-size:49px and upper


This is a header text with a size of 48px (font-size:48px; in the element that contains the text).

But, if you up the 48px to font-size:49px; (and 50px, 60px, 80px, etc...), something interesting happens


The text automatically get smooth, and seems really good

For another side...

If you are looking for small fonts, you can try this, but isn't very effective.

To the parent of the text, just apply the next css property: -webkit-backface-visibility: hidden;

You can transform something like this:

-webkit-backface-visibility: visible;

To this:

-webkit-backface-visibility: hidden;

(the font is Kreon)

Consider that when you are not putting that property, -webkit-backface-visibility: visible; is inherit

But be careful, that practice will not give always good results, if you see carefully, Chrome just make the text look a little bit blurry.

Another interesting fact:

-webkit-backface-visibility: hidden; will works too when you transform a text in Chrome (with the -webkit-transform property, that includes rotations, skews, etc)


Without -webkit-backface-visibility: hidden;


With -webkit-backface-visibility: hidden;

Well, I don't know why that practices works, but it does for me. Sorry for my weird english.

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

Test if remote TCP port is open from a shell script

With netcat you can check whether a port is open like this:

nc 80 < /dev/null

The return value of nc will be success if the TCP port was opened, and failure (typically the return code 1) if it could not make the TCP connection.

Some versions of nc will hang when you try this, because they do not close the sending half of their socket even after receiving the end-of-file from /dev/null. On my own Ubuntu laptop (18.04), the netcat-openbsd version of netcat that I have installed offers a workaround: the -N option is necessary to get an immediate result:

nc -N 80 < /dev/null

How to add AUTO_INCREMENT to an existing column?

I had existing data in the first column and they were 0's. First I made the first column nullable. Then I set the data for the column to null. Then I set the column as an index. Then I made it a primary key with auto incrementing turned on. This is where I used another persons answer above:

ALTER TABLE `table_name` CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;

This Added numbers to all the rows of this table starting at one. If I ran the above code first it wasn't working because all the values were 0's. And making it an index was also required before making it auto incrementing. Next I made the column a primary key.

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

How to get text with Selenium WebDriver in Python

You want just .text.

You can then verify it after you've got it, don't attempt to pass in what you expect it should have.

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("").getInputStream();
InputStream iStream = getConfigFile();

Java: Insert multiple rows into MySQL with PreparedStatement

we can be submit multiple updates together in JDBC to submit batch updates.

we can use Statement, PreparedStatement, and CallableStatement objects for bacth update with disable autocommit

addBatch() and executeBatch() functions are available with all statement objects to have BatchUpdate

here addBatch() method adds a set of statements or parameters to the current batch.

SQL Query to find the last day of the month

declare @date date=getdate()
declare @st_date date,@end_dt date
set @st_date=convert(varchar(5),year(@date))+'-'+convert(varchar(5),month(@date))+'-01'
set @end_dt=DATEADD(day,-1, DATEADD(month,1,@st_date))
select @st_date as [START DATE],@end_dt AS [END DATE]

How to detect if a stored procedure already exists

     -- Does Not Exists
     -- Exists

Remove all items from RecyclerView

On Xamarin.Android, It works for me and need change layout

 var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
 layout.SpanCount = GetItemPerRow(Context);
 recyclerView.SetAdapter(adapter); //reset

TSQL Pivot without aggregate function

Ok, sorry for the poor question. gbn got me on the right track. This is what I was looking for in an answer.

SELECT [FirstName], [MiddleName], [LastName], [Date] 
FROM #temp 
(   MIN([Data]) 
    FOR [DBColumnName] IN ([FirstName], [MiddleName], [LastName], [Date]) 
)AS p

Then I had to use a while statement and build the above statement as a varchar and use dynmaic sql.

Using something like this

SET @fullsql = @fullsql + 'SELECT ' + REPLACE(REPLACE(@fulltext,'(',''),')','')
SET @fullsql = @fullsql + 'FROM #temp '
SET @fullsql = @fullsql + 'PIVOT'
SET @fullsql = @fullsql + '('
SET @fullsql = @fullsql + ' MIN([Data])'
SET @fullsql = @fullsql + ' FOR [DBColumnName] IN '+@fulltext
SET @fullsql = @fullsql + ')'
SET @fullsql = @fullsql + 'AS p'

EXEC (@fullsql)

Having a to build @fulltext using a while loop and select the distinct column names out of the table. Thanks for the answers.

Enable SQL Server Broker taking too long

USE master;
USE Database_Name;

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:


aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 

aaron@ares ~/Downloads$ cd BeautifulSoup-

aaron@ares ~/Downloads/BeautifulSoup-$ sudo python install
running install
<... snip ...>

Laravel-5 'LIKE' equivalent (Eloquent)

If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.

Try this

BookingDates::where('email', Input::get('email'))
    ->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();

How to hide a div with jQuery?


will set the css display to none. if you need to set visibility to hidden as well, could do this via

$("#myDiv").css("visibility", "hidden");

or combine both in a chain

$("#myDiv").hide().css("visibility", "hidden");

or write everything with one css() function

  display: "none",
  visibility: "hidden"

How to decode viewstate


The parser should work with most non-encrypted ViewStates. It doesn’t handle the serialization format used by .NET version 1 because that version is sorely outdated and therefore too unlikely to be encountered in any real situation.

Parsing .NET ViewState

Read a plain text file with php

Try something like this:

$filename = 'file.txt';

$data = file($filename);
foreach ($data as $line_num=>$line)
    echo 'Line # <b>'.$line_num.'</b>:'.$line.'<br/>';

MVC 4 - Return error message from Controller - Show in View

If you want to do a redirect, you can either:

ViewBag.Error = "error message";


TempData["Error"] = "error message";

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

When should use Readonly and Get only properties

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

taken from Mark's example:

public class Fragrance : IFragrance
    private readonly string name;

    public Fragrance(string name)
        if (name == null)
            throw new ArgumentNullException("name");
        } = name;

    public string Spread()

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.

After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

Android open camera from button

For me this worked perfectly fine .

 Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

and add this permission to mainfest file:

<uses-permission android:name="android.permission.CAMERA">

It opens the camera,after capturing the image it saves the image to gallery with a new image set.

What is the difference between LATERAL and a subquery in PostgreSQL?

The difference between a non-lateral and a lateral join lies in whether you can look to the left hand table's row. For example:

select  *
from    table1 t1
cross join lateral
        select  *
        from    t2
        where   t1.col1 = t2.col1 -- Only allowed because of lateral
        ) sub

This "outward looking" means that the subquery has to be evaluated more than once. After all, t1.col1 can assume many values.

By contrast, the subquery after a non-lateral join can be evaluated once:

select  *
from    table1 t1
cross join
        select  *
        from    t2
        where   t2.col1 = 42 -- No reference to outer query
        ) sub

As is required without lateral, the inner query does not depend in any way on the outer query. A lateral query is an example of a correlated query, because of its relation with rows outside the query itself.

How to remove only 0 (Zero) values from column in excel 2010

I selected columns that I want to delete 0 values then clicked DATA > FILTER. In column's header there is a filter icon appears. I clicked on that icon and selected only 0 values and clicked OK. Only 0 values becomes selected. Finally clear content OR use DELETE button.

Then to remove the blank rows from the deleted 0 values removed. I click DATA > FILTER I clicked on that filter icon and unselected blanks copy and paste the remaining data into a new sheet.

Renaming files in a folder to sequential numbers

with "rename" command

rename -N 0001 -X 's/.*/$N/' *.jpg


rename -N 0001 's/.*/$N.jpg/' *.jpg

.ps1 cannot be loaded because the execution of scripts is disabled on this system

The problem is that the execution policy is set on a per user basis. You'll need to run the following command in your application every time you run it to enable it to work:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned

There probably is a way to set this for the ASP.NET user as well, but this way means that you're not opening up your whole system, just your application.


Redirect website after certain amount of time

The simplest way is using HTML META tag like this:

<meta http-equiv="refresh" content="3;url=" />


warning about too many open figures

This is also useful if you only want to temporarily suppress the warning:

import matplotlib.pyplot as plt
with plt.rc_context(rc={'figure.max_open_warning': 0}):

Vue.js img src concatenate variable and text

You can't use curlies (moustache tags) in attributes. Use the following to concat data:

<img v-bind:src="imgPreUrl + 'img/logo.png'">

Or the short version:

<img :src="imgPreUrl + 'img/logo.png'">

Read more on dynamic attributes in the Vue docs.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Here is a comparison with np.einsum to show how the indices are projected

np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b)        # True 
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b)        # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b),   # True

What is the difference between supervised learning and unsupervised learning?

Supervised learning can label a new item into one of the trained labels based on learning during training. You need to provide large numbers of training data set, validation data set and test data set. If you provide say pixel image vectors of digits along with training data with labels, then it can identify the numbers.

Unsupervised learning does not require training data-sets. In unsupervised learning it can group items into different clusters based on the difference in the input vectors. If you provide pixel image vectors of digits and ask it to classify into 10 categories, it may do that. But it does know how to labels it as you have not provided training labels.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

  1. As per, "DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed."

  2. Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status

SHA-1 fingerprint of keystore certificate

enter image description here

Right side Gradle --> signing project get all keys

How to convert an array to object in PHP?

You could also do this by adding (object) on left of variable to create a new object.

$a = Array
    ( 'status' => " text" );
$b = (object)$a;

How can I setup & run PhantomJS on Ubuntu?

I have found this simpler way - Phantom dependencies + Npm

sudo apt-get update
sudo apt-get install build-essential chrpath libssl-dev libxft-dev
sudo apt-get install libfreetype6 libfreetype6-dev
sudo apt-get install libfontconfig1 libfontconfig1-dev

and npm

[sudo] npm install -g phantomjs


Extension exists but uuid_generate_v4 fails

If the extension is already there but you don't see the uuid_generate_v4() function when you do a describe functions \df command then all you need to do is drop the extension and re-add it so that the functions are also added. Here is the issue replication:

db=# \df
                       List of functions
 Schema | Name | Result data type | Argument data types | Type
(0 rows)
ERROR:  extension "uuid-ossp" already exists
DROP EXTENSION "uuid-ossp";
db=# \df
                                  List of functions
 Schema |        Name        | Result data type |    Argument data types    |  Type
 public | uuid_generate_v1   | uuid             |                           | normal
 public | uuid_generate_v1mc | uuid             |                           | normal
 public | uuid_generate_v3   | uuid             | namespace uuid, name text | normal
 public | uuid_generate_v4   | uuid             |                           | normal

db=# select uuid_generate_v4();
(1 row)

What probably happened is that the extension was originally added to the cluster at some point in the past and then you probably created a new database within that cluster afterward. If that was the case then the new database will only be "aware" of the extension but it will not have the uuid functions added which happens when you add the extension. Therefore you must re-add it.

How to read numbers separated by space using scanf

I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3);

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3);

Get the client IP address using PHP

    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'] != '')
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if ($_SERVER['HTTP_X_FORWARDED_FOR'] != '')
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_X_FORWARDED'] != '')
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if ($_SERVER['HTTP_FORWARDED_FOR'] != '')
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_FORWARDED'] != '')
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if ($_SERVER['REMOTE_ADDR'] != '')
        $ipaddress = $_SERVER['REMOTE_ADDR'];
        $ipaddress = 'UNKNOWN';

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation:
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()


id: $("#id").val()

All together:

 <script src=""></script>
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },

How to check if a URL exists or returns 404 with Java?

this worked for me:

URL u = new URL ( "");
HttpURLConnection huc =  ( HttpURLConnection )  u.openConnection (); 
huc.setRequestMethod ("GET");  //OR  huc.setRequestMethod ("HEAD"); 
huc.connect () ; 
int code = huc.getResponseCode() ;

thanks for the suggestions above.

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

Static nested class in Java, why?

  1. JVM knows no nested classes. Nesting is just syntactic sugar.

    Below images shows Java file:

    enter image description here

    Below images show class files representation of the java file :

    enter image description here

    Notice that 2 class files are generated, one for parent and another for nested class.

  2. Non-static nested class' objects have access to the enclosing scope. That access to the enclosing scope is maintained by holding an implicit reference of the enclosing scope object in the nested object

  3. Nested class is a way to represent the intent that the nested class type represents a component of the parent class.

    public class Message {
    private MessageType messageType; // component of parent class
    public enum MessageType {
        SENT, RECEIVE;
    class Otherclass {
    public boolean isSent(Message message) {
        if (message.getMessageType() == MessageType.SENT) { // accessible at other places as well
            return true;
        return false;
  4. private static nested class represents Point#3 & the fact the nested type can only be the subcomponent to the parent class. It can't be used separately.

    public class Message {
     private Content content; // Component of message class
     private static class Content { // can only be a component of message class
      private String body;
      private int sentBy;
      public String getBody() {
         return body;
      public int getSentBy() {
         return sentBy;
    class Message2 {
      private Message.Content content; // Not possible
  5. More details here.

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
// or..
doAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
doAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
assertEquals("java", spy.get(0));

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy


strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

Razor MVC Populating Javascript array with Model Array

JSON syntax is pretty much the JavaScript syntax for coding your object. Therefore, in terms of conciseness and speed, your own answer is the best bet.

I use this approach when populating dropdown lists in my KnockoutJS model. E.g.

var desktopGrpViewModel = {
    availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
    desktopGrpComputeOfferingSelected: ko.observable(),


<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true" 
data-bind="options: availableComputeOffering,
           optionsText: 'Name',
           optionsValue: 'Id',
           value: desktopGrpComputeOfferingSelect,
           optionsCaption: 'Choose...'">

Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.


SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1

Change Spinner dropdown icon

We can manage it by hiding the icon as i did:

    <Spinner android:id="@+id/fragment_filter_sp_users"


How to load a text file into a Hive table stored as sequence files

You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.

Start with a tab delimited file:

% cat /tmp/input.txt
a       b
a2      b2

create a sequence file

hive> create table test_sq(k string, v string) stored as sequencefile;

try to load; as expected, this will fail:

hive> load data local inpath '/tmp/input.txt' into table test_sq;

But with this table:

hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;

The load works just fine:

hive> load data local inpath '/tmp/input.txt' into table test_t;
hive> select * from test_t;
a       b
a2      b2

Now load into the sequence table from the text table:

insert into table test_sq select * from test_t;

Can also do load/insert with overwrite to replace all.

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

How to display an alert box from C# in ASP.NET?

You can use Message box to show success message. This works great for me.

MessageBox.Show("Data inserted successfully");

Redirecting unauthorized controller in ASP.NET MVC

Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.

EDIT: I have a couple of blog posts that go into more detail:


    [AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
    public class MasterEventAuthorizationAttribute : AuthorizeAttribute
        /// <summary>
        /// The name of the master page or view to use when rendering the view on authorization failure.  Default
        /// is null, indicating to use the master page of the specified view.
        /// </summary>
        public virtual string MasterName { get; set; }

        /// <summary>
        /// The name of the view to render on authorization failure.  Default is "Error".
        /// </summary>
        public virtual string ViewName { get; set; }

        public MasterEventAuthorizationAttribute()
            : base()
            this.ViewName = "Error";

        protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
            validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );

        public override void OnAuthorization( AuthorizationContext filterContext )
            if (filterContext == null)
                throw new ArgumentNullException( "filterContext" );

            if (AuthorizeCore( filterContext.HttpContext ))
                SetCachePolicy( filterContext );
            else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                // auth failed, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();
            else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
                // is authenticated and is in the SuperUser role
                SetCachePolicy( filterContext );
                ViewDataDictionary viewData = new ViewDataDictionary();
                viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
                filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };


        protected void SetCachePolicy( AuthorizationContext filterContext )
            // ** IMPORTANT **
            // Since we're performing authorization at the action level, the authorization code runs
            // after the output caching module. In the worst case this could allow an authorized user
            // to cause the page to be cached, then an unauthorized user would later be served the
            // cached page. We work around this by telling proxies not to cache the sensitive page,
            // then we hook our custom authorization code into the caching mechanism so that we have
            // the final say on whether a page should be served from the cache.
            HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
            cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
            cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);


How to Count Duplicates in List with LINQ

The other solutions use GroupBy. GroupBy is slow (it holds all the elements in memory) so I wrote my own method CountBy:

public static Dictionary<TKey,int> CountBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
    var countsByKey = new Dictionary<TKey,int>();
    foreach(var x in source)
        var key = keySelector(x);
        if (!countsByKey.ContainsKey(key))
            countsByKey[key] = 0;
        countsByKey[key] += 1;
    return countsByKey;

How to determine equality for two JavaScript objects?

Pulling out from my personal library, which i use for my work repeatedly. The following function is a lenient recursive deep equal, which does not check

  • Class equality
  • Inherited values
  • Values strict equality

I mainly use this to check if i get equal replies against various API implementation. Where implementation difference (like string vs number) and additional null values, can occur.

Its implementation is quite straightforward and short (if all the comments is stripped off)

/** Recursively check if both objects are equal in value_x000D_
*** This function is designed to use multiple methods from most probable _x000D_
*** (and in most cases) valid, to the more regid and complex method._x000D_
*** One of the main principles behind the various check is that while_x000D_
*** some of the simpler checks such as == or JSON may cause false negatives,_x000D_
*** they do not cause false positives. As such they can be safely run first._x000D_
*** # !Important Note:_x000D_
*** as this function is designed for simplified deep equal checks it is not designed_x000D_
*** for the following_x000D_
*** - Class equality, (ClassA().a = 1) maybe valid to (ClassB().b = 1)_x000D_
*** - Inherited values, this actually ignores them_x000D_
*** - Values being strictly equal, "1" is equal to 1 (see the basic equality check on this)_x000D_
*** - Performance across all cases. This is designed for high performance on the_x000D_
***   most probable cases of == / JSON equality. Consider bench testing, if you have_x000D_
***   more 'complex' requirments_x000D_
*** @param  objA : First object to compare_x000D_
*** @param  objB : 2nd object to compare_x000D_
*** @param  .... : Any other objects to compare_x000D_
*** @returns true if all equals, or false if invalid_x000D_
*** @license Copyright by [email protected], 2012._x000D_
***          Licensed under the MIT license:
function simpleRecusiveDeepEqual(objA, objB) {_x000D_
 // Multiple comparision check_x000D_
 var args =;_x000D_
 if(args.length > 2) {_x000D_
  for(var a=1; a<args.length; ++a) {_x000D_
   if(!simpleRecusiveDeepEqual(args[a-1], args[a])) {_x000D_
    return false;_x000D_
  return true;_x000D_
 } else if(args.length < 2) {_x000D_
  throw "simpleRecusiveDeepEqual, requires atleast 2 arguments";_x000D_
 // basic equality check,_x000D_
 // if this succed the 2 basic values is equal,_x000D_
 // such as numbers and string._x000D_
 // or its actually the same object pointer. Bam_x000D_
 // Note that if string and number strictly equal is required_x000D_
 // change the equality from ==, to ===_x000D_
 if(objA == objB) {_x000D_
  return true;_x000D_
 // If a value is a bsic type, and failed above. This fails_x000D_
 var basicTypes = ["boolean", "number", "string"];_x000D_
 if( basicTypes.indexOf(typeof objA) >= 0 || basicTypes.indexOf(typeof objB) >= 0 ) {_x000D_
  return false;_x000D_
 // JSON equality check,_x000D_
 // this can fail, if the JSON stringify the objects in the wrong order_x000D_
 // for example the following may fail, due to different string order:_x000D_
 // JSON.stringify( {a:1, b:2} ) == JSON.stringify( {b:2, a:1} )_x000D_
 if(JSON.stringify(objA) == JSON.stringify(objB)) {_x000D_
  return true;_x000D_
 // Array equality check_x000D_
 // This is performed prior to iteration check,_x000D_
 // Without this check the following would have been considered valid_x000D_
 // simpleRecusiveDeepEqual( { 0:1963 }, [1963] );_x000D_
 // Note that u may remove this segment if this is what is intended_x000D_
 if( Array.isArray(objA) ) {_x000D_
  //objA is array, objB is not an array_x000D_
  if( !Array.isArray(objB) ) {_x000D_
   return false;_x000D_
 } else if( Array.isArray(objB) ) {_x000D_
  //objA is not array, objB is an array_x000D_
  return false;_x000D_
 // Nested values iteration_x000D_
 // Scan and iterate all the nested values, and check for non equal values recusively_x000D_
 // Note that this does not check against null equality, remove the various "!= null"_x000D_
 // if this is required_x000D_
 var i; //reuse var to iterate_x000D_
 // Check objA values against objB_x000D_
 for (i in objA) {_x000D_
  //Protect against inherited properties_x000D_
  if(objA.hasOwnProperty(i)) {_x000D_
   if(objB.hasOwnProperty(i)) {_x000D_
    // Check if deep equal is valid_x000D_
    if(!simpleRecusiveDeepEqual( objA[i], objB[i] )) {_x000D_
     return false;_x000D_
   } else if(objA[i] != null) {_x000D_
    //ignore null values in objA, that objB does not have_x000D_
    //else fails_x000D_
    return false;_x000D_
 // Check if objB has additional values, that objA do not, fail if so_x000D_
 for (i in objB) {_x000D_
  if(objB.hasOwnProperty(i)) {_x000D_
   if(objB[i] != null && !objA.hasOwnProperty(i)) {_x000D_
    //ignore null values in objB, that objA does not have_x000D_
    //else fails_x000D_
    return false;_x000D_
 // End of all checks_x000D_
 // By reaching here, all iteration scans have been done._x000D_
 // and should have returned false if it failed_x000D_
 return true;_x000D_
// Sanity checking of simpleRecusiveDeepEqual_x000D_
(function() {_x000D_
  // Basic checks_x000D_
  !simpleRecusiveDeepEqual({}, {}) ||_x000D_
  !simpleRecusiveDeepEqual([], []) ||_x000D_
  !simpleRecusiveDeepEqual(['a'], ['a']) ||_x000D_
  // Not strict checks_x000D_
  !simpleRecusiveDeepEqual("1", 1) ||_x000D_
  // Multiple objects check_x000D_
  !simpleRecusiveDeepEqual( { a:[1,2] }, { a:[1,2] }, { a:[1,2] } ) ||_x000D_
  // Ensure distinction between array and object (the following should fail)_x000D_
  simpleRecusiveDeepEqual( [1963], { 0:1963 } ) ||_x000D_
  // Null strict checks_x000D_
  simpleRecusiveDeepEqual( 0, null ) ||_x000D_
  simpleRecusiveDeepEqual( "", null ) ||_x000D_
  // Last "false" exists to make the various check above easy to comment in/out_x000D_
 ) {_x000D_
  alert("FATAL ERROR: simpleRecusiveDeepEqual failed basic checks");_x000D_
 } else { _x000D_
  //added this last line, for SO snippet alert on success_x000D_
  alert("simpleRecusiveDeepEqual: Passed all checks, Yays!");_x000D_

How to multiply all integers inside list

The most pythonic way would be to use a list comprehension:

l = [2*x for x in l]

If you need to do this for a large number of integers, use numpy arrays:

l = numpy.array(l, dtype=int)*2

A final alternative is to use map

l = list(map(lambda x:2*x, l))

How to limit the number of dropzone.js files uploaded?

I thought that the most intuitive single file upload process was to replace the previous file upon a new entry.

    url: '/cart?upload-engraving=true',
    maxFiles: 1,
    maxfilesexceeded: function(file) {

How do I declare an array with a custom class?

Your class:

class name {
    string first;
    string last;

  name() { }  //Default constructor.

  name(string a, string b){
    first = a;
    last = b;

Has an explicit constructor that requires two string parameters. Classes with no constructor written explicitly get default constructors taking no parameters. Adding the explicit one stopped the compiler from generating that default constructor for you.

So, if you wish to make an array of uninitialized objects, add a default constructor to your class so the compiler knows how to create them without providing those two string parameters - see the commented line above.

C# 'or' operator?

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

How to discard local changes and pull latest from GitHub repository

In addition to the above answers, there is always the scorched earth method.

rm -R <folder>

in Windows shell the command is:

rd /s <folder>

Then you can just checkout the project again:

git clone -v <repository URL> 

This will definitely remove any local changes and pull the latest from the remote repository. Be careful with rm -R as it will delete your good data if you put the wrong path. For instance, definitely do not do:

rm -R /

edit: To fix spelling and add emphasis.

phpmyadmin.pma_table_uiprefs doesn't exist

A really simple solution is to edit /etc/phpmyadmin/ and put

$cfg['Servers'][$i]['table_uiprefs'] = '';

It just manages the UI and who needs the UI if its interfering with display of actual data.


Android EditText view Floating Hint in Material Design

For an easier way to use the InputTextLayout, I have created this library that cuts your XML code to less than the half, and also provides you with the ability to set an error message as well as a hint message and an easy way to do your validations.

Simply add

compile 'com.github.TeleClinic:SmartEditText:0.1.0'

Then you can do something like this:

    app:setMandatoryErrorMsg="Mandatory field"
    app:setRegexErrorMsg="Wrong email format"
    app:setRegexType="EMAIL_VALIDATION" />

    app:setMandatoryErrorMsg="Mandatory field"
    app:setRegexErrorMsg="Weak password"
    app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />

    app:setRegexErrorMsg="Is that really your age :D?"
    app:setRegexString=".*\\d.*" />

Why do we use $rootScope.$broadcast in AngularJS?

What does $rootScope.$broadcast do?

It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)

Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .

refer for examples :-

How to create a GUID / UUID

UUID with timestamp built in (emitter/parser)
I will also post my simple approach to generating a valid UUID v4 with very strong uniqueness and fast runtime. The basic idea is not new, but approach is different. I use a timestamp in milliseconds from the (in Node.js library, which I'll point later, I use nanoseconds timestamp from process.hrtime.bigint()), and then add a random 5 digit number (10000-90000) to the end of the timestamp string. After merging the strings, I just form a valid UUID from digits and a pair of special characters, so that my UUID consists only of digits and a few non-numeric characters. Please check it out below:

 * uuid-timestamp (emitter)
 * UUID v4 based on timestamp
 * Created by tarkh
 * (C) 2020
const uuidEmit = () => {
  // Get now time
  const n =;
  // Generate random
  const r = Math.random();
  // Stringify now time and generate additional random number
  const s = String(n) + String(~~(r*9e4)+1e4);
  // Form UUID and return it
  return `${s.slice(0,8)}-${s.slice(8,12)}-4${s.slice(12,15)}-${[8,9,'a','b'][~~(r*3)]}${s.slice(15,18)}-${s.slice(s.length-12)}`;

// Generate 5 UUIDs

Looking at the results, you obviously see that the first part of UUIDs is the same, and then comes randomness. This is because I inserted the timestamp into the UUID linearly. The code will produce a new UUID every millisecond (nanosecond in Node.js library) + add a random 5-digit number to the end, so we end up with very approximate collision probability around 1 in 10 million per second. If we use Node.js library, our very approximate collision probability goes to 1 in 10 billion per second.

Timestamp built into the UUID
Since we insert a timestamp into the UUID linearly, we get a feature (good or bad - depends on the task) - ability to easily extract this timestamp back from the UUID. This way we can understand when UUID was released:

 * uuid-timestamp (parser)
 * UUID v4 based on timestamp
 * Created by tarkh
 * (C) 2020
const uuidParse = (uuid) => {
  // Get current timestamp string length
  let tl = String(;
  // Strip out timestamp from UUID
  let ts = '';
  let i = -1;
  while(tl--) {
    if(i===8||i===13||i===14||i===18||i===19||i===23) {
    ts += uuid[i];
  return Number(ts);

// Get the timestamp when UUID was emitted
const time = uuidParse('15970688-7109-4530-8114-887109530114');

// Covert timestamp to date and print it
console.log(new Date(time).toUTCString());

NPM version of my code above available as Node.js module. This version is even more powerful in generating unique values, because instead of millisecond timestamp it uses nanoseconds from combination of system time and process.hrtime.bigint() diff.

At the end of my post, I want to do some performance tests based on some of the answers from this topic. Of course, my decision is not the fastest, but it certainly takes the top positions.
Check jsBench here

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: '', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}

Or with the shortcut method:

$http.get('', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}

The list of the valid parameters is available in the $http service documentation.

Convert List<String> to List<Integer> directly

Using Java8:;

Difference between INNER JOIN and LEFT SEMI JOIN

An INNER JOIN can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):

FROM table_1 a
    SELECT * FROM table_2 b WHERE (

If there are multiple matching rows in the right-hand column, an INNER JOIN will return one row for each match on the right table, while a LEFT SEMI JOIN only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.

I am trying to get the names within table_1 that only appear in table_2.

Then a LEFT SEMI JOIN is the appropriate query to use.

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }

public class OtherClass {
    public void anotherMethod();

Web page and JavaScript code:

<applet id="app"
        code="MethodInvocation" ...>
<script language="javascript">
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You need to use dynamic SQL to achieve this; something like:

    TYPE cur_type IS REF CURSOR;

    CURSOR client_cur IS
        SELECT DISTING username
        FROM all_users
        WHERE length(username) = 3;

    emails_cur cur_type;
    l_cur_string VARCHAR2(128);
    l_email_id <type>;
    l_name <type>;
    FOR client IN client_cur LOOP
        dbms_output.put_line('Client is '|| client.username);
        l_cur_string := 'SELECT id, name FROM '
            || client.username || '.org';
        OPEN emails_cur FOR l_cur_string;
            FETCH emails_cur INTO l_email_id, l_name;
            EXIT WHEN emails_cur%NOTFOUND;
            dbms_output.put_line('Org id is ' || l_email_id
                || ' org name ' || l_name);
        END LOOP;
        CLOSE emails_cur;

Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR and an example. Edited to make the inner cursor query a string variable.

Why doesn't git recognize that my file has been changed, therefore git add not working

In my case, doing a git reset --hard deleted files & left some empty folders. After inspecting the content, I noticed the directories were empty.

However git ignores empty folders. (Correction, git ignores all directories as it tracks content, empty folders are not content.)

How to apply shell command to each line of a command output?

for s in `cmd`; do echo $s; done

If cmd has a large output:

cmd | xargs -L1 echo

Android "elevation" not showing a shadow

give some background color to layout worked for me like:


HTML input arrays

There are some references and pointers in the comments on this page at

Torsten says

"Section C.8 of the XHTML spec's compatability guidelines apply to the use of the name attribute as a fragment identifier. If you check the DTD you'll find that the 'name' attribute is still defined as CDATA for form elements."

Jetboy says

"according to this: the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document."

sort dict by value python

Sort the values:




How to stop asynctask thread in android?

You can't just kill asynctask immediately. In order it to stop you should first cancel it:


and than in asynctask's doInBackground() method check if it's already cancelled:


and if it is, stop executing it manually.

java.util.NoSuchElementException - Scanner reading user input

You need to remove the scanner closing lines: scan.close();

It happened to me before and that was the reason.

"date(): It is not safe to rely on the system's timezone settings..."

If you don't have access to the file php.ini, create or edit a .htaccess file in the root of your domain or sub and add this (generated by cpanel):

<IfModule mime_module>
AddType application/x-httpd-ea-php56 .php .php5 .phtml

<IfModule php5_module>
php_value date.timezone "America/New_York"

<IfModule lsapi_module>
php_value date.timezone "America/New_York"

CSS Equivalent of the "if" statement

I would argue that you can use if statements in CSS. Although they aren't worded as such. In the example below, I've said that if the check-box is checked I want the background changed to white. If you want to see a working example check out I built this for a client. Re size your window so that the mobile navigation takes over and click the nav button. All CSS. I think it's safe to say this concept could be used for many things.

     #sidebartoggler:checked + .page-wrap .hamb {
        background: #fff;

// example set as if statement sudo code.

if (sidebaretoggler is checked == true) {
set the background color of .hamb to white;

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Android button with different background colors

in Mono Android you can use filter like this:

your_button.Background.SetColorFilter(new Android.Graphics.PorterDuffColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.Multiply));

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;

    std::chrono::high_resolution_clock::time_point from;

int main (int argc, char* argv[])
  double total;
  Timer timer;

  total = 0.0;
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  return 0;

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

How can I make a CSS table fit the screen width?


table { 

Update with CSS from the comments:

td { 
    overflow: hidden; 
    text-overflow: ellipsis; 
    word-wrap: break-word;

For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):

@media only screen and (max-width: 480px) {
    /* horizontal scrollbar for tables if mobile screen */
    .tablemobile {
        overflow-x: auto;
        display: block;

Sufficient enough.

Xcode 6.1 Missing required architecture X86_64 in file

Here's a response to your latest question about the difference between x86_64 and arm64:

  • x86_64 architecture is required for running the 64bit simulator.

  • arm64 architecture is required for running the 64bit device (iPhone 5s, iPhone 6, iPhone 6 Plus, iPad Air, iPad mini with Retina display).

Using C++ base class constructors?

Yes, Since C++11:

struct B2 {
    B2(int = 13, int = 42);
struct D2 : B2 {
    using B2::B2;
// The set of inherited constructors is
// 1. B2(const B2&)
// 2. B2(B2&&)
// 3. B2(int = 13, int = 42)
// 4. B2(int = 13)
// 5. B2()

// D2 has the following constructors:
// 1. D2()
// 2. D2(const D2&)
// 3. D2(D2&&)
// 4. D2(int, int) <- inherited
// 5. D2(int) <- inherited

For additional information see

WampServer orange icon

Before you can fix anything you need to know which service has not started, Apache or MySQL.

As the TEST PORT 80 utility is saying Apache is running its probably the MySQL service that has not started. Unless you have another Apache running!

So which service has not started???

If the wampmanager icon is not GREEN then one of the services ( Apache/MySQL ) has not started properly.

How to tell which service is not running if the wampmanager icon is orange.

Left click the wampmanager icon to reveal the menu-> Apache -> Service If the Start/Resume service menu is Green then Apache IS NOT running.

Left click the wampmanager icon to reveal the menu-> MySQL -> Service If the Start/Resume service menu is Green then MySQL IS NOT running.

If Apache is the service that is not running it is normally, but not always, because something else has captured port 80.

Now do, Left click the wampmanager icon to reveal the menu-> Apache -> Service -> Test port 80 This will launch a command window and display some information about what, if anything is using port 80.

Whatever it is should be re-configured to not use port 80 or uninstalled if you are not using it.

If port 80 is not the problem look for errors in the appropriate error log ( use the wamp manager menus to view the error logs )

If these do not exists or show no errors then also check the Windows Event Viewer Start -> Administrative Tools -> Event Viewer And look in the 'Windows Logs' -> Application' section accessed from the menu on the left of the dialog for error messages from Apache and or MySQL.

If its MYSQL that has not started.

Check the mysql error log by using the menus

wampmanager->MySQL->error log

Check the Windows Event log for messages from MYSQL

Check you dont have another MYSQL Server instance running.

How to Configure SKYPE so it does not require port 80 or 443

Run SKYPE then using the menus do this: Tools -> Options -> Advanced -> Connection Un-Check the checkbox next to 'Use port 80 and 443 as alternatives for incomming connections' Now restart SKYPE for these changes to take effect.

If you are running Windows 8 SKYPE comes as an app and this cannot ( as yet ) be configured in this way. However if you uninstall the SKYPE app and install SKYPE in the old way, you can reconfigure it, and it works just as well.

How to set shadows in React Native for android?

Generating shadows for a circle, react native, android

Based on the answers here, and on text that I found in github (react-native-shadow), I made few tests and thought that some people may find the following helpful.

Here is how the screen looks like:

enter image description here


import React, { Component } from 'react';
import { View, TouchableHighlight, Text } from 'react-native';
import { BoxShadow } from 'react-native-shadow'

export default class ShadowsTest extends Component {

  render() {
    const shadowOpt = {
      width: 100,
      height: 100,
      color: "#000",
      border: 2,
      radius: 50,
      opacity: 0.8,
      x: 3,
      y: 3,
      //style: { marginVertical: 5 }

    return (
      <View style={{ flex: 1 }}>
          text={"Shadows Test"} />

        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
            <TouchableHighlight style={{
              position: 'relative',
              width: 100,
              height: 100,
              backgroundColor: "#fff",
              borderRadius: 50,
              borderWidth: 0.8,
              borderColor: '#000',
              // marginVertical:5,
              alignItems: 'center',
              justifyContent: 'center',
              overflow: "hidden" }}>
              <Text style={{ textAlign: 'center' }}>
                0: plain border

          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
            <BoxShadow setting={ shadowOpt }>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden" }}>
                <Text style={{ textAlign: 'center' }}>
                  1: RN shadow package

        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                shadowOffset: { width: 15, height: 15 },
                shadowColor: "black",
                shadowOpacity: 0.9,
                shadowRadius: 10,
                <Text style={{ textAlign: 'center' }}>
                  2: vanilla RN: shadow (may work on iOS)
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                elevation: 15,
                <Text style={{ textAlign: 'center' }}>
                  3: vanilla RN: elevation only (15)

        <View style={{ flexDirection: 'row', justifyContent: 'center', marginBottom: 30 }}>
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                elevation: 5,
                <Text style={{ textAlign: 'center' }}>
                  4: vanilla RN: elevation only (5)
          <View style={{ margin: 10, alignItems: 'center',
              justifyContent: 'center' }}>
              <TouchableHighlight style={{
                position: 'relative',
                width: 100,
                height: 100,
                backgroundColor: "#fff",
                borderRadius: 50,
                borderWidth: 1,
                borderColor: '#aaa',
                // marginVertical:5,
                alignItems: 'center',
                justifyContent: 'center',
                overflow: "hidden",
                elevation: 50,
                <Text style={{ textAlign: 'center' }}>
                  5: vanilla RN: elevation only (50)

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

What are the performance characteristics of sqlite with very large database files?

I have a 7GB SQLite database. To perform a particular query with an inner join takes 2.6s In order to speed this up I tried adding indexes. Depending on which index(es) I added, sometimes the query went down to 0.1s and sometimes it went UP to as much as 7s. I think the problem in my case was that if a column is highly duplicate then adding an index degrades performance :(

How to write log base(2) in c/c++

log2(x) = log10(x) / log10(2)

remove duplicates from sql union

If you are using T-SQL then it appears from previous posts that UNION removes duplicates. But if you are not, you could use distinct. This doesn't quite feel right to me either but it could get you the result you are looking for

select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4

Match everything except for specified strings

You don't need negative lookahead. There is working example:



  • [\s\S] - match any character
  • * - match from 0 to unlimited from previous group
  • ? - match as less as possible
  • (red|green|blue|) - match one of this words or nothing
  • g - repeat pattern



Will be:


Test it:

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

What online brokers offer APIs?

Ameritrade also offers an API, as long as you have an Ameritrade account:

Get the current URL with JavaScript?

  • Use window.location.href to get the complete URL.
  • Use window.location.pathname to get URL leaving the host.

How can I compare two dates in PHP?

You can convert the dates into UNIX timestamps and compare the difference between them in seconds.

$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
     echo "Enter a valid date";

How to get all elements inside "div" that starts with a known text

Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :

var elements = document.getElementById('parentContainer').children;

Option 2: Likely slowest :

var elements = document.getElementById('parentContainer').getElementsByTagName('*');

Option 3: Requires change to code (wrap a form instead of a div around it) :

// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;

var matches = [];

for (var i = 0; i < elements.length; i++)
    if (elements[i].value.indexOf('q17_') == 0)

Flushing footer to bottom of the page, twitter bootstrap

Here's a solution for the newest version of Bootstrap (4.3 at time of writing) using Flexbox.


<div class="wrapper">
  <div class="content">
    <p>Content goes here</p>
<footer class="footer"></footer>


html, body {
  height: 100%;

body {
  display: flex;
  flex-direction: column;

.wrapper {
  flex-grow: 1;

And a codepen example:

gradient descent using python and numpy

Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.

Data comes from a txt file with the following rows:

1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200

think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.

Here is the Octave implementation:

% Linear Regression with multiple variables

% Alpha for learning curve
alphaNum = 0.0005;

% Number of features
n = 2;

% Number of iterations for Gradient Descent algorithm
iterations = 10000

% No need to update after here


% Initial theta values
theta = ones(n + 1, 1);

% Number of training samples
m = length(DATA(:, 1));

% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
  X = [X, DATA(:,i)];

% Expected data must go always in the last column  
y = DATA(:, n + 1)

function gradientDescent(x, y, theta, alphaNum, iterations)
  iterations = [];
  costs = [];

  m = length(y);

  for iteration = 1:10000
    hypothesis = x * theta;

    loss = hypothesis - y;

    % J(theta)    
    cost = sum(loss.^2) / (2 * m);

    % Save for the graphic to see if the algorithm did work
    iterations = [iterations, iteration];
    costs = [costs, cost];

    gradient = (x' * loss) / m; % /m is for the average

    theta = theta - (alphaNum * gradient);

  % Show final theta values

  % Show J(theta) graphic evolution to check it worked, tendency must be zero
  plot(iterations, costs);


% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

Update multiple rows with different values in a single SQL query

I could not make @Clockwork-Muse work actually. But I could make this variation work:

WITH Tmp AS (SELECT * FROM (VALUES (id1, newsPosX1, newPosY1), 
                                   (id2, newsPosX2, newPosY2),
                                   ......................... ,
                                   (idN, newsPosXN, newPosYN)) d(id, px, py))


    posY = (SELECT py FROM Tmp WHERE =

FROM TableToUpdate t

I hope this works for you too!

Find and replace string values in list

An example with for loop (I prefer List Comprehensions).

a, b = '[br]', '<br />'
for i, v in enumerate(words):
    if a in v:
        words[i] = v.replace(a, b)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

        item.description as item_description, as party_name, 
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
    MyDerivedTable.RowNum BETWEEN 1 and 5 

Align two divs horizontally side by side center to the page using bootstrap css

Make sure you wrap your "row" inside the class "container" . Also add reference to bootstrap in your html.
Something like this should work:
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
     <p>lets learn!</p>
  <div class="container">
          <div class="row">
              <div class="col-lg-6" style="background-color: red;">
              <div class="col-lg-2" style="background-color: blue;">
              <div class="col-lg-4" style="background-color: green;">

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
>>> len((img,))

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see:

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    return rv;

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).

A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

How to use Git?

Have a look at git for designers for great one page article/high level intro to the topic. (That link is broken: Here is a link to another Git for Designers )

I would start at, there are documents and great video presentations for non-software-developer/cs users. Git for beginners have some basic stuff.

How to detect the swipe left or Right in Android?

here is generic swipe left detector for any view in kotlin using databinding

fun View.setOnSwipeLeft(runnable: Runnable) {
    setOnTouchListener(object : View.OnTouchListener {
        var x0 = 0F; var y0 = 0F; var t0 = 0L
        val defaultClickDuration = 200

        override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
            motionEvent?.let { event ->
                when(event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
                    MotionEvent.ACTION_UP -> {
                        val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()

                        if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
                            return false
                        if (x0 > x1) { }
                    else -> {}
            return true

and then to use it in your layout:

app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

There's a third-party service which provides a CORS-friendly REST API to perform DNS lookups from the browser -

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

SQL Error: ORA-00922: missing or invalid option

there's nothing wrong with using CHAR like that.. I think your problem is that you have a space in your tablename. It should be: charteredflight or chartered_flight..

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

A static method relates an action to a type of object, whereas the non static method relates an action to an instance of that type of object. Typically it is a method that does something with relation to the instance.


class Car might have a wash method, which would indicate washing a particular car, whereas a static method would apply to the type car.

Allow only pdf, doc, docx format for file upload?

Better to use change event on input field.

Updated source:

var myfile="";

$('#resume_link').click(function( e ) {

$('#resume').on( 'change', function() {
   myfile= $( this ).val();
   var ext = myfile.split('.').pop();
   if(ext=="pdf" || ext=="docx" || ext=="doc"){
   } else{

Updated jsFiddle.

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {

.error {
  color: #000;

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      <div class="input-container">
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>

How to update single value inside specific array item in redux

I'm afraid that using map() method of an array may be expensive since entire array is to be iterated. Instead, I combine a new array that consists of three parts:

  • head - items before the modified item
  • the modified item
  • tail - items after the modified item

Here the example I've used in my code (NgRx, yet the machanism is the same for other Redux implementations):

// toggle done property: true to false, or false to true

function (state, action) {
    const todos = state.todos;
    const todoIdx = todos.findIndex(t => ===;

    const todoObj = todos[todoIdx];
    const newTodoObj = { ...todoObj, done: !todoObj.done };

    const head = todos.slice(0, todoIdx - 1);
    const tail = todos.slice(todoIdx + 1);
    const newTodos = [...head, newTodoObj, ...tail];

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...

ClientAbortException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

DataTables: Cannot read property style of undefined

Make sure that in your input data, response[i] and response[i][j], are not undefined/null.

If so, replace them with "".

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

How to filter array in subdocument with MongoDB

Using aggregate is the right approach, but you need to $unwind the list array before applying the $match so that you can filter individual elements and then use $group to put it back together:

    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $unwind: '$list'},
    { $match: {'list.a': {$gt: 3}}},
    { $group: {_id: '$_id', list: {$push: '$list.a'}}}


  "result": [
      "_id": ObjectId("512e28984815cbfcb21646a7"),
      "list": [
  "ok": 1

MongoDB 3.2 Update

Starting with the 3.2 release, you can use the new $filter aggregation operator to do this more efficiently by only including the list elements you want during a $project:

    { $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
    { $project: {
        list: {$filter: {
            input: '$list',
            as: 'item',
            cond: {$gt: ['$$item.a', 3]}

How to draw a rectangle around a region of interest in python

please don't try with the old cv module, use cv2:

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)

x1,y1 ------
|          |
|          |
|          |

[edit] to append the follow-up questions below:


cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

Repeat command automatically in Linux

"watch" does not allow fractions of a second in Busybox, while "sleep" does. If that matters to you, try this:

while true; do ls -l; sleep .5; done

Manually Set Value for FormBuilder Control

  let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);

If you don't want manually set each field.

how I can show the sum of in a datagridview column?

//declare the total variable
int total = 0;
//loop through the datagrid and sum the column 
for(int i=0;i<datagridview1.Rows.Count;i++)
    total +=int.Parse(datagridview1.Rows[i].Cells["CELL NAME OR INDEX"].Value.ToString());

string tota

How do I concatenate strings?

I think that concat method and + should be mentioned here as well:

  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()

and there is also concat! macro but only for literals:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

Javascript : calling function from another file

Yes you can. Just check my fiddle for clarification. For demo purpose i kept the code in fiddle at same location. You can extract that code as shown in two different Javascript files and load them in html file.

 /******** PUT THIS CODE IN ONE JS FILE *******/

    var secondFileFuntion = function(){ = 'XYZ';

    secondFileFuntion.prototype.getSurname = function(){
     return 'ABC';

    var secondFileObject = new secondFileFuntion();

    /******** Till Here *******/

    /******** PUT THIS CODE IN SECOND JS FILE *******/

    function firstFileFunction(){
      var name =;
      var surname = secondFileObject.getSurname()
      alert(surname );


If you make an object using the constructor function and trying access the property or method from it in second file, it will give you the access of properties which are present in another file.

Just take care of sequence of including these files in index.html

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

Difference between string and StringBuilder in C#

System.String is a mutable object, meaning it cannot be modified after it’s been created. Please refer to Difference between string and StringBuilder in C#? for better understanding.

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

Parsing JSON object in PHP using json_decode

When you json decode , force it to return an array instead of object.

$data = json_decode($json, TRUE); -> // TRUE

This will return an array and you can access the values by giving the keys.

Problems with jQuery getJSON using local files in Chrome

You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.

How does inline Javascript (in HTML) work?

You've got it nearly correct, but you haven't accounted for the this value supplied to the inline code.

<a href="#" onclick="alert(this)">Click Me</a>

is actually closer to:

<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
    (function(event) {
    }).call(document.getElementById('click_me'), event);

Inline event handlers set this equal to the target of the event. You can also use anonymous function in inline script

<a href="#" onclick="(function(){alert(this);})()">Click Me</a>

What is a regular expression for a MAC Address?

Be warned that the Unicode property \p{xdigit} includes the FULLWIDTH versions. You might prefer \p{ASCII_Hex_Digit} instead.

The answer to the question asked might be best answered — provided you have a certain venerable CPAN module installed — by typing:

% perl -MRegexp::Common -lE 'say $RE{net}{MAC}'

I show the particular pattern it outputs here as lucky pattern number 13; there are many others.

This program:

#!/usr/bin/env perl
use 5.010;
use strict;
use warnings qw<FATAL all>;

my $mac_rx = qr{
    ^ (?&MAC_addr) $
                (?&pair) (?<it>  (?&either) )
            (?: (?&pair) \k<it> ) {4}
        (?<pair>    [0-9a-f] {2} )
        (?<either>  [:\-]        )

while (<DATA>) {
    printf("%-25s %s\n", $_ => /$mac_rx/ ? "ok" : "not ok");


generates this output:

3D:F2:C9:A6:B3:4F         ok
3D:F2:AC9:A6:B3:4F        not ok
3D:F2:C9:A6:B3:4F:00      not ok
:F2:C9:A6:B3:4F           not ok
F2:C9:A6:B3:4F            not ok
3d:f2:c9:a6:b3:4f         ok
3D-F2-C9-A6-B3-4F         ok
3D-F2:C9-A6:B3-4F         not ok

Which seems the sort of thing you're looking for.

Parse Json string in C#

I'm using in my project and it works great. In you case, you can do this to parse your json:

EDIT: I changed the code so it supports reading your json file (array)

Code to parse:

void Main()
    var json = System.IO.File.ReadAllText(@"d:\test.json");

    var objects = JArray.Parse(json); // parse as array  
    foreach(JObject root in objects)
        foreach(KeyValuePair<String, JToken> app in root)
            var appName = app.Key;
            var description = (String)app.Value["Description"];
            var value = (String)app.Value["Value"];



Lorem ipsum dolor sit amet

consectetur adipisicing elit

sed do eiusmod tempor incididunt ut labore et dolore magna aliqua

Ut enim ad minim veniam

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat

BTW, you can use LinqPad to test your code, easier than creating a solution or project in Visual Studio I think.

How do I compare two hashes?

what about convert both hash to_json and compare as string? but keeping in mind that

require "json"
h1 = {a: 20}
h2 = {a: "20"}

=> true
=> false

Python Requests and persistent sessions

The documentation says that get takes in an optional cookies argument allowing you to specify cookies to use:

from the docs:

>>> url = ''
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

How to see my Eclipse version?

Open .eclipseproduct in the product installation folder. Or open Configuration\config.ini and check property eclipse.buildId if exist.

How can I catch all the exceptions that will be thrown through reading and writing a file?

You may catch multiple exceptions in single catch block.

  // somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
  // handle exception.

SVG drop shadow using css3

Probably an evolution, it appears that inline css filters works nicely on elements, in a certain way.

Declaring a drop-shadow css filter, in an svg element, in both a class or inline does NOT works, as specified earlier.

But, at least in Firefox, with the following wizardry:

Appending the filter declaration inline, with javascript, after DOM load.

// Does not works, with regular dynamic css styling:

shadow0.oninput = () => { = "filter:drop-shadow(0 0 " + shadow0.value + "rem black);"

// Okay! Inline styling, appending.

shadow1.oninput = () => { += " ;filter:drop-shadow(0 0 " + shadow1.value + "rem black);" += " ;filter:drop-shadow(0 0 " + shadow1.value + "rem black);"
<h2>Firefox only</h2>
Does not works! 
<input id="shadow0" type="number" min="0" max="100" step="0.1">

 | Okay!
<input id="shadow1" type="number" min="0" max="100" step="0.1">

<svg viewBox="0 0 120 70">  
    <rect id="rect1" x="10" y="10" width="100" height="50" fill="#c66" />
    <!-- Inline style declaration does NOT works at svg level, no shadow at loading: -->
    <rect id="rect2" x="40" y="30" width="10" height="10" fill="#aaa" style="filter:drop-shadow(0 0 20rem black)" />

enter image description here

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    enumerable: false

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    enumerable: false

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

ImportError: No module named PyQt4.QtCore

I got the same error, when I was trying to import matplotlib.pyplot

In [1]: import matplotlib.pyplot as plt
ImportError: No module named PyQt4.QtCore

But in my case the problem was due to a missing linux library

OS : Cent OS 64 bit

Python version : 3.5.2

$> locate

If this command returns a value, your problem could be different, so please ignore my answer. If it does not return any value and your environment is same as mine, below steps would fix your problem.

$> yum install mesa-libGL.x86_64

This installs the necessary OpenGL libraries for 64 bit Cent OS.

$> locate

Now go back to iPython and try to import

In [1]: import matplotlib.pyplot as plt

This time it imported successfully.

Oracle client and networking components were not found

Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.

Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec executable, SSIS will not be able to find the Oracle client. The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.

How to check if multiple array keys exists

This is old and will probably get buried, but this is my attempt.

I had an issue similar to @Ryan. In some cases, I needed to only check if at least 1 key was in an array, and in some cases, all needed to be present.

So I wrote this function:

 * A key check of an array of keys
 * @param array $keys_to_check An array of keys to check
 * @param array $array_to_check The array to check against
 * @param bool $strict Checks that all $keys_to_check are in $array_to_check | Default: false
 * @return bool
function array_keys_exist(array $keys_to_check, array $array_to_check, $strict = false) {
    // Results to pass back //
    $results = false;

    // If all keys are expected //
    if ($strict) {
        // Strict check //

        // Keys to check count //
        $ktc = count($keys_to_check);
        // Array to check count //
        $atc = count(array_intersect($keys_to_check, array_keys($array_to_check)));

        // Compare all //
        if ($ktc === $atc) {
            $results = true;
    } else {
        // Loose check - to see if some keys exist //

        // Loop through all keys to check //
        foreach ($keys_to_check as $ktc) {
            // Check if key exists in array to check //
            if (array_key_exists($ktc, $array_to_check)) {
                $results = true;
                // We found at least one, break loop //

    return $results;

This was a lot easier than having to write multiple || and && blocks.

In which conda environment is Jupyter executing?

I have tried every method mentioned above and nothing worked, except installing jupyter in the new environment.

to activate the new environment conda activate new_env replace 'new_env' with your environment name.

next install jupyter 'pip install jupyter'

you can also install jupyter by going to anaconda navigator and selecting the right environment, and installing jupyter notebook from Home tab

Create HTTP post request and receive response using C# console application

Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.

Also microsoft recommends to use the HttpClient on this article

An example could look like this:

var client = new HttpClient();
var content = new MultipartFormDataContent
     { new StringContent("myUserId"), "userid"},
     { new StringContent("myFileName"), "filename"},
     { new StringContent("myPassword"), "password"},
     { new StringContent("myType"), "type"}

var responseMessage = await client.PostAsync("some url", content);        
var stream = await responseMessage.Content.ReadAsStreamAsync();

Can I set the height of a div based on a percentage-based width?

This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box CSS attribute:

div {_x000D_
  border: 1px solid red;_x000D_
  width: 40%;_x000D_
  padding: 40%;_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
p {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  <p>Some unnecessary content.</p>_x000D_

Adjust percentages to your liking. Here is a JSFiddle

Use CASE statement to check if column exists in table - SQL Server

Try this one -

FROM ...
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND = 'ModifiedByUser'

How do I put an already-running process under nohup?

Suppose for some reason Ctrl+Z is also not working, go to another terminal, find the process id (using ps) and run:


SIGSTOP will suspend the process and SIGCONT will resume the process, in background. So now, closing both your terminals won't stop your process.

How to install numpy on windows using pip install?

I had the same problem. I decided in a very unexpected way. Just opened the command line as an administrator. And then typed:

pip install numpy

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true

// false

Create a new Ruby on Rails application using MySQL instead of SQLite

If you already have a rails project, change the adapter in the config/database.yml file to mysql and make sure you specify a valid username and password, and optionally, a socket:

  adapter: mysql2
  database: db_name_dev
  username: koploper
  host: localhost
  socket: /tmp/mysql.sock

Next, make sure you edit your Gemfile to include the mysql2 or activerecord-jdbcmysql-adapter (if using jruby).

What does "wrong number of arguments (1 for 0)" mean in Ruby?

You passed an argument to a function which didn't take any. For example:

def takes_no_arguments

takes_no_arguments 1
# ArgumentError: wrong number of arguments (1 for 0)

Uncaught TypeError: Cannot set property 'onclick' of null

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.

Split string in C every white space

malloc(0) may (optionally) return NULL, depending on the implementation. Do you realize why you may be calling malloc(0)? Or more precisely, do you see where you are reading and writing beyond the size of your arrays?

How to get the range of occupied cells in excel sheet

See the Range.SpecialCells method. For example, to get cells with constant values or formulas use:

        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |

How do I run a spring boot executable jar in a Production environment?

Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.

For Maven, just include the following in your pom.xml:


For Gradle add the following snippet to your build.gradle:

springBoot {
    executable = true

The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d or use a systemd script.

init.d example:

$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp

This allows you to start, stop and restart your application like:

$/etc/init.d/yourapp start|stop|restart

Or use a systemd script:




More information at the following links:

Upload files with FTP using PowerShell

There are some other ways too. I have used the following script:

$File = "D:\Dev\";
$ftp = "ftp://username:[email protected]/pub/incoming/";

Write-Host -Object "ftp url: $ftp";

$webclient = New-Object -TypeName System.Net.WebClient;
$uri = New-Object -TypeName System.Uri -ArgumentList $ftp;

Write-Host -Object "Uploading $File...";

$webclient.UploadFile($uri, $File);

And you could run a script against the windows FTP command line utility using the following command

ftp -s:script.txt 

(Check out this article)

The following question on SO also answers this: How to script FTP upload and download?

Best way to do multi-row insert in Oracle?

In my case, I was able to use a simple insert statement to bulk insert many rows into TABLE_A using just one column from TABLE_B and getting the other data elsewhere (sequence and a hardcoded value) :

INSERT INTO table_a (
        table_b b;


1, JOHN, 123
2, SAM, 123
3, JESS, 123


How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
         XmlDocument xmlDocument = new XmlDocument();
         return xmlDocument;

        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    catch (Exception ex)
        throw ex;


Unable to Resolve Module in React Native App

This is my project directory structure

enter image description here

And i use the import like this

enter image description here

And it is working do not forget to add dot before slash for example './src/container/home/profile/index'

Timer function to provide time in nano seconds using C++

plf::nanotimer is a lightweight option for this, works in Windows, Linux, Mac and BSD etc. Has ~microsecond accuracy depending on OS:

  #include "plf_nanotimer.h"
  #include <iostream>

  int main(int argc, char** argv)
      plf::nanotimer timer;


      // Do something here

      double results = timer.get_elapsed_ns();
      std::cout << "Timing: " << results << " nanoseconds." << std::endl;    
      return 0;

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

"column not allowed here" error in INSERT statement

What you missed is " " in postcode because it is a varchar.

There are two ways of inserting.

When you created a table Table created. and you add a row just after creating it, you can use the following method.

INSERT INTO table_name
VALUES (value1,value2,value3,...);

1 row created.

You've added so many tables, or it is saved and you are reopening it, you need to mention the table's column name too or else it will display the same error.

ERROR at line 2:
ORA-00984: column not allowed here

INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

1 row created.

How to change scroll bar position with CSS?

Using CSS only:

Right/Left Flippiing: Working Fiddle

    height: 200px;
    overflow-x: auto;
    height: 300px;

    direction: rtl;
    direction: ltr;

Top/Bottom Flipping: Working Fiddle

    width: 200px;
    overflow-y: auto;
    width: 300px;

.Flipped, .Flipped .Content
    -ms-transform:rotateX(180deg); /* IE 9 */
    -webkit-transform:rotateX(180deg); /* Safari and Chrome */

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

Letter Count on a string

A simple way is as follows:

def count_letters(word, char):
    return word.count(char)

Or, there's another way count each element directly:

from collections import Counter

Of course, you can specify one element, e.g.


Visual Studio Code Tab Key does not insert a tab

Click "Tab Moves Focus" at the bottom right in the status bar.

I believe I had clicked on ctrl+M. When doing this, the "Tab Moves Focus" tab/button showed up at the bottom right. Clicking on that makes it go away and starts working again.

enter image description here

How to do URL decoding in Java?

public String decodeString(String URL)

    String urlString="";
    try {
        urlString = URLDecoder.decode(URL,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block


        return urlString;


How do I get rid of the "cannot empty the clipboard" error?

Good answers by Paul Simon and Steve Homer, I shut down team viewer and that did the trick. Skype or other programs may trigger the same glitch, but in this instance, I recalled the problem occurred when I tried to cut n paste a 2MB file from remote system through windows right click rather than using "File Transfer function in TV. An error message appeared, then the problem with Excel "'Cannot empty clipboard' message.

This problem occurs when you are working on a remote system. After copying and pasting a huge amount of data it shows the error. I have found the solution to this problem.

Go to remote systems task manager and perform the following task

Go to Task Manager > Processes Look for "rdpclip.exe" End that process

Your problem will be solved.

Youtube - downloading a playlist - youtube-dl

I have tried everything above, but none could solve my problem. I fixed it by updating the old version of youtube-dl to download playlist. To update it

sudo youtube-dl -U


youtube-dl -U

after you have successfully updated using the above command

youtube-dl -cit