Programs & Examples On #Xls

xls is the file extension for files created using the default format of Microsoft Excel (prior to Excel 2007).

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to change pivot table data source in Excel?

for MS excel 2000 office version, click on the pivot table you will find a tab above the ribon, called Pivottable tool - click on that You can change data source from Data tab

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

converting CSV/XLS to JSON?

Since Powershell 3.0 (shipped with Windows 8, available for Windows 7 and windows Server 2008 but not Windows Vista ) you can use the built-in convertto-json commandlet:

PS E:> $topicsjson = import-csv .\itinerary-all.csv | ConvertTo-Json 

PS E:\> $topicsjson.Length
11909

PS E:\> $topicsjson.getType()

IsPublic IsSerial Name                                     BaseType                  
-------- -------- ----                                     --------                  
True     True     Object[]                                 System.Array              

Online Help Page on Technet

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

How to parse Excel (XLS) file in Javascript/HTML5

include the xslx.js , xlsx.full.min.js , jszip.js

add a onchange event handler to the file input

function showDataExcel(event)
{
            var file = event.target.files[0];
            var reader = new FileReader();
            var excelData = [];
            reader.onload = function (event) {
                var data = event.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

                    for (var i = 0; i < XL_row_object.length; i++)
                    {
                        excelData.push(XL_row_object[i]["your column name"]);

                    }

                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    alert(excelData);
                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);

}

Importing Excel files into R, xlsx or xls

I recently discovered Schaun Wheeler's function for importing excel files into R after realising that the xlxs package hadn't been updated for R 3.1.0.

https://gist.github.com/schaunwheeler/5825002

The file name needs to have the ".xlsx" extension and the file can't be open when you run the function.

This function is really useful for accessing other peoples work. The main advantages over using the read.csv function are when

  • Importing multiple excel files
  • Importing large files
  • Files that are updated regularly

Using the read.csv function requires manual opening and saving of each Excel document which is time consuming and very boring. Using Schaun's function to automate the workflow is therefore a massive help.

Big props to Schaun for this solution.

How do I create a readable diff of two spreadsheets using git diff?

Newer versions of MS Office come with Spreadsheet Compare, which performs a fairly nice diff in a GUI. It detects most kinds of changes.

xls to csv converter

Maybe someone find this ready-to-use piece of code useful. It allows to create CSVs from all spreadsheets in Excel's workbook.

enter image description here

# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys

def csv_from_excel(excel_file):
    workbook = xlrd.open_workbook(excel_file)
    all_worksheets = workbook.sheet_names()
    for worksheet_name in all_worksheets:
        worksheet = workbook.sheet_by_name(worksheet_name)
        with open(u'{}.csv'.format(worksheet_name), 'wb') as your_csv_file:
            wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
            for rownum in xrange(worksheet.nrows):
                wr.writerow([unicode(entry).encode("utf-8") for entry in worksheet.row_values(rownum)])

if __name__ == "__main__":
    csv_from_excel(sys.argv[1])

Reading/parsing Excel (xls) files with Python

If you need old XLS format. Below code for ansii 'cp1251'.

import xlrd

file=u'C:/Landau/task/6200.xlsx'

try:
    book = xlrd.open_workbook(file,encoding_override="cp1251")  
except:
    book = xlrd.open_workbook(file)
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
for rx in range(sh.nrows):
   print(sh.row(rx))

Export to xls using angularjs

A cheap way to do this is to use Angular to generate a <table> and use FileSaver.js to output the table as an .xls file for the user to download. Excel will be able to open the HTML table as a spreadsheet.

<div id="exportable">
    <table width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>DoB</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in items">
                <td>{{item.name}}</td>
                <td>{{item.email}}</td>
                <td>{{item.dob | date:'MM/dd/yy'}}</td>
            </tr>
        </tbody>
    </table>
</div>

Export call:

var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
    });
    saveAs(blob, "Report.xls");
};

Demo: http://jsfiddle.net/TheSharpieOne/XNVj3/1/

Updated demo with checkbox functionality and question's data. Demo: http://jsfiddle.net/TheSharpieOne/XNVj3/3/

.NET Excel Library that can read/write .xls files

Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:

private DataTable LoadExcelData(string fileName)
{
  string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

  OleDbConnection con = new OleDbConnection(Connection);

  OleDbCommand command = new OleDbCommand();

  DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);

  myCommand.Fill(dt);

  Console.WriteLine(dt.Rows.Count);

  return dt;
}

You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.

How to install Ruby 2.1.4 on Ubuntu 14.04

There is a PPA with up-to-date versions of Ruby 2.x for Ubuntu 12.04+:

$ sudo apt-add-repository ppa:brightbox/ruby-ng
$ sudo apt-get update
$ sudo apt-get install ruby2.4

$ ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux-gnu]

Why cannot cast Integer to String in java?

No. Every object can be casted to an java.lang.Object, not a String. If you want a string representation of whatever object, you have to invoke the toString() method; this is not the same as casting the object to a String.

Select2 doesn't work when embedded in a bootstrap modal

Just remove tabindex="-1" and add style overflow:hidden

Here is an example:

<div id="myModal" class="modal fade" role="dialog" style="overflow:hidden;">
    <!---content modal here -->
</div>

How do I change Bootstrap 3 column order on mobile layout?

You cannot change the order of columns in smaller screens but you can do that in large screens.

So change the order of your columns.

<!--Main Content-->
<div class="col-lg-9 col-lg-push-3">
</div>

<!--Sidebar-->
<div class="col-lg-3 col-lg-pull-9">
</div>

By default this displays the main content first.

So in mobile main content is displayed first.

By using col-lg-push and col-lg-pull we can reorder the columns in large screens and display sidebar on the left and main content on the right.

Working fiddle here.

from list of integers, get number closest to a given value

>>> takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num))
>>> takeClosest(5,[4,1,88,44,3])
4

A lambda is a special way of writing an "anonymous" function (a function that doesn't have a name). You can assign it any name you want because a lambda is an expression.

The "long" way of writing the the above would be:

def takeClosest(num,collection):
   return min(collection,key=lambda x:abs(x-num))

Read a file in Node.js

simple synchronous way with node:

let fs = require('fs')

let filename = "your-file.something"

let content = fs.readFileSync(process.cwd() + "/" + filename).toString()

console.log(content)

Passing an Array as Arguments, not an Array, in PHP

Also note that if you want to apply an instance method to an array, you need to pass the function as:

call_user_func_array(array($instance, "MethodName"), $myArgs);

Use the auto keyword in C++ STL

auto keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.

Conversion from 12 hours time to 24 hours time in java

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); 

provided by Bart Kiers answer should be replaced with somethig like

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

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

Make sure that the component has the "exported" flag set to true. Also the component defining the permission should be installed before the component that uses it.

How do I attach events to dynamic HTML elements with jQuery?

I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

From http://api.jquery.com/live/

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

See http://api.jquery.com/on/

So instead of...

$(".myclass").click( function() {
    // do something
});

You can write...

$('body').on('click', 'a.myclass', function() {
    // do something
});

This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

$('ul').on('click', 'li', function() {
    alert( $(this).text() );
});

As long as the ul tag exists this will work (no li elements need exist yet).

Joining Multiple Tables - Oracle

I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN, and CROSS JOIN elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM clause and all the join conditions are put in the the WHERE clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.

I'd rewrite your query as:

SELECT bc.firstname,
       bc.lastname,
       b.title,
       TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
       p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
  ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN  book_order bo
  ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
  ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';

Share and enjoy.

Deserializing JSON array into strongly typed .NET object

Pat, the json structure looks very familiar to a problem i described here - The answer for me was to treat the json representation as a Dictionary<TKey, TValue>, even though there was only 1 entry.

If I am correct your key is of type string and the value of a List<T> where T represents the class 'TheUser'

HTH

PS - if you want better serialisation perf check out using Silverlight Serializer, you'll need to build a WP7 version, Shameless plug - I wrote a blog post about this

How to check if all of the following items are in a list?

This was what I was searching online but unfortunately found not online but while experimenting on python interpreter.

>>> case  = "caseCamel"
>>> label = "Case Camel"
>>> list  = ["apple", "banana"]
>>>
>>> (case or label) in list
False
>>> list = ["apple", "caseCamel"]
>>> (case or label) in list
True
>>> (case and label) in list
False
>>> list = ["case", "caseCamel", "Case Camel"]
>>> (case and label) in list
True
>>>

and if you have a looong list of variables held in a sublist variable

>>>
>>> list  = ["case", "caseCamel", "Case Camel"]
>>> label = "Case Camel"
>>> case  = "caseCamel"
>>>
>>> sublist = ["unique banana", "very unique banana"]
>>>
>>> # example for if any (at least one) item contained in superset (or statement)
...
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
False
>>>
>>> sublist[0] = label
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>> # example for whether a subset (all items) contained in superset (and statement)
...
>>> # a bit of demorgan's law
...
>>> next((False for item in sublist if item not in list), True)
False
>>>
>>> sublist[1] = case
>>>
>>> next((False for item in sublist if item not in list), True)
True
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>>

How to create bitmap from byte array?

Guys thank you for your help. I think all of this answers works. However i think my byte array contains raw bytes. That's why all of those solutions didnt work for my code.

However i found a solution. Maybe this solution helps other coders who have problem like mine.

static byte[] PadLines(byte[] bytes, int rows, int columns) {
   int currentStride = columns; // 3
   int newStride = columns;  // 4
   byte[] newBytes = new byte[newStride * rows];
   for (int i = 0; i < rows; i++)
       Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
   return newBytes;
 }

 int columns = imageWidth;
 int rows = imageHeight;
 int stride = columns;
 byte[] newbytes = PadLines(imageData, rows, columns);

 Bitmap im = new Bitmap(columns, rows, stride, 
          PixelFormat.Format8bppIndexed, 
          Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));

 im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");

This solutions works for 8bit 256 bpp (Format8bppIndexed). If your image has another format you should change PixelFormat .

And there is a problem with colors right now. As soon as i solved this one i will edit my answer for other users.

*PS = I am not sure about stride value but for 8bit it should be equal to columns.

And also this function Works for me.. This function copies 8 bit greyscale image into a 32bit layout.

public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
        {

            byte[] data = new byte[width * height * 4];

            int o = 0;

            for (int i = 0; i < width * height; i++)
            {
                byte value = imageData[i];


                data[o++] = value;
                data[o++] = value;
                data[o++] = value;
                data[o++] = 0; 
            }

            unsafe
            {
                fixed (byte* ptr = data)
                {

                    using (Bitmap image = new Bitmap(width, height, width * 4,
                                PixelFormat.Format32bppRgb, new IntPtr(ptr)))
                    {

                        image.Save(Path.ChangeExtension(fileName, ".jpg"));
                    }
                }
            }
        }

Does bootstrap have builtin padding and margin classes?

I'm adding this code to my Bootstrap3.3 project with the same grid columns breakpoints, based with the @guest answer. Before I have used the Bootstrap 4 padding and margins helper it seens to be a good choice.

/*Margin and Padding helpers*/
/*xs*/
.p-xs { padding: .25em; }
.p-x-xs { padding: 0 .25em; }
.p-y-xs { padding: .25em 0 ; }
.p-t-xs { padding-top: .25em; }
.p-r-xs { padding-right: .25em; }
.p-b-xs { padding-bottom: .25em; }
.p-l-xs { padding-left: .25em; }
.m-xs { margin: .25em; }
.m-x-xs { margin: 0 .25em; }
.m-y-xs { margin: .25em 0 ; }
.m-r-xs { margin-right: .25em; }
.m-l-xs { margin-left: .25em; }
.m-t-xs { margin-top: .25em; }
.m-b-xs { margin-bottom: .25em; }
/*sm*/
@media (min-width:768px){
/*sm*/
.p-sm { padding: .5em; }
.p-x-sm { padding: 0 .5em; }
.p-y-sm { padding: .5em 0 ; }
.p-t-sm { padding-top: .5em; }
.p-r-sm { padding-right: .5em; }
.p-b-sm { padding-bottom: .5em; }
.p-l-sm { padding-left: .5em; }
.m-sm { margin: .5em; }
.m-x-sm { margin: 0 .5em; }
.m-y-sm { margin: .5em 0 ; }
.m-t-sm { margin-top: .5em; }
.m-r-sm { margin-right: .5em; }
.m-b-sm { margin-bottom: .5em; }
.m-l-sm { margin-left: .5em; }
}

/*md*/
@media (min-width: 992px){
.p-md { padding: 1em; }
.p-x-md { padding: 0 1em; }
.p-y-md { padding: 1em 0; }
.p-t-md { padding-top: 1em; }
.p-r-md { padding-right: 1em; }
.p-b-md { padding-bottom: 1em; }
.p-l-md { padding-left: 1em; }
.m-md { margin: 1em; }
.m-x-md { margin: 0 1em; }
.m-y-md { margin: 1em 0 ; }
.m-t-md { margin-top: 1em; }
.m-r-md { margin-right: 1em; }
.m-b-md { margin-bottom: 1em; }
.m-l-md { margin-left: 1em; }
}

/*lg*/
@media (min-width: 1200px){
.p-lg { padding: 1.5em; }
.p-x-lg { padding: 0 1.5em; }
.p-y-lg { padding: 1.5em 0; }
.p-t-lg { padding-top: 1.5em; }
.p-r-lg { padding-right: 1.5em; }
.p-b-lg { padding-bottom: 1.5em; }
.p-l-lg { padding-left: 1.5em; }
.m-lg { margin: 1.5em; }
.m-x-lg { margin: 0 1.5em; }
.m-y-lg { margin: 1.5em 0; }
.m-t-lg { margin-top: 1.5em; }
.m-r-lg { margin-right: 1.5em; }
.m-b-lg { margin-bottom: 1.5em; }
.m-l-lg { margin-left: 1.5em; }
}
/*xl*/
.p-xl { padding: 3em; }
.p-x-xl { padding: 0 3em; }
.p-y-xl { padding: 3em 0 ; }
.p-t-xl { padding-top: 3em; }
.p-r-xl { padding-right: 3em; }
.p-b-xl { padding-bottom: 3em; }
.p-l-xl { padding-left: 3em; }
.m-xl { margin: 3em; }
.m-x-xl { margin: 0 3em; }
.m-y-xl { margin: 3em 0; }
.m-t-xl { margin-top: 3em; }
.m-r-xl { margin-right: 3em; }
.m-b-xl { margin-bottom: 3em; }
.m-l-xl { margin-left: 3em; }``

How to Code Double Quotes via HTML Codes

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

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

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

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

First few lines: man head.

Append lines: use the >> operator (?) in Bash:

echo 'This goes at the end of the file' >> file

anaconda - graphviz - can't import after installation

Check if tensorflow is activated in your terminal

first deactivate it using

conda deactivate

then use the command

conda install python-graphviz

and then install

conda install graphviz

this is solution for UBUNTU USERS :) CHEERS :)

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

javascript scroll event for iPhone/iPad?

Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.

So, if you register the scroll event handler and check window.pageYOffset inside that event handler, everything works just fine.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Select distinct rows from datatable in Linq

Like this: (Assuming a typed dataset)

someTable.Select(r => new { r.attribute1_name, r.attribute2_name }).Distinct();

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You should replace the old OpenSSL binary file by the new one via a symlink:

sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`

Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

How to keep footer at bottom of screen

set its position:fixed and bottom:0 so that it will always reside at bottom of your browser windows

java.io.InvalidClassException: local class incompatible:

One thing that could have happened:

  • 1: you create your serialized data with a given library A (version X)
  • 2: you then try to read this data with the same library A (but version Y)

Hence, at compile time for the version X, the JVM will generate a first Serial ID (for version X) and it will do the same with the other version Y (another Serial ID).

When your program tries to de-serialize the data, it can't because the two classes do not have the same Serial ID and your program have no guarantee that the two Serialized objects correspond to the same class format.

Assuming you changed your constructor in the mean time and this should make sense to you.

css width: calc(100% -100px); alternative using jquery

If you have a browser that doesn't support the calc expression, it's not hard to mimic with jQuery:

$('#yourEl').css('width', '100%').css('width', '-=100px');

It's much easier to let jQuery handle the relative calculation than doing it yourself.

Allowed memory size of 536870912 bytes exhausted in Laravel

While using Laravel on apache server there is another php.ini

 /etc/php/7.2/apache2/php.ini

Modify the memory limit value in this file

 memory_limit=1024M

and restart the apache server

 sudo service apache2 restart

How do I get git to default to ssh and not https for new repositories

Set up a repository's origin branch to be SSH

The GitHub repository setup page is just a suggested list of commands (and GitHub now suggests using the HTTPS protocol). Unless you have administrative access to GitHub's site, I don't know of any way to change their suggested commands.

If you'd rather use the SSH protocol, simply add a remote branch like so (i.e. use this command in place of GitHub's suggested command). To modify an existing branch, see the next section.

$ git remote add origin [email protected]:nikhilbhardwaj/abc.git

Modify a pre-existing repository

As you already know, to switch a pre-existing repository to use SSH instead of HTTPS, you can change the remote url within your .git/config file.

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    -url = https://github.com/nikhilbhardwaj/abc.git
    +url = [email protected]:nikhilbhardwaj/abc.git

A shortcut is to use the set-url command:

$ git remote set-url origin [email protected]:nikhilbhardwaj/abc.git

More information about the SSH-HTTPS switch

How do I handle the window close event in Tkinter?

Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the iconify method
be the protocol method's second argument.

Here's a working example, tested on Windows 7 & 10:

# Python 3
import tkinter
import tkinter.scrolledtext as scrolledtext

root = tkinter.Tk()
# make the top right close button minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# make Esc exit the program
root.bind('<Escape>', lambda e: root.destroy())

# create a menu bar with an Exit command
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)

# create a Text widget with a Scrollbar attached
txt = scrolledtext.ScrolledText(root, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')

root.mainloop()

In this example we give the user two new exit options:
the classic File ? Exit, and also the Esc button.

How to access private data members outside the class without making "friend"s?

In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!

class A {
     int iData;
};

int main ()
{
    A a;
    struct ATwin { int pubData; }; // define a twin class with public members
    reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value

    return 0;
}

jQuery creating objects

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});

How do you use variables in a simple PostgreSQL script?

DO $$
DECLARE  
   a integer := 10;  
   b integer := 20;  
   c integer;  
BEGIN  
   c := a + b;
    RAISE NOTICE'Value of c: %', c;
END $$;

How can I pass POST parameters in a URL?

This could work if the PHP script generates a form for each entry with hidden fields and the href uses JavaScript to post the form.

Static linking vs dynamic linking

One reason to do a statically linked build is to verify that you have full closure for the executable, i.e. that all symbol references are resolved correctly.

As a part of a large system that was being built and tested using continuous integration, the nightly regression tests were run using a statically linked version of the executables. Occasionally, we would see that a symbol would not resolve and the static link would fail even though the dynamically linked executable would link successfully.

This was usually occurring when symbols that were deep seated within the shared libs had a misspelt name and so would not statically link. The dynamic linker does not completely resolve all symbols, irrespective of using depth-first or breadth-first evaluation, so you can finish up with a dynamically linked executable that does not have full closure.

Write single CSV file using spark-csv

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs._
import org.apache.spark.sql.{DataFrame,SaveMode,SparkSession}
import org.apache.spark.sql.functions._

I solved using below approach (hdfs rename file name):-

Step 1:- (Crate Data Frame and write to HDFS)

df.coalesce(1).write.format("csv").option("header", "false").mode(SaveMode.Overwrite).save("/hdfsfolder/blah/")

Step 2:- (Create Hadoop Config)

val hadoopConfig = new Configuration()
val hdfs = FileSystem.get(hadoopConfig)

Step3 :- (Get path in hdfs folder path)

val pathFiles = new Path("/hdfsfolder/blah/")

Step4:- (Get spark file names from hdfs folder)

val fileNames = hdfs.listFiles(pathFiles, false)
println(fileNames)

setp5:- (create scala mutable list to save all the file names and add it to the list)

    var fileNamesList = scala.collection.mutable.MutableList[String]()
    while (fileNames.hasNext) {
      fileNamesList += fileNames.next().getPath.getName
    }
    println(fileNamesList)

Step 6:- (filter _SUCESS file order from file names scala list)

    // get files name which are not _SUCCESS
    val partFileName = fileNamesList.filterNot(filenames => filenames == "_SUCCESS")

step 7:- (convert scala list to string and add desired file name to hdfs folder string and then apply rename)

val partFileSourcePath = new Path("/yourhdfsfolder/"+ partFileName.mkString(""))
    val desiredCsvTargetPath = new Path(/yourhdfsfolder/+ "op_"+ ".csv")
    hdfs.rename(partFileSourcePath , desiredCsvTargetPath)

Get an OutputStream into a String

Here's what I ended up doing:

Obj.writeToStream(toWrite, os);
try {
    String out = new String(os.toByteArray(), "UTF-8");
    assertTrue(out.contains("testString"));
} catch (UnsupportedEncondingException e) {
    fail("Caught exception: " + e.getMessage());
}

Where os is a ByteArrayOutputStream.

Saving data to a file in C#

I think you might want something like this

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

Named placeholders in string formatting

You can use StringTemplate library, it offers what you want and much more.

import org.antlr.stringtemplate.*;

final StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());

join on multiple columns

Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.

    Select TableA.Col1, TableA.Col2, TableB.Val
    FROM TableA
    INNER JOIN TableB
          ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2 
          OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

check jar files in your project which are mentioned in config.ini if not proper then install manually and then follow the following steps:

  1. Select your product configuration file, right-click on it and select Run As Run Configurations
  2. Select "Validate plug-ins prior to launching". This will check if you have all required plug-ins in your run configuration. If this check reports that some plug-ins are missing, try clicking the "Add Required-Plug-Ins" button. Also make sure to define all dependencies in your product. And your application start running

React js onClick can't pass value to method

I guess you will have to bind the method to the React’s class instance. It’s safer to use a constructor to bind all methods in React. In your case when you pass the parameter to the method, the first parameter is used to bind the ‘this’ context of the method, thus you cannot access the value inside the method.

How to tell whether a point is to the right or left side of a line

First check if you have a vertical line:

if (x2-x1) == 0
  if x3 < x2
     it's on the left
  if x3 > x2
     it's on the right
  else
     it's on the line

Then, calculate the slope: m = (y2-y1)/(x2-x1)

Then, create an equation of the line using point slope form: y - y1 = m*(x-x1) + y1. For the sake of my explanation, simplify it to slope-intercept form (not necessary in your algorithm): y = mx+b.

Now plug in (x3, y3) for x and y. Here is some pseudocode detailing what should happen:

if m > 0
  if y3 > m*x3 + b
    it's on the left
  else if y3 < m*x3 + b
    it's on the right
  else
    it's on the line
else if m < 0
  if y3 < m*x3 + b
    it's on the left
  if y3 > m*x3+b
    it's on the right
  else
    it's on the line
else
  horizontal line; up to you what you do

How to find out line-endings in a text file?

You can use vim -b filename to edit a file in binary mode, which will show ^M characters for carriage return and a new line is indicative of LF being present, indicating Windows CRLF line endings. By LF I mean \n and by CR I mean \r. Note that when you use the -b option the file will always be edited in UNIX mode by default as indicated by [unix] in the status line, meaning that if you add new lines they will end with LF, not CRLF. If you use normal vim without -b on a file with CRLF line endings, you should see [dos] shown in the status line and inserted lines will have CRLF as end of line. The vim documentation for fileformats setting explains the complexities.

Also, I don't have enough points to comment on the Notepad++ answer, but if you use Notepad++ on Windows, use the View / Show Symbol / Show End of Line menu to display CR and LF. In this case LF is shown whereas for vim the LF is indicated by a new line.

Why does my Spring Boot App always shutdown immediately after starting?

With gradle, I replaced this line at build.gradle.kts file inside dependencies block

providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")

with this

compile("org.springframework.boot:spring-boot-starter-web")

and works fine.

MySQL Sum() multiple columns

If any of your markn columns are "AllowNull" then you will need to do a little extra to insure the correct result is returned, this is because 1 NULL value will result in a NULL total.

This is what i would consider to be the correct answer.

SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 

IFNULL will return the 2nd parameter if the 1st is NULL. COALESCE could be used but i prefer to only use it if it is required. See What is the difference bewteen ifnull and coalesce in mysql?

SUM-ing the entire calculation is tidier than SUM-ing each column individually.

SELECT `student`, SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 
FROM student_scorecard
GROUP BY `student`

How to download Visual Studio 2017 Community Edition for offline installation?

The command above worked for me

C:\Users\marcelo\Downloads\vs_community.exe --lang en-en --layout C:\VisualStudio2017 --all

"Thinking in AngularJS" if I have a jQuery background?

jQuery: you think a lot about 'QUERYing the DOM' for DOM elements and doing something.

AngularJS: THE model is the truth, and you always think from that ANGLE.

For example, when you get data from THE server which you intend to display in some format in the DOM, in jQuery, you need to '1. FIND' where in the DOM you want to place this data, the '2. UPDATE/APPEND' it there by creating a new node or just setting its innerHTML. Then when you want to update this view, you then '3. FIND' the location and '4. UPDATE'. This cycle of find and update all done within the same context of getting and formatting data from server is gone in AngularJS.

With AngularJS you have your model (JavaScript objects you are already used to) and the value of the model tells you about the model (obviously) and about the view, and an operation on the model automatically propagates to the view, so you don't have to think about it. You will find yourself in AngularJS no longer finding things in the DOM.

To put in another way, in jQuery, you need to think about CSS selectors, that is, where is the div or td that has a class or attribute, etc., so that I can get their HTML or color or value, but in AngularJS, you will find yourself thinking like this: what model am I dealing with, I will set the model's value to true. You are not bothering yourself of whether the view reflecting this value is a checked box or resides in a td element (details you would have often needed to think about in jQuery).

And with DOM manipulation in AngularJS, you find yourself adding directives and filters, which you can think of as valid HTML extensions.

One more thing you will experience in AngularJS: in jQuery you call the jQuery functions a lot, in AngularJS, AngularJS will call your functions, so AngularJS will 'tell you how to do things', but the benefits are worth it, so learning AngularJS usually means learning what AngularJS wants or the way AngularJS requires that you present your functions and it will call it accordingly. This is one of the things that makes AngularJS a framework rather than a library.

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

How to start and stop android service from a adb shell?

For anyone still confused about how to define the service name parameter, the forward slash goes immediately after the application package name in the fully qualified class name.

So given an application package name of: app.package.name

And a full path to the service of: app.package.name.example.package.path.MyServiceClass

Then the command would look like this:

adb shell am startservice app.package.name/.example.package.path.MyServiceClass

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

How to merge multiple lists into one list in python?

a = ['it']
b = ['was']
c = ['annoying']

a.extend(b)
a.extend(c)

# a now equals ['it', 'was', 'annoying']

What is private bytes, virtual bytes, working set?

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

How do you turn a Mongoose document into a plain object?

A better way of tackling an issue like this is using doc.toObject() like this

doc.toObject({ getters: true })

other options include:

  • getters: apply all getters (path and virtual getters)
  • virtuals: apply virtual getters (can override getters option)
  • minimize: remove empty objects (defaults to true)
  • transform: a transform function to apply to the resulting document before returning
  • depopulate: depopulate any populated paths, replacing them with their original refs (defaults to false)
  • versionKey: whether to include the version key (defaults to true)

so for example you can say

Model.findOne().exec((err, doc) => {
   if (!err) {
      doc.toObject({ getters: true })
      console.log('doc _id:', doc._id)
   }
})

and now it will work.

For reference, see: http://mongoosejs.com/docs/api.html#document_Document-toObject

Remove last character of a StringBuilder?

stringBuilder.Remove(stringBuilder.Length - 1, 1);

Python reading from a file and saving to utf-8

You can't do that using open. use codecs.

when you are opening a file in python using the open built-in function you will always read/write the file in ascii. To write it in utf-8 try this:

import codecs
file = codecs.open('data.txt','w','utf-8')

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

How to return value from Action()?

Your static method should go from:

public static class SimpleUsing
{
    public static void DoUsing(Action<MyDataContext> action)
    {
        using (MyDataContext db = new MyDataContext())
           action(db);
    }
}

To:

public static class SimpleUsing
{
    public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action)
    {
        using (MyDataContext db = new MyDataContext())
           return action(db);
    }
}

This answer grew out of comments so I could provide code. For a complete elaboration, please see @sll's answer below.

Create two-dimensional arrays and access sub-arrays in Ruby

You didn't state your actual goal, but maybe this can help:

require 'matrix'  # bundled with Ruby
m = Matrix[
 [1, 2, 3],
 [4, 5, 6]
]

m.column(0) # ==> Vector[1, 4]

(and Vectors acts like arrays)

or, using a similar notation as you desire:

m.minor(0..1, 2..2) # => Matrix[[3], [6]]

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

What's the PowerShell syntax for multiple values in a switch statement?

switch($someString.ToLower()) 
{ 
    {($_ -eq "y") -or ($_ -eq "yes")} { "You entered Yes." } 
    default { "You entered No." } 
}

Display Image On Text Link Hover CSS Only

add

.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

In Python, how do I iterate over a dictionary in sorted key order?

Greg's answer is right. Note that in Python 3.0 you'll have to do

sorted(dict.items())

as iteritems will be gone.

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

What is http multipart request?

As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.

Retrieving parameters from a URL

parameters = dict([part.split('=') for part in get_parsed_url[4].split('&')])

This one is simple. The variable parameters will contain a dictionary of all the parameters.

Displaying the Indian currency symbol on a website

It will take more than an year (or two) for the universal acceptance.

  1. Unicode consortium approves the char-code.
  2. Fonts are updated to include this symbol
  3. Browsers/OS are updated to include new fonts and then only it is visible on every browser on earth.

Creating custom fonts by using arbitrary code-base and (forcefully) embedding them in every web-pages is discouraged for Website. (for desktop applications it may be acceptable). Although your solution may be acceptable; I would not advice just for the sake of one symbol! Loading a font file makes web-pages slower.

By the time it is advised to use icon-sets for rupee symbol. Prepare a set of icons with sizes 12x8, 16x12, 32x32 that you can incorporate in-line using <img> tag.

E.g 5000/- (i just resized the image; it should have been re-sampled for given size for better results)

<img src="http://i.stack.imgur.com/nGbfO.png" width="8" height="10">

Note: This is what Wikipedia does. it uses png/svg file. Check the infobox here.

How does ifstream's eof() work?

The EOF flag is only set after a read operation attempts to read past the end of the file. get() is returning the symbolic constant traits::eof() (which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof() be true. If you want to check for this condition, you can do something like the following:

int ch;
while ((ch = inf.get()) != EOF) {
    std::cout << static_cast<char>(ch) << "\n";
}

adding text to an existing text element in javascript via DOM

remove .textContent from var t = document.getElementById("p").textContent;

_x000D_
_x000D_
var t = document.getElementById("p");_x000D_
var y = document.createTextNode("This just got added");_x000D_
_x000D_
t.appendChild(y);
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

Use .get(), which if the key is not found, returns None.

for i in keySet:
    temp = myDict.get(i)
    if temp is not None:
        print temp
        break

What is the difference between Google App Engine and Google Compute Engine?

App Engine gives developers the ability to control Google Compute Engine cores, as well as provide a web-facing front end for Google Compute Engine data processing applications.

On the other hand, Compute Engine offers direct and complete operating system management of your virtual machines. To present your App, you're going to need resources, and Google Cloud Storage is ideal for storing your assets and data, whatever they're used for. You get fast data access with hosting around the globe. Reliability is guaranteed at a 99.95% up-time, and Google also provides the ability to back up and restore your data, and believe it or not, storage is unlimited.

You can manage your assets with Google Cloud Storage, storing, retrieving, displaying, and deleting them. You can also quickly read and write to flat datasheets that are kept in Cloud Storage. Next in the Google Cloud lineup is BigQuery. With BigQuery, you can analyze massive amounts of data, we're talking millions of records, within seconds. Access is handled via a straightforward UI, or a Representational State Transfer, or REST interface.

Data storage is, as you might suspect, not a problem, and scales to hundreds of TB. BigQuery is accessible via a host of client libraries, including those for Java, .NET, Python, Go, Ruby, PHP, and Javascript. A SQL-like syntax called NoSQL is available which can be accessed through these client libraries, or through a web user interface. Finally, let's talk about the Google Cloud platform database options, Cloud SQL and Cloud Datastore.

There is a major difference. Cloud SQL is for relational databases, primarily MySQL, whereas Cloud Datastore is for non-relational databases using noSQL. With Cloud SQL, you have the choice of either hosting in the US, Europe, or Asia, with 100 GB of storage, and 16 GB of RAM per database instance.

Cloud Datastore is available at no charge for up to 50 K read/write instructions per month and 1 GB of data stored also per month. There is a fee if you exceed these quotas, however. App Engine can also work with other lesser known, more targeted members of the Google Cloud platform, including the Cloud Endpoints for creating API backends, Google Prediction API for data analysis and trend forecasting, or the Google Translate API, for multilingual output.

While you can do a fair amount with App Engine on its own, It's potential skyrockets when you factor in its ability to work easily and efficiently with its fellow Google Cloud platform services.

Google Map API v3 — set bounds and center

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

How can I find the number of days between two Date objects in Ruby?

all of these steered me to the correct result, but I wound up doing

DateTime.now.mjd - DateTime.parse("01-01-1995").mjd

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Object reference not set to an instance of an object.

I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:

public static IsEmptyOrWhitespace(this string value) {
    return String.IsEmptyOrWhitespace(value);
}

This makes it possible to call:

string strValue;
if (strValue.IsEmptyOrWhitespace())
     // do stuff

To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

Flutter Countdown Timer

I'm using https://pub.dev/packages/flutter_countdown_timer

dependencies: flutter_countdown_timer: ^1.0.0

$ flutter pub get

CountdownTimer(endTime: 1594829147719)

1594829147719 is your timestamp in milliseconds

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case

demo.sh

#!/bin/bash

function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."

export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"

# clean function style
sudo_exports ./sudo_test.sh

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh

Result

$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.

How?

This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

Unable to connect PostgreSQL to remote database using pgAdmin

Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

  1. Open PuTTY. If you already have a session set up to connect to the EC2 instance, load that, but don't connect to it just yet. If you don't have such a session, see this post.
  2. Go to Connection > SSH > Tunnels
  3. Enter 5433 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the "Add" button.
  6. Go back to Session, and save your session, then click "Open" to connect.
  7. This opens a terminal window. Once you're connected, you can leave that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 5433 in the Port field. Specify a Name for the connection, and the username and password. Click OK when you're done.

How to check if array element exists or not in javascript?

(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Check if the second item in the array is undefined using the typeof and checking for undefined

Ripple effect on Android Lollipop CardView

I wasn't happy with AppCompat, so I wrote my own CardView and backported ripples. Here it's running on Galaxy S with Gingerbread, so it's definitely possible.

Demo of Ripple on Galaxy S

For more details check the source code.

JQuery Redirect to URL after specified time

Use setTimeout function with either of the following

// simulates similar behavior as an HTTP redirect
window.location.replace("http://www.google.com");

// simulates similar behavior as clicking on a link
window.location.href = "http://www.google.com";

setTimeout(function(){
   window.location.replace("http://www.google.com");
}, 1000) 

source: https://www.sitepoint.com/jquery-redirect-web-page/

Simple If/Else Razor Syntax

To get rid of the if/else awkwardness you could use a using block:

@{
    var count = 0;
    foreach (var item in Model)
    {
        using(Html.TableRow(new { @class = (count++ % 2 == 0) ? "alt-row" : "" }))
        {
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Truncate(item.Details, 75)
            </td>
            <td>
                <img src="@Url.Content("~/Content/Images/Projects/")@item.Images.Where(i => i.IsMain == true).Select(i => i.Name).Single()" 
                    alt="@item.Images.Where(i => i.IsMain == true).Select(i => i.AltText).Single()" class="thumb" />
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ProjectId }) |
                @Html.ActionLink("Details", "Details", new { id = item.ProjectId }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.ProjectId })
            </td>
        }
    }
}

Reusable element that make it easier to add attributes:

//Block is take from http://www.codeducky.org/razor-trick-using-block/
public class TableRow : Block
{
    private object _htmlAttributes;
    private TagBuilder _tr;

    public TableRow(HtmlHelper htmlHelper, object htmlAttributes) : base(htmlHelper)
    {
        _htmlAttributes = htmlAttributes;
    }

    public override void BeginBlock()
    {
        _tr = new TagBuilder("tr");
        _tr.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(_htmlAttributes));
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.StartTag));
    }

    protected override void EndBlock()
    {
        this.HtmlHelper.ViewContext.Writer.Write(_tr.ToString(TagRenderMode.EndTag));
    }
}

Helper method to make razor syntax clearer:

public static TableRow TableRow(this HtmlHelper self, object htmlAttributes)
{
    var tableRow = new TableRow(self, htmlAttributes);
    tableRow.BeginBlock();
    return tableRow;
}

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

Position: absolute and parent height?

This kind of layout problem can be solved with flexbox now, avoiding the need to know heights or control layout with absolute positioning, or floats. OP's main question was how to get a parent to contain children of unknown height, and they wanted to do it within a certain layout. Setting height of the parent container to "fit-content" does this; using "display: flex" and "justify-content: space-between" produces the section/column layout I think the OP was trying to create.

<section id="foo">
    <header>Foo</header>
    <article>
        <div class="main one"></div>
        <div class="main two"></div>
    </article>
</section>    

<div style="clear:both">Clear won't do.</div>

<section id="bar">
    <header>bar</header>
    <article>
        <div class="main one"></div><div></div>
        <div class="main two"></div>
    </article>
</section> 

* { text-align: center; }
article {
    height: fit-content ;
    display: flex;
    justify-content: space-between;
    background: whitesmoke;
}
article div { 
    background: yellow;     
    margin:20px;
    width: 30px;
    height: 30px;
    }

.one {
    background: red;
}

.two {
    background: blue;
}

I modified the OP's fiddle: http://jsfiddle.net/taL4s9fj/

css-tricks on flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

Why have header files and .cpp files?

Because C++ inherited them from C. Unfortunately.

Concatenate two JSON objects

I use:

let x = { a: 1, b: 2, c: 3 }

let y = {c: 4, d: 5, e: 6 }

let z = Object.assign(x, y)

console.log(z)

// OUTPUTS:
{ a:1, b:2, c:4, d:5, e:6 }

From here.

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

Ignore <br> with CSS?

While this question appears to already have been solved, the accepted answer didn't solve the problem for me on Firefox. Firefox (and possibly IE, though I haven't tried it) skip whitespaces while reading the contents of the "content" tag. While I completely understand why Mozilla would do that, it does bring its share of problems. The easiest workaround I found was to use non-breakable spaces instead of regular ones as shown below.

.noLineBreaks br:before{
content: '\a0'
}

Have a look.

Plot correlation matrix using pandas

You can observe the relation between features either by drawing a heat map from seaborn or scatter matrix from pandas.

Scatter Matrix:

pd.scatter_matrix(dataframe, alpha = 0.3, figsize = (14,8), diagonal = 'kde');

If you want to visualize each feature's skewness as well - use seaborn pairplots.

sns.pairplot(dataframe)

Sns Heatmap:

import seaborn as sns

f, ax = pl.subplots(figsize=(10, 8))
corr = dataframe.corr()
sns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), cmap=sns.diverging_palette(220, 10, as_cmap=True),
            square=True, ax=ax)

The output will be a correlation map of the features. i.e. see the below example.

enter image description here

The correlation between grocery and detergents is high. Similarly:

Pdoducts With High Correlation:
  1. Grocery and Detergents.
Products With Medium Correlation:
  1. Milk and Grocery
  2. Milk and Detergents_Paper
Products With Low Correlation:
  1. Milk and Deli
  2. Frozen and Fresh.
  3. Frozen and Deli.

From Pairplots: You can observe same set of relations from pairplots or scatter matrix. But from these we can say that whether the data is normally distributed or not.

enter image description here

Note: The above is same graph taken from the data, which is used to draw heatmap.

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I got the same problem (with Plesk 12 installed). However, when i switched from execute PHP as FastCGI to Apache Module the website worked.

Checked my suexec log:

$ cd /var/log/apache2/
$ less suexec.log

When you find something like this:

[2015-03-22 10:49:00]: directory is writable by others: (/var/www/cgi-bin/cgi_wrapper)
[2015-03-22 10:49:05]: uid: (10004/gb) gid: (1005/1005) cmd: cgi_wrapper

try this commands

$ chown root:root /var/www/cgi-bin/cgi_wrapper
$ chmod 755 /var/www/cgi-bin/cgi_wrapper
$ shutdown -r now

as root.

I hope it can help you.

MySQL set current date in a DATETIME field on insert

Since MySQL 5.6.X you can do this:

ALTER TABLE `schema`.`users` 
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;

That way your column will be updated with the current timestamp when a new row is inserted, or updated.

If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP in the DEFAULT value field, like so:

enter image description here

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

How to display image from database using php

<?php
    $conn = mysql_connect ("localhost:3306","root","");
    $db = mysql_select_db ("database_name", $conn);

    if(!$db) {
        echo mysql_error();
    }

    $q = "SELECT image FROM table_name where id=4";
    $r = mysql_query ("$q",$conn);
    if($r) {
         while($row = mysql_fetch_array($r)) {
            header ("Content-type: image/jpeg");       
    echo $row ["image"];
        }
    }else{
        echo mysql_error();
    }
    ?>

sometimes problem may  occures because of port number of mysql server is incoreect to avoid it just write port number with host name like this "localhost:3306" 
in case if you have installed two mysql servers on same system then write port according to that

in order to display any data from database please make sure following steps
1.proper connection with sql
2.select database
3.write query 
4.write correct table name inside the query
5.and last is traverse through data

How to ssh from within a bash script?

What you need to do is to exchange the SSH keys for the user the script runs as. Have a look at this tutorial

After doing so, your scripts will run without the need for entering a password. But, for security's sake, you don't want to do this for root users!

jquery select option click handler

What I have done in this situation is that I put in the option elements OnClick event like this:

<option onClick="something();">Option Name</option>

Then just create a script function like this:

function something(){
    alert("Hello"); 
    }

UPDATE: Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm

Determine a user's timezone

Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application:

It's About Time

In short, the described approach relies on the JavaScript getTimezoneOffset function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

If you want to uninstall when connected to single device/emulator then use below command

adb uninstall <package name>

else with multiple devices then use below command

adb -s <device ID> uninstall <package name>

How can I use the apply() function for a single column?

Although the given responses are correct, they modify the initial data frame, which is not always desirable (and, given the OP asked for examples "using apply", it might be they wanted a version that returns a new data frame, as apply does).

This is possible using assign: it is valid to assign to existing columns, as the documentation states (emphasis is mine):

Assign new columns to a DataFrame.

Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.

In short:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])

In [3]: df.assign(a=lambda df: df.a / 2)
Out[3]: 
      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

In [4]: df
Out[4]: 
    a   b  c
0  15  15  5
1  20  10  7
2  25  30  9

Note that the function will be passed the whole dataframe, not only the column you want to modify, so you will need to make sure you select the right column in your lambda.

int object is not iterable?

Well, you want to process the string representing the number, iterating over the digits, not the number itself (which is an abstract entity that could be written differently, like "CX" in Roman numerals or "0x6e" hexadecimal (both for 110) or whatever).

Therefore:

inp = input('Enter a number:')

n = 0
for digit in inp:
     n = n + int(digit)
     print(n)

Note that the n = 0 is required (someplace before entry into the loop). You can't take the value of a variable which doesn't exist (and the right hand side of n = n + int(digit) takes the value of n). And if n does exist at that point, it might hold something completely unrelated to your present needs, leading to unexpected behaviour; you need to guard against that.

This solution makes no attempt to ensure that the input provided by the user is actually a number. I'll leave this problem for you to think about (hint: all that you need is there in the Python tutorial).

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

AngularJS - How to use $routeParams in generating the templateUrl?

//module dependent on ngRoute  
 var app=angular.module("myApp",['ngRoute']);
    //spa-Route Config file
    app.config(function($routeProvider,$locationProvider){
          $locationProvider.hashPrefix('');
          $routeProvider
            .when('/',{template:'HOME'})
            .when('/about/:paramOne/:paramTwo',{template:'ABOUT',controller:'aboutCtrl'})
            .otherwise({template:'Not Found'});
    }
   //aboutUs controller 
    app.controller('aboutCtrl',function($routeParams){
          $scope.paramOnePrint=$routeParams.paramOne;
          $scope.paramTwoPrint=$routeParams.paramTwo;
    });

in index.html

<a ng-href="#/about/firstParam/secondParam">About</a>

firstParam and secondParam can be anything according to your needs.

Adobe Reader Command Line Reference

Call this after the print job has returned:

oShell.AppActivate "Adobe Reader"
oShell.SendKeys "%FX"

How to make a gui in python

Consider wxPython (which is cross-platform). Here is a tutorial.

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

How to get the query string by javascript?

You can easily build a dictionary style collection...

function getQueryStrings() { 
  var assoc  = {};
  var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
  var queryString = location.search.substring(1); 
  var keyValues = queryString.split('&'); 

  for(var i in keyValues) { 
    var key = keyValues[i].split('=');
    if (key.length > 1) {
      assoc[decode(key[0])] = decode(key[1]);
    }
  } 

  return assoc; 
} 

And use it like this...

var qs = getQueryStrings();
var myParam = qs["myParam"]; 

How to use protractor to check if an element is visible?

I had a similar issue, in that I only wanted return elements that were visible in a page object. I found that I'm able to use the css :not. In the case of this issue, this should do you...

expect($('i.icon-spinner:not(.ng-hide)').isDisplayed()).toBeTruthy();

In the context of a page object, you can get ONLY those elements that are visible in this way as well. Eg. given a page with multiple items, where only some are visible, you can use:

this.visibileIcons = $$('i.icon:not(.ng-hide)'); 

This will return you all visible i.icons

get enum name from enum value

This is my take on it:

public enum LoginState { 
    LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);

    private int code;

    LoginState(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static LoginState getLoginStateFromCode(int code){
        for(LoginState e : LoginState.values()){
            if(code == e.code) return e;
        }
        return LoginState.LOGGED_OUT; //or null
    }
};

And I have used it with System Preferences in Android like so:

LoginState getLoginState(int i) {
    return LoginState.getLoginStateFromCode(
                prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
            );
}

public static void setLoginState(LoginState newLoginState) {
    editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
    editor().commit();
}

where pref and editor are SharedPreferences and a SharedPreferences.Editor

datetime dtypes in pandas read_csv

There is a parse_dates parameter for read_csv which allows you to define the names of the columns you want treated as dates or datetimes:

date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)

Associating existing Eclipse project with existing SVN repository

I came across the same issue. I checked out using Tortoise client and then tried to import the projects in Eclipse using import wizard. Eclipse did not recognize the svn location. I tried share option as mentioned in the above posts and it tried to commit these projects into SVN. But my issue was a version mismatch. I selected svn 1.8 version in eclipse (I was using 1.7 in eclipse and 1.8.8 in tortoise) and then re imported the projects. It resolved with no issues.

Simple way to change the position of UIView?

aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

If you're targeting HTML5 only you can use:

<input type="text" id="firstname" placeholder="First Name:" />

For non HTML5 browsers, I would build upon Floern's answer by using jQuery and make the javascript non-obtrusive. I would also use a class to define the blurred properties.

$(document).ready(function () {

    //Set the initial blur (unless its highlighted by default)
    inputBlur($('#Comments'));

    $('#Comments').blur(function () {
        inputBlur(this);
    });
    $('#Comments').focus(function () {
        inputFocus(this);
    });

})

Functions:

function inputFocus(i) {
    if (i.value == i.defaultValue) {
        i.value = "";
        $(i).removeClass("blurredDefaultText");
    }
}
function inputBlur(i) {
    if (i.value == "" || i.value == i.defaultValue) {
        i.value = i.defaultValue;
        $(i).addClass("blurredDefaultText");
    }
}

CSS:

.blurredDefaultText {
    color:#888 !important;
}

Django - taking values from POST request

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

How to compare if two structs, slices or maps are equal?

reflect.DeepEqual is often incorrectly used to compare two like structs, as in your question.

cmp.Equal is a better tool for comparing structs.

To see why reflection is ill-advised, let's look at the documentation:

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

....

numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

If we compare two time.Time values of the same UTC time, t1 == t2 will be false if their metadata timezone is different.

go-cmp looks for the Equal() method and uses that to correctly compare times.

Example:

m1 := map[string]int{
    "a": 1,
    "b": 2,
}
m2 := map[string]int{
    "a": 1,
    "b": 2,
}
fmt.Println(cmp.Equal(m1, m2)) // will result in true

How to make a Bootstrap accordion collapse when clicking the header div?

Simple solution would be to remove padding from .panel-heading and add to .panel-title a.

.panel-heading {
    padding: 0;
}
.panel-title a {
    display: block;
    padding: 10px 15px;
}

This solution is similar to the above one posted by calfzhou, slightly different.

How do I set a checkbox in razor view?

you set AllowRating property to true from your controller or model

      @Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })

Loading inline content using FancyBox

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

How to set header and options in axios?

try this code

in example code use axios get rest API.

in mounted

  mounted(){
    var config = {
    headers: { 
      'x-rapidapi-host': 'covid-19-coronavirus-statistics.p.rapidapi.com',
      'x-rapidapi-key': '5156f83861mshd5c5731412d4c5fp18132ejsn8ae65e661a54' 
      }
   };
   axios.get('https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats? 
    country=Thailand',  config)
    .then((response) => {
    console.log(response.data);
  });
}

Hope is help.

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Automating the InvokeRequired code pattern

I'd rather use a single instance of a method Delegate instead of creating a new instance every time. In my case i used to show progress and (info/error) messages from a Backroundworker copying and casting large data from a sql instance. Everywhile after about 70000 progress and message calls my form stopped working and showing new messages. This didn't occure when i started using a single global instance delegate.

delegate void ShowMessageCallback(string message);

private void Form1_Load(object sender, EventArgs e)
{
    ShowMessageCallback showMessageDelegate = new ShowMessageCallback(ShowMessage);
}

private void ShowMessage(string message)
{
    if (this.InvokeRequired)
        this.Invoke(showMessageDelegate, message);
    else
        labelMessage.Text = message;           
}

void Message_OnMessage(object sender, Utilities.Message.MessageEventArgs e)
{
    ShowMessage(e.Message);
}

How to raise a ValueError?

>>> response='bababa'
...  if "K" in response.text:
...     raise ValueError("Not found")

Replace only some groups with Regex

Here is a version similar to Daniel's but replacing multiple matches:

public static string ReplaceGroup(string input, string pattern, RegexOptions options, string groupName, string replacement)
{
    Match match;
    while ((match = Regex.Match(input, pattern, options)).Success)
    {
        var group = match.Groups[groupName];

        var sb = new StringBuilder();

        // Anything before the match
        if (match.Index > 0)
            sb.Append(input.Substring(0, match.Index));

        // The match itself
        var startIndex = group.Index - match.Index;
        var length = group.Length;
        var original = match.Value;
        var prior = original.Substring(0, startIndex);
        var trailing = original.Substring(startIndex + length);
        sb.Append(prior);
        sb.Append(replacement);
        sb.Append(trailing);

        // Anything after the match
        if (match.Index + match.Length < input.Length)
            sb.Append(input.Substring(match.Index + match.Length));

        input = sb.ToString();
    }

    return input;

How to print HTML content on click of a button, but not the page?

Below Code May Be Help You :

<html>
<head>
<script>
function printPage(id)
{
   var html="<html>";
   html+= document.getElementById(id).innerHTML;

   html+="</html>";

   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();
}
</script>
</head>
<body>
<div id="block1">
<table border="1" >
</tr>
<th colspan="3">Block 1</th>
</tr>
<tr>
<th>1</th><th>XYZ</th><th>athock</th>
</tr>
</table>

</div>

<div id="block2">
    This is Block 2 content
</div>

<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>
<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>
</body>
</html>

SQL ORDER BY multiple columns

yes,the sorting proceed differently. in first scenario, orders based on column1 and in addition to that process further by sorting colmun2 based on column1 .. in second scenario ,it orders completely based on column 1 only... please proceed with a simple example...u will get quickly..

PostgreSQL database default location on Linux

The command pg_lsclusters (at least under Linux / Ubuntu) can be used to list the existing clusters and with it also the data directory:

Ver Cluster Port Status Owner    Data directory               Log file
9.5 main    5433 down   postgres /var/lib/postgresql/9.5/main /var/log/postgresql/postgresql-9.5-main.log
10  main    5432 down   postgres /var/lib/postgresql/10/main  /var/log/postgresql/postgresql-10-main.log

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

Best practice for using assert?

In addition to the other answers, asserts themselves throw exceptions, but only AssertionErrors. From a utilitarian standpoint, assertions aren't suitable for when you need fine grain control over which exceptions you catch.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Java output formatting for Strings

To answer your updated question you can do

String[] lines = ("Name =              Bob\n" +
        "Age =               27\n" +
        "Occupation =        Student\n" +
        "Status =            Single").split("\n");

for (String line : lines) {
    String[] parts = line.split(" = +");
    System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}

prints

Name =              Bob
Age =               27
Occupation =        Student
Status =            Single

Select records from today, this week, this month php mysql

Try using date and time functions (MONTH(), YEAR(), DAY(), MySQL Manual)

This week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW());

Last week:

SELECT * FROM jokes WHERE WEEKOFYEAR(date)=WEEKOFYEAR(NOW())-1;

How do you select a particular option in a SELECT element in jQuery?

Using jquery-2.1.4, I found the following answer to work for me:

$('#MySelectionBox').val(123).change();

If you have a string value try the following:

$('#MySelectionBox').val("extra thing").change();

Other examples did not work for me so that's why I'm adding this answer.

I found the original answer at: https://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu

Eclipse error: indirectly referenced from required .class files?

This is as likely a matter of Eclipse's getting confused as it is an actual error. I ignored the error and ran the web service whose endpointInterface it complained about, and it ran fine, except for having to deal with the dialog every time I wanted to run it. Just another opaque error that tells me nothing.

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

Spring @Value is not resolving to value from property file

Please note that if you have multiple application.properties files throughout your codebase, then try adding your value to the parent project's property file.

You can check your project's pom.xml file to identify what the parent project of your current project is.

Alternatively, try using environment.getProperty() instead of @Value.

SQL Server: use CASE with LIKE

One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.

You should create another table and store one value per row.

This will make your querying easier, and your database structure better.

select 
    case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end
from yourtable

Counting array elements in Python

If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:

import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2

This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.

import numpy as np
len(a) == np.shape(a)[0]

To get the number of elements in a multi-dimensional array of arbitrary shape:

import numpy as np
size = 1
for dim in np.shape(a): size *= dim

How do I check if the mouse is over an element in jQuery?

I needed something exactly as this (in a little more complex environment and the solution with a lot of 'mouseenters' and 'mouseleaves' wasnt working properly) so i created a little jquery plugin that adds the method ismouseover. It has worked pretty well so far.

//jQuery ismouseover  method
(function($){ 
    $.mlp = {x:0,y:0}; // Mouse Last Position
    function documentHandler(){
        var $current = this === document ? $(this) : $(this).contents();
        $current.mousemove(function(e){jQuery.mlp = {x:e.pageX,y:e.pageY}});
        $current.find("iframe").load(documentHandler);
    }
    $(documentHandler);
    $.fn.ismouseover = function(overThis) {  
        var result = false;
        this.eq(0).each(function() {  
                var $current = $(this).is("iframe") ? $(this).contents().find("body") : $(this);
                var offset = $current.offset();             
                result =    offset.left<=$.mlp.x && offset.left + $current.outerWidth() > $.mlp.x &&
                            offset.top<=$.mlp.y && offset.top + $current.outerHeight() > $.mlp.y;
        });  
        return result;
    };  
})(jQuery);

Then in any place of the document yo call it like this and it returns true or false:

$("#player").ismouseover()

I tested it on IE7+, Chrome 1+ and Firefox 4 and is working properly.

how to save DOMPDF generated content to file?

I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.

Give "write" permission to the directory you need to put the file. In your case it is the current directory.

Use "chmod" in linux.

Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.

Update built-in vim on Mac OS X

Don't overwrite the built-in Vim.

Instead, install it from source in a different location or via Homebrew or MacPorts in their default location then add this line to your .bashrc or .profile:

alias vim='/path/to/your/own/vim'

and/or change your $PATH so that it looks into its location before the default location.

The best thing to do, in my opinion, is to simply download the latest MacVim which comes with a very complete vim executable and use it in Terminal.app like so.

alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' # or something like that, YMMV

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

Calculating the distance between 2 points

If you are using System.Windows.Point data type to represent a point, you can use

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;

Update 2017-01-08:

  • Add reference to Microsoft documentation
  • Result of Point.Subtract is System.Windows.Vector and it has also property LengthSquared to save one sqrt calculation if you just need to compare distance.
  • Adding reference to WindowsBase assembly may be needed in your project
  • You can also use operators

Example with LengthSquared and operators

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;

How to get the anchor from the URL using jQuery?

jQuery style:

$(location).attr('hash');

How do you debug MySQL stored procedures?

The first and stable debugger for MySQL is in dbForge Studio for MySQL

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

objective-c is the primary language used.

i believe there is a mono touch framework that can be used with c#

Adobe also is working in some tools, one is this iPhone Packager which can utilize actionscript code

Spring @ContextConfiguration how to put the right location for the xml

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

How to find server name of SQL Server Management Studio

Open up SQL Server Configuration Manager (search for it in the Start menu). Click on SQL Server Services. The instance name of SQL Server is in parenthesis inline with SQL Server service. If it says MSSQLSERVER, then it's the default instance. To connect to it in Management Studio, just type . (dot) OR (local) and click Connect. If the instance name is different, then use .\[instance name] to connect to it (for example if the instance name is SQL2008, connect to .\SQL2008).

Also make sure SQL Server and SQL Server Browser services are running, otherwise you won't be able to connect.

Edit:

Here's a screenshot of how it looks like on my machine. In this case, I have two instances installed: SQLExpress and SQL2008.

enter image description here

What is the difference between <section> and <div>?

The section tag provides a more semantic syntax for html. div is a generic tag for a section. When you use section tag for appropriate content, it can be used for search engine optimization also. section tag also makes it easy for html parsing. for more info, refer. http://blog.whatwg.org/is-not-just-a-semantic

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

bootstrap multiselect get selected values

more efficient, due to less DOM lookups:

$('#multiselect1').multiselect({
    // ...
    onChange: function() {
        var selected = this.$select.val();
        // ...
    }
});

github markdown colspan

There is no way to do so. Either use an HTML table, or put the same text on several cells.

like this:

| Can Reorder | 2nd operation |2nd operation |2nd operation |
| :---: | --- |
|1st operation|Normal Load <br/>Normal Store| Volatile Load <br/>MonitorEnter|Volatile Store<br/> MonitorExit|
|Normal Load <br/> Normal Store| | | No|
|Volatile Load <br/> MonitorEnter| No|No|No|
|Volatile store <br/> MonitorExit| | No|No|

which looks like

HTML table

Comparing arrays in C#

Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:

var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);

In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual methods actually does, since it may well optimise for the special case of array values anyway!

How to replace all strings to numbers contained in each string in Notepad++?

In Notepad++ to replace, hit Ctrl+H to open the Replace menu.

Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines

value="4"
value="403"
value="200"
value="201"
value="116"
value="15"

using the .*"\d+" pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses ( and ), like that: .*"(\d+)". So now in your replacement you can simply write $1, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)", $1 will return the string value and $2 will return the number.

So by using:

Find: .*"(\d+)"

Replace: $1

It will return you

4
403
200
201
116
15

Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)" would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)

CSS div 100% height

I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:

myDiv {
    min-height: 100%;
    overflow-y: hidden;
    position: relative;
}

That should do the job!

Add event handler for body.onload by javascript within <body> part

Simply wrap the code you want to execute into the onload event of the window object:

window.onload = function(){ 
   // your code here
}

Difference between declaring variables before or in loop?

It is language dependent - IIRC C# optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation shebang each time.

How to set radio button checked as default in radiogroup?

    RadioGroup radioGroup = new RadioGroup(WvActivity.this);
    RadioButton radioBtn1 = new RadioButton(this);
    RadioButton radioBtn2 = new RadioButton(this);
    RadioButton radioBtn3 = new RadioButton(this);

    radioBtn1.setText("Less");
    radioBtn2.setText("Normal");
    radioBtn3.setText("More");


    radioGroup.addView(radioBtn1);
    radioGroup.addView(radioBtn2);
    radioGroup.addView(radioBtn3);

    radioGroup.check(radioBtn2.getId());

Working with a List of Lists in Java

The example provided by @tster shows how to create a list of list. I will provide an example for iterating over such a list.

Iterator<List<String>> iter = listOlist.iterator();
while(iter.hasNext()){
    Iterator<String> siter = iter.next().iterator();
    while(siter.hasNext()){
         String s = siter.next();
         System.out.println(s);
     }
}

How to clear textarea on click?

Here's a solution if you have dynamic data coming in from a database...
The 'data' variable represents database data.
If there is no data saved yet, the placeholder will show instead.
Once the user starts typing, the placeholder will disappear and they can then enter text.

Hope this helps someone!

// If data is NOT saved in the database
if (data == "") {
    var desc_text = "";
    var placeholder = "Please describe why";
// If data IS saved in the database
} else {
    var desc_text = data;
    var placeholder = "";
}

<textarea placeholder="'+placeholder+'">'+desc_text+'</textarea>

Git error: src refspec master does not match any error: failed to push some refs

One classic root cause for this message is:

  • when the repo has been initialized (git init lis4368/assignments),
  • but no commit has ever been made

Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

Try first to create a commit:

  • either by adding (git add .) then git commit -m "first commit"
    (assuming you have the right files in place to add to the index)
  • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

And then try git push -u origin master again.

See "Why do I need to explicitly push a new branch?" for more.

How to test if a list contains another list?

I think this one is fast...

def issublist(subList, myList, start=0):
    if not subList: return 0
    lenList, lensubList = len(myList), len(subList)
    try:
        while lenList - start >= lensubList:
            start = myList.index(subList[0], start)
            for i in xrange(lensubList):
                if myList[start+i] != subList[i]:
                    break
            else:
                return start, start + lensubList - 1
            start += 1
        return False
    except:
        return False

Converting JSON data to Java object

The easiest way is that you can use this softconvertvalue method which is a custom method in which you can convert jsonData into your specific Dto class.

Dto response = softConvertValue(jsonData, Dto.class);


public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
{
    ObjectMapper objMapper = new ObjectMapper();
    return objMapper
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .convertValue(fromValue, toValueType);
}

Accessing members of items in a JSONArray with Java

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

Is there a short cut for going back to the beginning of a file by vi editor?

Typing in 0% takes you to the beginning.

100% takes you to the end.

50% takes you half way.

Practical uses of different data structures

As per my understanding data structure is any data residing in memory of any electronic system that can be efficiently managed. Many times it is a game of memory or faster accessibility of data. In terms of memory again, there are tradeoffs done with the management of data based on cost to the company of that end product. Efficiently managed tells us how best the data can be accessed based on the primary requirement of the end product. This is a very high level explanation but data structures is a vast subjects. Most of the interviewers dive into data structures that they can afford to discuss in the interviews depending on the time they have, which are linked lists and related subjects.

Now, these data types can be divided into primitive, abstract, composite, based on the way they are logically constructed and accessed.

  • primitive data structures are basic building blocks for all data structures, they have a continuous memory for them: boolean, char, int, float, double, string.
  • composite data structures are data structures that are composed of more than one primitive data types.class, structure, union, array/record.
  • abstract datatypes are composite datatypes that have way to access them efficiently which is called as an algorithm. Depending on the way the data is accessed data structures are divided into linear and non linear datatypes. Linked lists, stacks, queues, etc are linear data types. heaps, binary trees and hash tables etc are non linear data types.

I hope this helps you dive in.

How can I select the record with the 2nd highest salary in database Oracle?

RANK and DENSE_RANK have already been suggested - depending on your requirements, you might also consider ROW_NUMBER():

select * from (
  select e.*, row_number() over (order by sal desc) rn from emp e
)
where rn = 2;

The difference between RANK(), DENSE_RANK() and ROW_NUMBER() boils down to:

  • ROW_NUMBER() always generates a unique ranking; if the ORDER BY clause cannot distinguish between two rows, it will still give them different rankings (randomly)
  • RANK() and DENSE_RANK() will give the same ranking to rows that cannot be distinguished by the ORDER BY clause
  • DENSE_RANK() will always generate a contiguous sequence of ranks (1,2,3,...), whereas RANK() will leave gaps after two or more rows with the same rank (think "Olympic Games": if two athletes win the gold medal, there is no second place, only third)

So, if you only want one employee (even if there are several with the 2nd highest salary), I'd recommend ROW_NUMBER().

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

The above answers get at the most fundamental aspects of the C++ memory model. In practice, most uses of std::atomic<> "just work", at least until the programmer over-optimizes (e.g., by trying to relax too many things).

There is one place where mistakes are still common: sequence locks. There is an excellent and easy-to-read discussion of the challenges at https://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf. Sequence locks are appealing because the reader avoids writing to the lock word. The following code is based on Figure 1 of the above technical report, and it highlights the challenges when implementing sequence locks in C++:

atomic<uint64_t> seq; // seqlock representation
int data1, data2;     // this data will be protected by seq

T reader() {
    int r1, r2;
    unsigned seq0, seq1;
    while (true) {
        seq0 = seq;
        r1 = data1; // INCORRECT! Data Race!
        r2 = data2; // INCORRECT!
        seq1 = seq;

        // if the lock didn't change while I was reading, and
        // the lock wasn't held while I was reading, then my
        // reads should be valid
        if (seq0 == seq1 && !(seq0 & 1))
            break;
    }
    use(r1, r2);
}

void writer(int new_data1, int new_data2) {
    unsigned seq0 = seq;
    while (true) {
        if ((!(seq0 & 1)) && seq.compare_exchange_weak(seq0, seq0 + 1))
            break; // atomically moving the lock from even to odd is an acquire
    }
    data1 = new_data1;
    data2 = new_data2;
    seq = seq0 + 2; // release the lock by increasing its value to even
}

As unintuitive as it seams at first, data1 and data2 need to be atomic<>. If they are not atomic, then they could be read (in reader()) at the exact same time as they are written (in writer()). According to the C++ memory model, this is a race even if reader() never actually uses the data. In addition, if they are not atomic, then the compiler can cache the first read of each value in a register. Obviously you wouldn't want that... you want to re-read in each iteration of the while loop in reader().

It is also not sufficient to make them atomic<> and access them with memory_order_relaxed. The reason for this is that the reads of seq (in reader()) only have acquire semantics. In simple terms, if X and Y are memory accesses, X precedes Y, X is not an acquire or release, and Y is an acquire, then the compiler can reorder Y before X. If Y was the second read of seq, and X was a read of data, such a reordering would break the lock implementation.

The paper gives a few solutions. The one with the best performance today is probably the one that uses an atomic_thread_fence with memory_order_relaxed before the second read of the seqlock. In the paper, it's Figure 6. I'm not reproducing the code here, because anyone who has read this far really ought to read the paper. It is more precise and complete than this post.

The last issue is that it might be unnatural to make the data variables atomic. If you can't in your code, then you need to be very careful, because casting from non-atomic to atomic is only legal for primitive types. C++20 is supposed to add atomic_ref<>, which will make this problem easier to resolve.

To summarize: even if you think you understand the C++ memory model, you should be very careful before rolling your own sequence locks.

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

How can I save an image with PIL?

I know that this is old, but I've found that (while using Pillow) opening the file by using open(fp, 'w') and then saving the file will work. E.g:

with open(fp, 'w') as f:
    result.save(f)

fp being the file path, of course.

How to convert a string to ASCII

.NET stores all strings as a sequence of UTF-16 code units. (This is close enough to "Unicode characters" for most purposes.)

Fortunately for you, Unicode was designed such that ASCII values map to the same number in Unicode, so after you've converted each character to an integer, you can just check whether it's in the ASCII range. Note that you can use an implicit conversion from char to int - there's no need to call a conversion method:

string text = "Here's some text including a \u00ff non-ASCII character";
foreach (char c in text)
{
    int unicode = c;
    Console.WriteLine(unicode < 128 ? "ASCII: {0}" : "Non-ASCII: {0}", unicode);
}

How to Correctly handle Weak Self in Swift Blocks with Arguments

If self could be nil in the closure use [weak self].

If self will never be nil in the closure use [unowned self].

If it's crashing when you use [unowned self] I would guess that self is nil at some point in that closure, which is why you had to go with [weak self] instead.

I really liked the whole section from the manual on using strong, weak, and unowned in closures:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

Note: I used the term closure instead of block which is the newer Swift term:

Difference between block (Objective C) and closure (Swift) in ios

Regular expression for matching HH:MM time format

The best would be for HH:MM without taking any risk.

^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

Waiting till the async task finish its work

wait until this call is finish its executing

You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

To get result back in UI Thread start AsyncTask as :

String str_result= new RunInBackGround().execute().get();

Exception: Unexpected end of ZLIB input stream

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

Here's the correct code (in Java);

package test;

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

public class GZipTest {

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

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

How to ping a server only once from within a batch file?

The only thing you need to think about in this case is, in which directory you are on your computer. Your command line window shows C:\users\rei0d\desktop\ as your current directory.

So the only thing you really need to do is:
Remove the desktop by "going up" with the command cd ...

So the complete command would be:

cd ..
ping XXX.XXX.XXX.XXX -t

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I'm aware that this question is a bit old, but I consider that my small update could help other programmers.

I didn't want to modify WhoIsRich's answer because it's really great, but I adapted it to fulfill my needs:

  1. If the Automatically Detect Settings is checked then uncheck it.
  2. If the Automatically Detect Settings is unchecked then check it.

    On Error Resume Next
    
    Set oReg   = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
    sKeyPath   = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
    sValueName = "DefaultConnectionSettings"
    
    ' Get registry value where each byte is a different setting.
    oReg.GetBinaryValue &H80000001, sKeyPath, sValueName, bValue
    
    ' Check byte to see if detect is currently on.
    If (bValue(8) And 8) = 8 Then
        ' To change the value to Off.
        bValue(8) = bValue(8) And Not 8
    ' Check byte to see if detect is currently off.
    ElseIf (bValue(8) And 8) = 0 Then
        ' To change the value to On.
        bValue(8) = bValue(8) Or 8
    End If
    
    'Write back settings value
    oReg.SetBinaryValue &H80000001, sKeyPath, sValueName, bValue
    
    Set oReg = Nothing
    

Finally, you only need to save it in a .VBS file (VBScript) and run it.

vbscript

Remove Identity from a column in a table

ALTER TABLE TABLE_NAME MODIFY (COLUMN_NAME DROP IDENTITY);

How to fix: Error device not found with ADB.exe

If you installed Eclipse have Android SDK, go to DDMS. If the list device display "?????????"

you do adb kill-server and then adb start-server.

Please make sure you install USB driver and enable debug mode.

How to debug in Django, the good way?

I highly recommend epdb (Extended Python Debugger).

https://bitbucket.org/dugan/epdb

One thing I love about epdb for debugging Django or other Python webservers is the epdb.serve() command. This sets a trace and serves this on a local port that you can connect to. Typical use case:

I have a view that I want to go through step-by-step. I'll insert the following at the point I want to set the trace.

import epdb; epdb.serve()

Once this code gets executed, I open a Python interpreter and connect to the serving instance. I can analyze all the values and step through the code using the standard pdb commands like n, s, etc.

In [2]: import epdb; epdb.connect()
(Epdb) request
<WSGIRequest
path:/foo,
GET:<QueryDict: {}>, 
POST:<QuestDict: {}>,
...
>
(Epdb) request.session.session_key
'i31kq7lljj3up5v7hbw9cff0rga2vlq5'
(Epdb) list
 85         raise some_error.CustomError()
 86 
 87     # Example login view
 88     def login(request, username, password):
 89         import epdb; epdb.serve()
 90  ->     return my_login_method(username, password)
 91
 92     # Example view to show session key
 93     def get_session_key(request):
 94         return request.session.session_key
 95

And tons more that you can learn about typing epdb help at any time.

If you want to serve or connect to multiple epdb instances at the same time, you can specify the port to listen on (default is 8080). I.e.

import epdb; epdb.serve(4242)

>> import epdb; epdb.connect(host='192.168.3.2', port=4242)

host defaults to 'localhost' if not specified. I threw it in here to demonstrate how you can use this to debug something other than a local instance, like a development server on your local LAN. Obviously, if you do this be careful that the set trace never makes it onto your production server!

As a quick note, you can still do the same thing as the accepted answer with epdb (import epdb; epdb.set_trace()) but I wanted to highlight the serve functionality since I've found it so useful.

Using classes with the Arduino

I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

class AMLed
{
    private:
          uint8_t _ledPin;
          long _turnOffTime;

    public:
          AMLed(uint8_t pin);
          void setOn();
          void setOff();
          // Turn the led on for a given amount of time (relies
          // on a call to check() in the main loop()).
          void setOnForTime(int millis);
          void check();
};

And here is the main source

AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
    pinMode(_ledPin, OUTPUT);
}

void AMLed::setOn()
{
    digitalWrite(_ledPin, HIGH);
}

void AMLed::setOff()
{
    digitalWrite(_ledPin, LOW);
}

void AMLed::setOnForTime(int p_millis)
{
    _turnOffTime = millis() + p_millis;
    setOn();
}

void AMLed::check()
{
    if (_turnOffTime != 0 && (millis() > _turnOffTime))
    {
        _turnOffTime = 0;
        setOff();
    }
}

It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

To use, I simply do something like this in the .pde file:

#include "AM_Led.h"

#define TIME_LED    12   // The port for the LED

AMLed test(TIME_LED);

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

Given you've set up a git daemon on <url> and an empty repository:

cd <localdir>
git init
git add .
git commit -m 'message'
git remote add origin <url>
git push -u origin master

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

Getting selected value of a combobox

Try this:

int selectedIndex = comboBox1.SelectedIndex;
comboBox1.SelectedItem.ToString();
int selectedValue = (int)comboBox1.Items[selectedIndex];

How do you synchronise projects to GitHub with Android Studio?

Android Studio 3.0

I love how easy this is in Android Studio.

1. Enter your GitHub login info

In Android Studio go to File > Settings > Version Control > GitHub. Then enter your GitHub username and password. (You only have to do this step once. For future projects you can skip it.)

enter image description here

2. Share your project

With your Android Studio project open, go to VCS > Import into Version Control > Share Project on GitHub.

Then click Share and OK.

enter image description here

That's all!

Simple function to sort an array of objects

My solution for similar sort problem using ECMA 6

_x000D_
_x000D_
var library = [_x000D_
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, _x000D_
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},_x000D_
        {name: 'Asad', course:'SWE', courseID: 'cs542'},_x000D_
];_x000D_
_x000D_
const sorted_by_name = library.sort( (a,b) => a.name > b.name );_x000D_
_x000D_
for(let k in sorted_by_name){_x000D_
    console.log(sorted_by_name[k]);_x000D_
}
_x000D_
_x000D_
_x000D_

How can we dynamically allocate and grow an array

You can do something like this:

String [] wordList;
int wordCount = 0;
int occurrence = 1;
int arraySize = 100;
int arrayGrowth = 50;
wordList = new String[arraySize];
while ((strLine = br.readLine()) != null)   {
     // Store the content into an array
     Scanner s = new Scanner(strLine);
     while(s.hasNext()) {
         if (wordList.length == wordCount) {
              // expand list
              wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth);
         }
         wordList[wordCount] = s.next();
         wordCount++;
     } 
}

Using java.util.Arrays.copyOf(String[]) is basically doing the same thing as:

if (wordList.length == wordCount) {
    String[] temp = new String[wordList.length + arrayGrowth];
    System.arraycopy(wordList, 0, temp, 0, wordList.length);
    wordList = temp;
}

except it is one line of code instead of three. :)