Programs & Examples On #Numerical computing

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

Eclipse: How do I add the javax.servlet package to a project?

Right click on your project -> properties -> build path. Add to your build path jar file(s) that have the javax.servlet implemenation. Ite depends on your servlet container or application server what file(s) you need to include, so search for that information.

How to change active class while click to another link in bootstrap use jquery?

$(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
        $(this).removeClass("active");
    }
    $(this).addClass("active");
});

This is what I came up with. It checks if the "li" element has the class of active, if it doesn't it skips the remove class part. I'm a bit late to the party, but hope this helps. :)

What is the difference between require and require-dev sections in composer.json?

From the composer site (it's clear enough)

require#

Lists packages required by this package. The package will not be installed unless those requirements can be met.

require-dev (root-only)#

Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev part would be ignored.

Also check this answer posted by the author and this post as well.

Calling UserForm_Initialize() in a Module

SOLUTION After all this time, I managed to resolve the problem.

In Module: UserForms(Name).Userform_Initialize

This method works best to dynamically init the current UserForm

Python coding standards/best practices

I follow the PEP8, it is a great piece of coding style.

How to find whether a number belongs to a particular range in Python?

No, you can't do that. range() expects integer arguments. If you want to know if x is inside this range try some form of this:

print 0.0 <= x <= 0.5

Be careful with your upper limit. If you use range() it is excluded (range(0, 5) does not include 5!)

SSRS - Checking whether the data is null

try like this

= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "",  FormatNumber(  MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )

How to play .wav files with java

A solution without java reflection DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat)

Java reflection decrease performance. to run: java playsound absoluteFilePathTo/file.wav

import javax.sound.sampled.*;
import java.io.*;
public class playsound {

    public static void main (String args[]) throws Exception {
        playSound (args[0]);
    }

    public static void playSound () throws Exception {
        AudioInputStream 
        audioStream = AudioSystem.getAudioInputStream(new File (filename));

        int BUFFER_SIZE = 128000;
        AudioFormat audioFormat = null;
        SourceDataLine sourceLine = null;

        audioFormat = audioStream.getFormat();

        sourceLine = AudioSystem.getSourceDataLine(audioFormat);
        sourceLine.open(audioFormat);
        sourceLine.start();

        int nBytesRead = 0;
        byte[] abData = new byte[BUFFER_SIZE];
        while (nBytesRead != -1) {
            try {
                nBytesRead = 
                audioStream.read(abData, 0, abData.length);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (nBytesRead >= 0) {
                int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
            }
        }

        sourceLine.drain();
        sourceLine.close();
    }

}

Multiline for WPF TextBox

Here is a sample XAML that will allow TextBox to accept multiline text and it uses its own scrollbars:

<TextBox
Height="200"
Width="500"
TextWrapping="Wrap"
AcceptsReturn="True"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"/>

How to enable DataGridView sorting when user clicks on the column header?

your data grid needs to be bound to a sortable list in the first place.

Create this event handler:

    void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        //Add this as an event on DataBindingComplete
        DataGridView dataGridView = sender as DataGridView;
        if (dataGridView == null)
        {
            var ex = new InvalidOperationException("This event is for a DataGridView type senders only.");
            ex.Data.Add("Sender type", sender.GetType().Name);
            throw ex;
        }

        foreach (DataGridViewColumn column in dataGridView.Columns)
            column.SortMode = DataGridViewColumnSortMode.Automatic;
    }

And initialize the event of each of your datragrids like this:

        dataGridView1.DataBindingComplete += MakeColumnsSortable_DataBindingComplete;

How to get length of a list of lists in python

The method len() returns the number of elements in the list.

 list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
    print "First list length : ", len(list1)
    print "Second list length : ", len(list2)

When we run above program, it produces the following result -

First list length : 3 Second list length : 2

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

Single Form Hide on Startup

This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.

More here: http://code.msdn.microsoft.com/TheNotifyIconExample

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

Twitter Bootstrap scrollable table rows and fixed header

Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)

  <table id="tableHeader" class="table" style="table-layout:fixed">
        <thead>
            <tr>
                <th>Col1</th>
                ...
            </tr>
        </thead>
  </table>
  <div style="overflow-y:auto;">
    <table id="tableData" class="table table-condensed" style="table-layout:fixed">
        <tbody>
            <tr>
                <td>data</td>
                ...
            </tr>
        </tbody>
    </table>
 </div>

Demo JSFiddle

The content table div needs overflow-y:auto, for vertical scroll bars. Had to use table-layout:fixed, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.

Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.

    // ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
    $(function () {

        //copy width of header cells to match width of cells with data
        //so they line up properly
        var tdHeader = document.getElementById("tableHeader").rows[0].cells;
        var tdData = document.getElementById("tableData").rows[0].cells;

        for (var i = 0; i < tdData.length; i++)
            tdHeader[i].style.width = tdData[i].offsetWidth + 'px';

    });

String.Format for Hex

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

Proxies with Python 'Requests' module

i just made a proxy graber and also can connect with same grabed proxy without any input here is :

#Import Modules

from termcolor import colored
from selenium import webdriver
import requests
import os
import sys
import time

#Proxy Grab

options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.sslproxies.org/")
tbody = driver.find_element_by_tag_name("tbody")
cell = tbody.find_elements_by_tag_name("tr")
for column in cell:

        column = column.text.split(" ")
        print(colored(column[0]+":"+column[1],'yellow'))
driver.quit()
print("")

os.system('clear')
os.system('cls')

#Proxy Connection

print(colored('Getting Proxies from graber...','green'))
time.sleep(2)
os.system('clear')
os.system('cls')
proxy = {"http": "http://"+ column[0]+":"+column[1]}
url = 'https://mobile.facebook.com/login'
r = requests.get(url,  proxies=proxy)
print("")
print(colored('Connecting using proxy' ,'green'))
print("")
sts = r.status_code

View google chrome's cached pictures

You can make a bookmark with this as the url:

javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
    var ca = cached_anchors[i];
    if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
        var a = document.createElement('a');
        a.href = ca.innerHTML;
        a.target = '_blank';

        var img = document.createElement('img');
        img.src = ca.innerHTML;
        img.style.maxHeight = '100px';

        a.appendChild(img);
        document.getElementsByTagName('body')[0].appendChild(a);
    }
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);

Then just go to chrome://cache and then click your bookmark and it'll show you all the images.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

jsPDF multi page PDF with HTML renderer

         html2canvas(element[0], {
                    onrendered: function (canvas) {
                        pages = Math.ceil(element[0].clientHeight / 1450);
                        for (i = 0; i <= pages; i += 1) {
                            if (i > 0) {
                                pdf.addPage();
                            }
                            srcImg = canvas;
                            sX = 0;
                            sY = 1450 * i;
                            sWidth = 1100;
                            sHeight = 1450;
                            dX = 0;
                            dY = 0;
                            dWidth = 1100;
                            dHeight = 1450;
                            window.onePageCanvas = document.createElement("canvas");
                            onePageCanvas.setAttribute('width', 1100);
                            onePageCanvas.setAttribute('height', 1450);
                            ctx = onePageCanvas.getContext('2d');
                            ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
                            canvasDataURL = onePageCanvas.toDataURL("image/png");
                            width = onePageCanvas.width;
                            height = onePageCanvas.clientHeight;
                            pdf.setPage(i + 1);
                            pdf.addImage(canvasDataURL, 'PNG', 35, 30, (width * 0.5), (height * 0.5));
                        }
                        pdf.save('testfilename.pdf');
                    }
                });

How to solve Permission denied (publickey) error when using Git?

The easiest solution to this, when you are trying to push to a repository with a different username is:

 git remote set-url origin https://[email protected]/USERNAME/PROJECTNAME.git

JavaScript variable number of arguments to function

Be aware that passing an Object with named properties as Ken suggested adds the cost of allocating and releasing the temporary object to every call. Passing normal arguments by value or reference will generally be the most efficient. For many applications though the performance is not critical but for some it can be.

How to disable an input type=text?

If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly attribute (or disabled, if you want to remove it from the form submission as well) to the <input>, like this:

<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />

Entity Framework 5 Updating a Record

There are some really good answers given already, but I wanted to throw in my two cents. Here is a very simple way to convert a view object into a entity. The simple idea is that only the properties that exist in the view model get written to the entity. This is similar to @Anik Islam Abhi's answer, but has null propagation.

public static T MapVMUpdate<T>(object updatedVM, T original)
{
    PropertyInfo[] originalProps = original.GetType().GetProperties();
    PropertyInfo[] vmProps = updatedVM.GetType().GetProperties();
    foreach (PropertyInfo prop in vmProps)
    {
        PropertyInfo projectProp = originalProps.FirstOrDefault(x => x.Name == prop.Name);
        if (projectProp != null)
        {
            projectProp.SetValue(original, prop.GetValue(updatedVM));
        }
    }
    return original;
}

Pros

  • Views don't need to have all the properties of the entity.
  • You never have to update code when you add remove a property to a view.
  • Completely generic

Cons

  • 2 hits on the database, one to load the original entity, and one to save it.

To me the simplicity and low maintenance requirements of this approach outweigh the added database call.

How do I get the current mouse screen coordinates in WPF?

Do you want coordinates relative to the screen or the application?

If it's within the application just use:

Mouse.GetPosition(Application.Current.MainWindow);

If not, I believe you can add a reference to System.Windows.Forms and use:

System.Windows.Forms.Control.MousePosition;

How do I open the "front camera" on the Android platform?

public void surfaceCreated(SurfaceHolder holder) {
    try {
        mCamera = Camera.open();
        mCamera.setDisplayOrientation(90);
        mCamera.setPreviewDisplay(holder);

        Camera.Parameters p = mCamera.getParameters();
        p.set("camera-id",2);
        mCamera.setParameters(p);   
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

The program can't start because libgcc_s_dw2-1.dll is missing

If you are wondering where you can download the shared library (although this will not work on your client's devices unless you include the dll) here is the link: https://de.osdn.net/projects/mingw/downloads/72215/libgcc-9.2.0-1-mingw32-dll-1.tar.xz/

console.log showing contents of array object

Seems like Firebug or whatever Debugger you are using, is not initialized properly. Are you sure Firebug is fully initialized when you try to access the console.log()-method? Check the Console-Tab (if it's set to activated).

Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.

Forbidden: You don't have permission to access / on this server, WAMP Error

1.

first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)

2.

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Order Allow,Deny
      Allow from all

if "Allow from all" line not work for your then use "Require all granted" then it will work for you.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80

3. Dont forget to restart All Services of Wamp or Apache after making this change

AngularJS Error: $injector:unpr Unknown Provider

I got this error writing a Jasmine unit test. I had the line:

angular.injector(['myModule'])

It needed to be:

angular.injector(['ng', 'myModule'])

How to set image for bar button with swift?

Initialize barbuttonItem like following:

let pauseButton = UIBarButtonItem(image: UIImage(named: "big"),
                                  style: .plain,
                                  target: self,
                                  action: #selector(PlaybackViewController.pause))

How do you read CSS rule values with JavaScript?

I made a similar helper function which shows the unneeded styles for this page. appends a <div> to the body listing all styles that where not used.

(to be used with the firebug console)

(function getStyles(){var CSSrules,allRules,CSSSheets, unNeeded, currentRule;
CSSSheets=document.styleSheets;

for(j=0;j<CSSSheets.length;j++){
for(i=0;i<CSSSheets[j].cssRules.length;i++){
    currentRule = CSSSheets[j].cssRules[i].selectorText;

    if(!document.querySelectorAll(currentRule).length){ 
       unNeeded+=CSSSheets[j].cssRules[i].cssText+"<br>"; 
  }       
 }
}

docBody=document.getElementsByTagName("body")[0];
allRulesContainer=document.createElement("div");
docBody.appendChild(allRulesContainer);
allRulesContainer.innerHTML=unNeeded+isHover;
return false
})()

Display List in a View MVC

Your action method considers model type asList<string>. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>. You can solve this problem with changing the model in your view to List<string>.

But, the best approach would be to return IEnumerable<Standings.Models.Teams> as a model from your action method. Then you haven't to change model type in your view.

But, in my opinion your models are not correctly implemented. I suggest you to change it as:

public class Team
{
    public int Position { get; set; }
    public string HomeGround {get; set;}
    public string NickName {get; set;}
    public int Founded { get; set; }
    public string Name { get; set; }
}

Then you must change your action method as:

public ActionResult Index()
{
    var model = new List<Team>();

    model.Add(new Team { Name = "MU"});
    model.Add(new Team { Name = "Chelsea"});
    ...

    return View(model);
}

And, your view:

@model IEnumerable<Standings.Models.Team>

@{
     ViewBag.Title = "Standings";
}

@foreach (var item in Model)
{
    <div>
        @item.Name
        <hr />
    </div>
}

Intellij idea subversion checkout error: `Cannot run program "svn"`

Under settings ->verison control -> Subversion, uncheck use command line client. It will work.

How to check if a column exists in a datatable

DataColumnCollection col = datatable.Columns;        
if (!columns.Contains("ColumnName1"))
{
   //Column1 Not Exists
}

if (columns.Contains("ColumnName2"))
{
   //Column2 Exists
}

Android update activity UI from service

I would recommend checking out Otto, an EventBus tailored specifically to Android. Your Activity/UI can listen to events posted on the Bus from the Service, and decouple itself from the backend.

Getting parts of a URL (Regex)

Propose a much more readable solution (in Python, but applies to any regex):

def url_path_to_dict(path):
    pattern = (r'^'
               r'((?P<schema>.+?)://)?'
               r'((?P<user>.+?)(:(?P<password>.*?))?@)?'
               r'(?P<host>.*?)'
               r'(:(?P<port>\d+?))?'
               r'(?P<path>/.*?)?'
               r'(?P<query>[?].*?)?'
               r'$'
               )
    regex = re.compile(pattern)
    m = regex.match(path)
    d = m.groupdict() if m is not None else None

    return d

def main():
    print url_path_to_dict('http://example.example.com/example/example/example.html')

Prints:

{
'host': 'example.example.com', 
'user': None, 
'path': '/example/example/example.html', 
'query': None, 
'password': None, 
'port': None, 
'schema': 'http'
}

Cookies vs. sessions

Basic ideas to distinguish between those two.

Session:

  1. IDU is stored on server (i.e. server-side)
  2. Safer (because of 1)
  3. Expiration can not be set, session variables will be expired when users close the browser. (nowadays it is stored for 24 minutes as default in php)

Cookies:

  1. IDU is stored on web-browser (i.e. client-side)
  2. Not very safe, since hackers can reach and get your information (because of 1)
  3. Expiration can be set (see setcookies() for more information)

Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.

Cookies is preferred when you need to store long-term information/values, such as user's account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can't think of many examples for cookies since it isn't adopted in most of the situations.

Scanner is skipping nextLine() after using next() or nextFoo()?

sc.nextLine() is better as compared to parsing the input. Because performance wise it will be good.

CSS to stop text wrapping under image

setting display:flexfor the text worked for me.

How to install SQL Server Management Studio 2012 (SSMS) Express?

Easiest way to install MSSQL 2012 MS SQL INSTALLATION

Here i am showing the easiest way to install ms sql 2012.

My opinion is the installation will be easier with windows 8.1 rather than windows 7.

This is my personnal opinion only.

We can install in windows 7 as well.

The steps to be followed:

Download any one of the link using the following URL

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

SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe

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

SQLEXPRWT_x86_ENU.exe or SQLEXPRWT_x64_ENU.exe

Right click on .exe file and run it

We should leave everything default while installing.

During installation, there will be 2 options:

1)If you are New user,then click on new sql-server stand alone application.

2)If you have already MS SQL application then you can upgrade by using the other option.

Then accept the Licence terms and click Next.

Now you will move on to Product Updates and press next then Setup support rules.

After this Feature selection.According to me we can check all the boxes except localdb.

Next it will take you to Instance Configuration where you should select Named Instance as

"SQLEXPRESS".

Then go to Server Configuration and press next.

Now Database engine configuration:

Authentication Mode:we can click on any one that is windows authentication mode or mixed.

Windows authentication mode (default for windows).

Mixed authentication mode:then should create username and password.

Then move on Error reporting,we can move further by clicking next to install process.

Finally we can see the Complete windows by showing the products added .

We can close and run the MSSQL server.

I hope it's useful.

Regards

Ramya

Cannot install Aptana Studio 3.6 on Windows

Most of us will run into this problem. This can be solved by installing NodeJS from http://go.aptana.com/installer_nodejs_windows. My Aptana installation installed the GIT automatically but if you still find trouble then I would suggest to install the GIT latest version yourself and rerun the Aptana installation.

How do I start a program with arguments when debugging?

My suggestion would be to use Unit Tests.

In your application do the following switches in Program.cs:

#if DEBUG
    public class Program
#else
    class Program
#endif

and the same for static Main(string[] args).

Or alternatively use Friend Assemblies by adding

[assembly: InternalsVisibleTo("TestAssembly")]

to your AssemblyInfo.cs.

Then create a unit test project and a test that looks a bit like so:

[TestClass]
public class TestApplication
{
    [TestMethod]
    public void TestMyArgument()
    {
        using (var sw = new StringWriter())
        {
            Console.SetOut(sw); // this makes any Console.Writes etc go to sw

            Program.Main(new[] { "argument" });

            var result = sw.ToString();

            Assert.AreEqual("expected", result);
        }
    }
}

This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.

Android Google Maps v2 - set zoom level for myLocation

Slightly different solution than HeatfanJohn's, where I change the zoom relatively to the current zoom level:

// Zoom out just a little
map.animateCamera(CameraUpdateFactory.zoomTo(map.getCameraPosition().zoom - 0.5f));

Transpose list of lists

Maybe not the most elegant solution, but here's a solution using nested while loops:

def transpose(lst):
    newlist = []
    i = 0
    while i < len(lst):
        j = 0
        colvec = []
        while j < len(lst):
            colvec.append(lst[j][i])
            j = j + 1
        newlist.append(colvec)
        i = i + 1
    return newlist

How to push object into an array using AngularJS

_x000D_
_x000D_
  var app = angular.module('myApp', []);_x000D_
        app.controller('myCtrl', function ($scope) {_x000D_
_x000D_
            //Comments object having reply oject_x000D_
            $scope.comments = [{ comment: 'hi', reply: [{ comment: 'hi inside commnet' }, { comment: 'hi inside commnet' }] }];_x000D_
_x000D_
            //push reply_x000D_
            $scope.insertReply = function (index, reply) {_x000D_
                $scope.comments[index].reply.push({ comment: reply });_x000D_
            }_x000D_
_x000D_
            //push commnet_x000D_
            $scope.newComment = function (comment) {_x000D_
                $scope.comments.push({ comment:comment, reply: [] });_x000D_
            }_x000D_
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
        <!--Comment section-->_x000D_
        <ul ng-repeat="comment in comments track by $index" style="background: skyblue; padding: 10px;">_x000D_
            <li>_x000D_
                <b>Comment {{$index}} : </b>_x000D_
                <br>_x000D_
                {{comment.comment}}_x000D_
                <!--Reply section-->_x000D_
                    <ul ng-repeat="reply in comment.reply track by $index">_x000D_
                        <li><i>Reply {{$index}} :</i><br>_x000D_
                            {{reply.comment}}</li>_x000D_
                    </ul>_x000D_
                <!--End reply section-->_x000D_
                <input type="text" ng-model="reply" placeholder=" Write your reply." /><a href="" ng-click="insertReply($index,reply)">Reply</a>_x000D_
            </li>_x000D_
        </ul>_x000D_
        <!--End comment section -->_x000D_
            _x000D_
_x000D_
        <!--Post your comment-->_x000D_
        <b>New comment</b>_x000D_
        <input type="text" placeholder="Your comment" ng-model="comment" />_x000D_
        <a href="" ng-click="newComment(comment)">Post </a>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Angular window resize event

I know this was asked a long time ago, but there is a better way to do this now! I'm not sure if anyone will see this answer though. Obviously your imports:

import { fromEvent, Observable, Subscription } from "rxjs";

Then in your component:

resizeObservable$: Observable<Event>
resizeSubscription$: Subscription

ngOnInit() {
    this.resizeObservable$ = fromEvent(window, 'resize')
    this.resizeSubscription$ = this.resizeObservable$.subscribe( evt => {
      console.log('event: ', evt)
    })
}

Then be sure to unsubscribe on destroy!

ngOnDestroy() {
    this.resizeSubscription$.unsubscribe()
}

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

@NaturalBornCamper,

Nice code! Here is a clean-cut code function for such process!

function get_raw_facebook_avatar_url($uid)
{
    $array = get_headers('https://graph.facebook.com/'.$uid.'/picture?type=large', 1);
    return (isset($array['Location']) ? $array['Location'] : FALSE);
}

This will return the raw Facebook avatar image URL. Feel free to do whatever you want with it then!

What is the alternative for ~ (user's home directory) on Windows command prompt?

If you want a shorter version of Jay's you could try

    set usr=%userprofile%
    cd %usr%

Or you could even use %u% if you wanted to. It saves some keystrokes anyway.

Calling functions in a DLL from C++

There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.

CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.

Here is an simple example on how this is done.

Step 1: Define the function in the export.h file.

int WINAPI IsolatedFunction(const char *title, const char *test);

Step 2: Define the function in the export.cpp file.

#include <windows.h>

int WINAPI IsolatedFunction(const char *title, const char *test)
{
    MessageBox(0, title, test, MB_OK);
    return 1;
}

Step 3: Define the function as an export in the export.def defintion file.

EXPORTS    IsolatedFunction          @1

Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.

The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.

Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.

Step 6: Call the IsolatedFunction function from within the Test application as shown below.

#include "stdafx.h"

// get the function prototype of the imported function
#include "../export/export.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // call the imported function found in the dll
    int result = IsolatedFunction("hello", "world");

    return 0;
}

How to read barcodes with the camera on Android?

With Google Firebase ML Kit's barcode scanning API, you can read data encoded using most standard barcode formats.

https://firebase.google.com/docs/ml-kit/read-barcodes?authuser=0

You can follow this link to read barcodes efficiently.

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

In Android EditText, how to force writing uppercase?

In kotlin, in .kt file make changes:

edit_text.filters = edit_text.filters + InputFilter.AllCaps()

Use synthetic property for direct access of widget with id. And in XML, for your edit text add a couple of more flag as:

<EditText
    android:id="@+id/edit_text_qr_code"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ...other attributes...
    android:textAllCaps="true"
    android:inputType="textCapCharacters"
    />

This will update the keyboard as upper case enabled.

what is the unsigned datatype?

In C and C++

unsigned = unsigned int (Integer type)
signed   = signed int (Integer type)

An unsigned integer containing n bits can have a value between 0 and (2^n-1) , which is 2^n different values.

An unsigned integer is either positive or zero.

Signed integers are stored in a computer using 2's complement.

Is there a limit on how much JSON can hold?

It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings.

Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: https://stackoverflow.com/a/1151993/61569

Checking that a List is not empty in Hamcrest

Create your own custom IsEmpty TypeSafeMatcher:

Even if the generics problems are fixed in 1.3 the great thing about this method is it works on any class that has an isEmpty() method! Not just Collections!

For example it will work on String as well!

/* Matches any class that has an <code>isEmpty()</code> method
 * that returns a <code>boolean</code> */ 
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
    @Factory
    public static <T> Matcher<T> empty()
    {
        return new IsEmpty<T>();
    }

    @Override
    protected boolean matchesSafely(@Nonnull final T item)
    {
        try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
        catch (final NoSuchMethodException e) { return false; }
        catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}

How to get current screen width in CSS?

this can be achieved with the css calc() operator

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
        zoom:calc(100% / 480);
    }
}

The simplest way to comma-delimit a list?

Based on Java's List toString implementation:

Iterator i = list.iterator();
for (;;) {
  sb.append(i.next());
  if (! i.hasNext()) break;
  ab.append(", ");
}

It uses a grammar like this:

List --> (Item , )* Item

By being last-based instead of first-based, it can check for skip-comma with the same test to check for end-of-list. I think this one is very elegant, but I'm not sure about clarity.

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

2 month old thread, but better late than never! On 10.6, I have my webserver documents folder set to:

owner:root
group:_www
permission:755

_www is the user that runs apache under Mac OS X. I then added an ACL to allow full permissions to the Administrators group. That way, I can still make any changes with my admin user without having to authenticate as root. Also, when I want to allow the webserver to write to a folder, I can simply chmod to 775, leaving everyone other than root:_www with only read/execute permissions (excluding any ACLs that I have applied)

How to insert blank lines in PDF?

I had to add blank lines after a table and I manage it adding many divs as I need it with a css style with padding-top set it up, like this. I've used a template engine (underscore) to loop through the number of lines I need to add.

 <% var maxRow = 30; var pos = items.models.length; %>
 <% for( pos; pos < maxRow; pos++ ){ %>
       <div class="blankRow"></div>
 <% }; %>

My css file:

 .blankRow:{ padding-top: 15px;}

AngularJS Folder Structure

I like this entry about angularjs structure

It's written by one of the angularjs developers, so should give you a good insight

Here's an excerpt:

root-app-folder
+-- index.html
+-- scripts
¦   +-- controllers
¦   ¦   +-- main.js
¦   ¦   +-- ...
¦   +-- directives
¦   ¦   +-- myDirective.js
¦   ¦   +-- ...
¦   +-- filters
¦   ¦   +-- myFilter.js
¦   ¦   +-- ...
¦   +-- services
¦   ¦   +-- myService.js
¦   ¦   +-- ...
¦   +-- vendor
¦   ¦   +-- angular.js
¦   ¦   +-- angular.min.js
¦   ¦   +-- es5-shim.min.js
¦   ¦   +-- json3.min.js
¦   +-- app.js
+-- styles
¦   +-- ...
+-- views
    +-- main.html
    +-- ...

keycode 13 is for which key

_x000D_
_x000D_
function myFunction(event) {
  var x = event.charCode;
  document.getElementById("demo").innerHTML = "The Unicode value is: " + x;
}
_x000D_
<p>Keycode 13 is: </p> 
<button>Enter</button>
<p>Press a key on the keyboard in the input field to get the Unicode character code of the pressed key.</p>
<b>You can test in below</b>

<input type="text" size="40" onkeypress="myFunction(event)">

<p id="demo"></p>

<p><strong>Note:</strong> The charCode property is not supported in IE8 and earlier versions.</p>
_x000D_
_x000D_
_x000D_

How to convert a structure to a byte array in C#?

You can use Marshal (StructureToPtr, ptrToStructure), and Marshal.copy but this is plataform dependent.


Serialization includes Functions to Custom Serialization.

public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) 

SerializationInfo include functions to serialize each member.


BinaryWriter and BinaryReader also contains methods to Save / Load to Byte Array (Stream).

Note that you can create a MemoryStream from a Byte Array or a Byte Array from a MemoryStream.

You can create a method Save and a method New on your structure:

   Save(Bw as BinaryWriter)
   New (Br as BinaryReader)

Then you select members to Save / Load to Stream -> Byte Array.

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

How do you declare string constants in C?

The main disadvantage of the #define method is that the string is duplicated each time it is used, so you can end up with lots of copies of it in the executable, making it bigger.

How to tag an older commit in Git?

Just the Code

# Set the HEAD to the old commit that we want to tag
git checkout 9fceb02

# temporarily set the date to the date of the HEAD commit, and add the tag
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" \
git tag -a v1.2 -m"v1.2"

# set HEAD back to whatever you want it to be
git checkout master

Details

The answer by @dkinzer creates tags whose date is the current date (when you ran the git tag command), not the date of the commit. The Git help for tag has a section "On Backdating Tags" which says:

If you have imported some changes from another VCS and would like to add tags for major releases of your work, it is useful to be able to specify the date to embed inside of the tag object; such data in the tag object affects, for example, the ordering of tags in the gitweb interface.

To set the date used in future tag objects, set the environment variable GIT_COMMITTER_DATE (see the later discussion of possible values; the most common form is "YYYY-MM-DD HH:MM").

For example:

$ GIT_COMMITTER_DATE="2006-10-02 10:31" git tag -s v1.0.1

The page "How to Tag in Git" shows us that we can extract the time of the HEAD commit via:

git show --format=%aD  | head -1
#=> Wed, 12 Feb 2014 12:36:47 -0700

We could extract the date of a specific commit via:

GIT_COMMITTER_DATE="$(git show 9fceb02 --format=%aD | head -1)" \
git tag -a v1.2 9fceb02 -m "v1.2"

However, instead of repeating the commit twice, it seems easier to just change the HEAD to that commit and use it implicitly in both commands:

git checkout 9fceb02 

GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" git tag -a v1.2 -m "v1.2"

AngularJS : How to watch service variables?

==UPDATED==

Very simple now in $watch.

Pen here.

HTML:

<div class="container" data-ng-app="app">

  <div class="well" data-ng-controller="FooCtrl">
    <p><strong>FooController</strong></p>
    <div class="row">
      <div class="col-sm-6">
        <p><a href="" ng-click="setItems([ { name: 'I am single item' } ])">Send one item</a></p>
        <p><a href="" ng-click="setItems([ { name: 'Item 1 of 2' }, { name: 'Item 2 of 2' } ])">Send two items</a></p>
        <p><a href="" ng-click="setItems([ { name: 'Item 1 of 3' }, { name: 'Item 2 of 3' }, { name: 'Item 3 of 3' } ])">Send three items</a></p>
      </div>
      <div class="col-sm-6">
        <p><a href="" ng-click="setName('Sheldon')">Send name: Sheldon</a></p>
        <p><a href="" ng-click="setName('Leonard')">Send name: Leonard</a></p>
        <p><a href="" ng-click="setName('Penny')">Send name: Penny</a></p>
      </div>
    </div>
  </div>

  <div class="well" data-ng-controller="BarCtrl">
    <p><strong>BarController</strong></p>
    <p ng-if="name">Name is: {{ name }}</p>
    <div ng-repeat="item in items">{{ item.name }}</div>
  </div>

</div>

JavaScript:

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

app.factory('PostmanService', function() {
  var Postman = {};
  Postman.set = function(key, val) {
    Postman[key] = val;
  };
  Postman.get = function(key) {
    return Postman[key];
  };
  Postman.watch = function($scope, key, onChange) {
    return $scope.$watch(
      // This function returns the value being watched. It is called for each turn of the $digest loop
      function() {
        return Postman.get(key);
      },
      // This is the change listener, called when the value returned from the above function changes
      function(newValue, oldValue) {
        if (newValue !== oldValue) {
          // Only update if the value changed
          $scope[key] = newValue;
          // Run onChange if it is function
          if (angular.isFunction(onChange)) {
            onChange(newValue, oldValue);
          }
        }
      }
    );
  };
  return Postman;
});

app.controller('FooCtrl', ['$scope', 'PostmanService', function($scope, PostmanService) {
  $scope.setItems = function(items) {
    PostmanService.set('items', items);
  };
  $scope.setName = function(name) {
    PostmanService.set('name', name);
  };
}]);

app.controller('BarCtrl', ['$scope', 'PostmanService', function($scope, PostmanService) {
  $scope.items = [];
  $scope.name = '';
  PostmanService.watch($scope, 'items');
  PostmanService.watch($scope, 'name', function(newVal, oldVal) {
    alert('Hi, ' + newVal + '!');
  });
}]);

Why am I getting InputMismatchException?

I encountered the same problem. Strange, but the reason was that the object Scanner interprets fractions depending on localization of system. If the current localization uses a comma to separate parts of the fractions, the fraction with the dot will turn into type String. Hence the error ...

Error message "Strict standards: Only variables should be passed by reference"

The cause of the error is the use of the internal PHP programming data structures function, array_shift() [php.net/end].

The function takes an array as a parameter. Although an ampersand is indicated in the prototype of array_shift() in the manual", there isn't any cautionary documentation following in the extended definition of that function, nor is there any apparent explanation that the parameter is in fact passed by reference.

Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.

Reproduce code:

function get_arr()
{
    return array(1, 2);
}
$array = get_arr();
$el = array_shift($array);

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

When to use single quotes, double quotes, and backticks in MySQL

In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Now, suppose you are using a direct post variable into the MySQL query then, use it this way:

$query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";

This is the best practice for using PHP variables into MySQL.

How to find whether or not a variable is empty in Bash?

Presuming Bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

How to create a collapsing tree table in html/css/js?

HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link

How to hide navigation bar permanently in android activity?

Do this.

public void FullScreencall() {
    if(Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
        View v = this.getWindow().getDecorView();
        v.setSystemUiVisibility(View.GONE);
    } else if(Build.VERSION.SDK_INT >= 19) {
        //for new api versions.
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }
}

This works 100% and you can do same for lower API versions, even if it's a late answer I hope it will helps someone else.

If you want this to be permanent, just call FullscreenCall() inside your onResume() method.

Filtering Pandas Dataframe using OR statement

You can do like below to achieve your result:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()


#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()

What does the exclamation mark do before the function?

JavaScript syntax 101. Here is a function declaration:

function foo() {}

Note that there's no semicolon: this is just a function declaration. You would need an invocation, foo(), to actually run the function.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! and instantly calls the function.

So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

(function(){})();

Lastly, ! makes the expression return true. This is because by default all immediately invoked function expressions (IIFE) return undefined, which leaves us with !undefined which is true. Not particularly useful.

In Python, how do I split a string and keep the separators?

I found this generator based approach more satisfying:

def split_keep(string, sep):
    """Usage:
    >>> list(split_keep("a.b.c.d", "."))
    ['a.', 'b.', 'c.', 'd']
    """
    start = 0
    while True:
        end = string.find(sep, start) + 1
        if end == 0:
            break
        yield string[start:end]
        start = end
    yield string[start:]

It avoids the need to figure out the correct regex, while in theory should be fairly cheap. It doesn't create new string objects and, delegates most of the iteration work to the efficient find method.

... and in Python 3.8 it can be as short as:

def split_keep(string, sep):
    start = 0
    while (end := string.find(sep, start) + 1) > 0:
        yield string[start:end]
        start = end
    yield string[start:]

Android - default value in editText

From the xml:

  android:text="yourtext"

Send form data using ajax

I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:

  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }

It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.

Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:

function ajax_create_request_string(data, recursion) {
  var data_string = '';
  //Zpracovani formulare
  if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
    //Get all the input elements in form
    var elem = data.elements;
    //Loop through the element array
    for(var i = 0; i < elem.length; i++) {
      //Ignore elements that are not supposed to be sent
      if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
        continue; 
      //Add & to any subsequent entries (that means every iteration except the first one) 
      if(data_string.length>0)
        data_string+="&";
      //Get data for selectbox
      if (elem[i].tagName.toUpperCase() == "SELECT")
      {
        data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
      }
      //Get data from checkbox
      else if(elem[i].type=="checkbox")
      {
        data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
      }
      //Get data from textfield
      else
      {
        if(elem[i].className.indexOf("autoempty")!=-1) {
          data_string += elem[i].name+"=";
        }
        else
          data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
      }
    }
    return data_string; 
  }
  //Loop through array
  if(data instanceof Array) {
    for(var i=0; i<data.length; i++) {
      if(data_string!="")
        data_string+="&";
      data_string+=recursion+"["+i+"]="+data[i];
    }
    return data_string;
  }
  //Loop through object (like foreach)
  for(var i in data) {
    if(data_string!="")
      data_string+="&";
    if(typeof data[i]=="object") {
      if(recursion==null)
        data_string+= ajax_create_request_string(data[i], i);
      else
        data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
    }
    else if(recursion==null)
      data_string+=i+"="+data[i];
    else 
      data_string+=recursion+"["+i+"]="+data[i];
  }
  return data_string;
}

Image convert to Base64

Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!

Usage: input is your nameId input has file image

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

  if (image && image[0]) {
    const reader = new FileReader();

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

Example: converImageToBase64('yourFileInputId')

https://codepen.io/mariohandsome/pen/yLadmVb

how do I use an enum value on a switch statement in C++

Some things to note:

You should always declare your enum inside a namespace as enums are not proper namespaces and you will be tempted to use them like one.

Always have a break at the end of each switch clause execution will continue downwards to the end otherwise.

Always include the default: case in your switch.

Use variables of enum type to hold enum values for clarity.

see here for a discussion of the correct use of enums in C++.

This is what you want to do.

namespace choices
{
    enum myChoice 
    { 
        EASY = 1 ,
        MEDIUM = 2, 
        HARD = 3  
    };
}

int main(int c, char** argv)
{
    choices::myChoice enumVar;
    cin >> enumVar;
    switch (enumVar)
    {
        case choices::EASY:
        {
            // do stuff
            break;
        }
        case choices::MEDIUM:
        {
            // do stuff
            break;
        }

        default:
        {
            // is likely to be an error
        }
    };

}

HTML form with two submit buttons and two "target" attributes

Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!

<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">

<input type="submit"  name="scheduled" value="Schedule Emails">
<input type="submit"  name="single" value="Email Now">
</form>

twosubmits.php

<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}

if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>

Route.get() requires callback functions but got a "object Undefined"

I had the same error. The problem was in the export and import of the modules.

Example of my solution:

Controller (File: posts.js)

exports.getPosts = (req, res) => {
    res.json({
        posts: [
            { tittle: 'First posts' },
            { tittle: 'Second posts' },
        ]
    });
};

Router (File: posts.js)

const express = require('express');
const { getPosts } = require('../controllers/posts');

const routerPosts = express.Router();
routerPosts.get('/', getPosts);

exports.routerPosts = routerPosts;

Main (File: app.js)

const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const { routerPosts } = require('./routes/posts');

const app = express();
const port = process.env.PORT || 3000;

dotenv.config();

// Middleware
app.use(morgan('dev'));

app.use('/', routerPosts);

app.listen(port, () => {
    console.log(`A NodeJS API is listining on port: ${port}`);
});

Running the application (chrome output)

// 20200409002022
// http://localhost:3000/

{
  "posts": [
    {
      "tittle": "First posts"
    },
    {
      "tittle": "Second posts"
    }
  ]
}

Console Log

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev

> [email protected] dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js

[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 304 5.093 ms - -
GET / 304 0.714 ms - -
GET / 304 0.653 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 200 4.427 ms - 62
GET / 304 0.783 ms - -
GET / 304 0.642 ms - -

Node Version

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ node -v
v13.12.0

NPM Version

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ npm -v
6.14.4

git pull while not in a git directory

Starting git 1.8.5 (Q4 2013), you will be able to "use a Git command, but without having to change directories".

Just like "make -C <directory>", "git -C <directory> ..." tells Git to go there before doing anything else.

See commit 44e1e4 by Nazri Ramliy:

It takes more keypresses to invoke Git command in a different directory without leaving the current directory:

  1. (cd ~/foo && git status)
    git --git-dir=~/foo/.git --work-tree=~/foo status
    GIT_DIR=~/foo/.git GIT_WORK_TREE=~/foo git status
  2. (cd ../..; git grep foo)
  3. for d in d1 d2 d3; do (cd $d && git svn rebase); done

The methods shown above are acceptable for scripting but are too cumbersome for quick command line invocations.

With this new option, the above can be done with fewer keystrokes:

  1. git -C ~/foo status
  2. git -C ../.. grep foo
  3. for d in d1 d2 d3; do git -C $d svn rebase; done

Since Git 2.3.4 (March 2015), and commit 6a536e2 by Karthik Nayak (KarthikNayak), git will treat "git -C '<path>'" as a no-op when <path> is empty.

'git -C ""' unhelpfully dies with error "Cannot change to ''", whereas the shell treats cd ""' as a no-op.
Taking the shell's behavior as a precedent, teach git to treat -C ""' as a no-op, as well.


4 years later, Git 2.23 (Q3 2019) documents that 'git -C ""' works and doesn't change directory

It's been behaving so since 6a536e2 (git: treat "git -C '<path>'" as a no-op when <path> is empty, 2015-03-06, Git v2.3.4).

That means the documentation now (finally) includes:

If '<path>' is present but empty, e.g. -C "", then the current working directory is left unchanged.


You can see git -C used with Git 2.26 (Q1 2020), as an example.

See commit b441717, commit 9291e63, commit 5236fce, commit 10812c2, commit 62d58cd, commit b87b02c, commit 9b92070, commit 3595d10, commit f511bc0, commit f6041ab, commit f46c243, commit 99c049b, commit 3738439, commit 7717242, commit b8afb90 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 381e8e9, 05 Feb 2020)

t1507: inline full_name()

Signed-off-by: Denton Liu

Before, we were running test_must_fail full_name. However, test_must_fail should only be used on git commands.
Inline full_name() so that we can use test_must_fail on the git command directly.

When full_name() was introduced in 28fb84382b ("Introduce <branch>@{upstream} notation", 2009-09-10, Git v1.7.0-rc0 -- merge), the git -C option wasn't available yet (since it was introduced in 44e1e4d67d ("git: run in a directory given with -C option", 2013-09-09, Git v1.8.5-rc0 -- merge listed in batch #5)).
As a result, the helper function removed the need to manually cd each time. However, since git -C is available now, we can just use that instead and inline full_name().

how to hide the content of the div in css

There are many ways to do it:
One way:

#mybox:hover {
   display:none;
}

Another way:

#mybox:hover {
   visibility: hidden;
}

Or you could just do:

#mybox:hover {
   background:transparent;
   color:transparent;
}

Yahoo Finance API

You may use YQL however yahoo.finance.* tables are not the core yahoo tables. It is an open data table which uses the 'csv api' and converts it to json or xml format. It is more convenient to use but it's not always reliable. I could not use it just a while ago because it the table hits its storage limit or something...

You may use this php library to get historical data / quotes using YQL https://github.com/aygee/php-yql-finance

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

How to get the server path to the web directory in Symfony2 from inside the controller?

UPDATE: Since 2.8 this no longer works because assetic is no longer included by default. Although if you're using assetic this will work.

You can use the variable %assetic.write_to%.

$this->getParameter('assetic.write_to');

Since your assets depend on this variable to be dumped to your web directory, it's safe to assume and use to locate your web folder.

http://symfony.com/doc/current/reference/configuration/assetic.html

Best way to get value from Collection by index

You shouldn't. a Collection avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List implies some form of ordering, but a Set does not.

Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = World
elem = Hello
myCollection.toArray()[0] = World

whilst:

myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);

gives me:

elem = Hello
elem = World
myCollection.toArray()[0] = Hello

Why do you want to do this? Could you not just iterate over the collection?

Error using eclipse for Android - No resource found that matches the given name

I renamed the file in res/values "strings.xml" to "string.xml" (no 's' on the end), cleaned and rebuilt without error.

How can I recursively find all files in current and subfolders based on wildcard matching?

for file search
find / -xdev -name settings.xml --> whole computer
find ./ -xdev -name settings.xml --> current directory & its sub directory

for files with extension type

find . -type f -name "*.iso"

How to delete and recreate from scratch an existing EF Code First database

There re many ways to drop a database or update existing database, simply you can switched to previous migrations.

dotnet ef database update previousMigraionName    

But some databases have limitations like not allow to modify after create relationships, means you have not allow privileges to drop columns from ef core database providers but most of time in ef core drop database is allowed.so you can drop DB using drop command and then you use previous migration again.

dotnet ef database drop
PMC command 
PM> drop-database

OR you can do manually deleting database and do a migration.

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

Apply CSS styles to an element depending on its child elements

As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.

It'd be wonderful if you could do something like div[div.a] or div:containing[div.a] as you said, but this isn't possible.

You may want to consider looking at jQuery. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.

If you use jQuery, something along the lines of this would may work (untested but the theory is there):

$('div:has(div.a)').css('border', '1px solid red');

or

$('div:has(div.a)').addClass('redBorder');

combined with a CSS class:

.redBorder
{
    border: 1px solid red;
}

Here's the documentation for the jQuery "has" selector.

What is offsetHeight, clientHeight, scrollHeight?

My descriptions for the three:

  • offsetHeight: How much of the parent's "relative positioning" space is taken up by the element. (ie. it ignores the element's position: absolute descendents)
  • clientHeight: Same as offset-height, except it excludes the element's own border, margin, and the height of its horizontal scroll-bar (if it has one).
  • scrollHeight: How much space is needed to see all of the element's content/descendents (including position: absolute ones) without scrolling.

Then there is also:

Change color inside strings.xml

Just add your text between the font tags:

for blue color

<string name="hello_world"><font color='blue'>Hello world!</font></string>

or for red color

<string name="hello_world"><font color='red'>Hello world!</font></string>

In CSS how do you change font size of h1 and h2

h1 {
  font-weight: bold;
  color: #fff;
  font-size: 32px;
}

h2 {
  font-weight: bold;
  color: #fff;
  font-size: 24px;
}

Note that after color you can use a word (e.g. white), a hex code (e.g. #fff) or RGB (e.g. rgb(255,255,255)) or RGBA (e.g. rgba(255,255,255,0.3)).

What's the proper way to compare a String to an enum value?

You should declare toString() and valueOf() method in enum.

 import java.io.Serializable;

public enum Gesture implements Serializable {
    ROCK,PAPER,SCISSORS;

    public String toString(){
        switch(this){
        case ROCK :
            return "Rock";
        case PAPER :
            return "Paper";
        case SCISSORS :
            return "Scissors";
        }
        return null;
    }

    public static Gesture valueOf(Class<Gesture> enumType, String value){
        if(value.equalsIgnoreCase(ROCK.toString()))
            return Gesture.ROCK;
        else if(value.equalsIgnoreCase(PAPER.toString()))
            return Gesture.PAPER;
        else if(value.equalsIgnoreCase(SCISSORS.toString()))
            return Gesture.SCISSORS;
        else
            return null;
    }
}

How to get full path of a file?

the easiest way I found is

for i in `ls`; do echo "`pwd`/$i"; done

it works well for me

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
    

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('http://your-first-site.com')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in event.data:
            console.log(event.data); 
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.
            return; 
        } 
    }); 
    

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

Percentage Height HTML 5/CSS

Sometimes, you may want to conditionally set the height of a div, such as when the entire content is less than the height of the screen. Setting all parent elements to 100% will cut off content when it is longer than the screen size.

So, the way to get around this is to set the min-height:

Continue to let the parent elements automatically adjust their height Then in your main div, subtract the pixel sizes of the header and footer div from 100vh (viewport units). In css, something like:

min-height: calc(100vh - 246px);

100vh is full length of the screen, minus the surrounding divs. By setting min-height and not height, content longer than screen will continue to flow, instead of getting cut off.

How to add multiple files to Git at the same time

You can also select multiple files like this

git add folder/subfolder/*

This will add all the files in the specified subfolder. Very useful when you edit a bunch of files but you just want to commit some of them...

How to remove a newline from a string in Bash

Adding answer to show example of stripping multiple characters including \r using tr and using sed. And illustrating using hexdump.

In my case I had found that a command ending with awk print of the last item |awk '{print $2}' in the line included a carriage-return \r as well as quotes.

I used sed 's/["\n\r]//g' to strip both the carriage-return and quotes.

I could also have used tr -d '"\r\n'.

Interesting to note sed -z is needed if one wishes to remove \n line-feed chars.

$ COMMAND=$'\n"REBOOT"\r   \n'

$ echo "$COMMAND" |hexdump -C
00000000  0a 22 52 45 42 4f 4f 54  22 0d 20 20 20 0a 0a     |."REBOOT".   ..|

$ echo "$COMMAND" |tr -d '"\r\n' |hexdump -C
00000000  52 45 42 4f 4f 54 20 20  20                       |REBOOT   |

$ echo "$COMMAND" |sed 's/["\n\r]//g' |hexdump -C
00000000  0a 52 45 42 4f 4f 54 20  20 20 0a 0a              |.REBOOT   ..|

$ echo "$COMMAND" |sed -z 's/["\n\r]//g' |hexdump -C
00000000  52 45 42 4f 4f 54 20 20  20                       |REBOOT   |

And this is relevant: What are carriage return, linefeed, and form feed?

  • CR == \r == 0x0d
  • LF == \n == 0x0a

usr/bin/ld: cannot find -l<nameOfTheLibrary>

I had this problem with compiling LXC on a fresh VM with Centos 7.8. I tried all the above and failed. Some suggested removing the -static flag from the compiler configuration but I didn't want to change anything.

The only thing that helped was to install glibc-static and retry. Hope that helps someone.

Sorting a List<int>

double jhon = 3;
double[] numbers = new double[3];
for (int i = 0; i < 3; i++)

{
    numbers[i] = double.Parse(Console.ReadLine());

}
Console.WriteLine("\n");

Array.Sort(numbers);

for (int i = 0; i < 3; i++)
{
    Console.WriteLine(numbers[i]);

}

Console.ReadLine();

How to call code behind server method from a client side JavaScript function?

JS Code:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML Code:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

Code Behind C#

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
}

How to correctly use the extern keyword in C

When you have that function defined on a different dll or lib, so that the compiler defers to the linker to find it. Typical case is when you are calling functions from the OS API.

How do I check if a variable is of a certain type (compare two types) in C?

As others have mentioned, you can't extract the type of a variable at runtime. However, you could construct your own "object" and store the type along with it. Then you would be able to check it at runtime:

typedef struct {
   int  type;     // or this could be an enumeration
   union {
      double d;
      int i;
   } u;
} CheesyObject;

Then set the type as needed in the code:

CheesyObject o;
o.type = 1;  // or better as some define, enum value...
o.u.d = 3.14159;

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Add elements in first arraylist

ArrayList<String> firstArrayList = new ArrayList<String>();

firstArrayList.add("A");
firstArrayList.add("B");
firstArrayList.add("C");
firstArrayList.add("D");
firstArrayList.add("E");

Add elements in second arraylist

ArrayList<String> secondArrayList = new ArrayList<String>();

secondArrayList.add("B");
secondArrayList.add("D");
secondArrayList.add("F");
secondArrayList.add("G");

Add first arraylist's elements in second arraylist

secondArrayList.addAll(firstArrayList);

Assign new combine arraylist and add all elements from both arraylists

ArrayList<String> comboArrayList = new ArrayList<String>(firstArrayList);
comboArrayList.addAll(secondArrayList);

Assign new Set for remove duplicate entries from arraylist

Set<String> setList = new LinkedHashSet<String>(comboArrayList);
comboArrayList.clear();
comboArrayList.addAll(setList);

Sorting arraylist

Collections.sort(comboArrayList);

Output

 A
 B
 C
 D
 E
 F
 G

What's the difference between RANK() and DENSE_RANK() functions in oracle?

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

I got the same error while using Entity Framework 6 with SQL Server Compact 4.0. The article on MSDN for Entity Framework Providers for EF6 was helpful. Running the respective provider commands as nuget packages at Package Manager Console might solve the problem, as also NuGet packages will automatically add registrations to the config file. I ran PM> Install-Package EntityFramework.SqlServerCompact to solve the problem.

SecurityError: The operation is insecure - window.history.pushState()

I had this problem on ReactJS history push, turned out i was trying to open //link (with double slashes)

How to compare two floating point numbers in Bash?

I used the answers from here and put them in a function, you can use it like this:

is_first_floating_number_bigger 1.5 1.2
result="${__FUNCTION_RETURN}"

Once called, echo $result will be 1 in this case, otherwise 0.

The function:

is_first_floating_number_bigger () {
    number1="$1"
    number2="$2"

    [ ${number1%.*} -eq ${number2%.*} ] && [ ${number1#*.} \> ${number2#*.} ] || [ ${number1%.*} -gt ${number2%.*} ];
    result=$?
    if [ "$result" -eq 0 ]; then result=1; else result=0; fi

    __FUNCTION_RETURN="${result}"
}

Or a version with debug output:

is_first_floating_number_bigger () {
    number1="$1"
    number2="$2"

    echo "... is_first_floating_number_bigger: comparing ${number1} with ${number2} (to check if the first one is bigger)"

    [ ${number1%.*} -eq ${number2%.*} ] && [ ${number1#*.} \> ${number2#*.} ] || [ ${number1%.*} -gt ${number2%.*} ];
    result=$?
    if [ "$result" -eq 0 ]; then result=1; else result=0; fi

    echo "... is_first_floating_number_bigger: result is: ${result}"

    if [ "$result" -eq 0 ]; then
        echo "... is_first_floating_number_bigger: ${number1} is not bigger than ${number2}"
    else
        echo "... is_first_floating_number_bigger: ${number1} is bigger than ${number2}"
    fi

    __FUNCTION_RETURN="${result}"
}

Just save the function in a separated .sh file and include it like this:

. /path/to/the/new-file.sh

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

This exact same error happened to me only when I tried to build my debug build type. The way I solved it was to change my google-services.json for my debug build type. My original field had a field called client_id and the value was android:com.example.exampleapp, and I just deleted the android: prefix and leave as com.example.exampleapp and after that my gradle build was successful.

Hope it helps!

EDIT

I've just added back the android: prefix in my google-services.json and it continued to work correctly. Not sure what happened exactly but I was able to solve my problem with the solution mentioned above.

Eclipse fonts and background color

If you are having trouble with Eclipse 2019 and using a dark theme and setting the background and having it not change: There seems to be a recent Eclipse bug. I suggest you look here or here for workarounds.

Oracle sqlldr TRAILING NULLCOLS required, but why?

I had similar issue when I had plenty of extra records in csv file with empty values. If I open csv file in notepad then empty lines looks like this: ,,,, ,,,, ,,,, ,,,,

You can not see those if open in Excel. Please check in Notepad and delete those records

How to send password securely over HTTP?

You can use SRP to use secure passwords over an insecure channel. The advantage is that even if an attacker sniffs the traffic, or compromises the server, they can't use the passwords on a different server. https://github.com/alax/jsrp is a javascript library that supports secure passwords over HTTP in the browser, or server side (via node).

Global Events in Angular

I'm using a message service that wraps an rxjs Subject (TypeScript)

Plunker example: Message Service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/map'

interface Message {
  type: string;
  payload: any;
}

type MessageCallback = (payload: any) => void;

@Injectable()
export class MessageService {
  private handler = new Subject<Message>();

  broadcast(type: string, payload: any) {
    this.handler.next({ type, payload });
  }

  subscribe(type: string, callback: MessageCallback): Subscription {
    return this.handler
      .filter(message => message.type === type)
      .map(message => message.payload)
      .subscribe(callback);
  }
}

Components can subscribe and broadcast events (sender):

import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'

@Component({
  selector: 'sender',
  template: ...
})
export class SenderComponent implements OnDestroy {
  private subscription: Subscription;
  private messages = [];
  private messageNum = 0;
  private name = 'sender'

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe(this.name, (payload) => {
      this.messages.push(payload);
    });
  }

  send() {
    let payload = {
      text: `Message ${++this.messageNum}`,
      respondEvent: this.name
    }
    this.messageService.broadcast('receiver', payload);
  }

  clear() {
    this.messages = [];
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

(receiver)

import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'

@Component({
  selector: 'receiver',
  template: ...
})
export class ReceiverComponent implements OnDestroy {
  private subscription: Subscription;
  private messages = [];

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe('receiver', (payload) => {
      this.messages.push(payload);
    });
  }

  send(message: {text: string, respondEvent: string}) {
    this.messageService.broadcast(message.respondEvent, message.text);
  }

  clear() {
    this.messages = [];
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

The subscribe method of MessageService returns an rxjs Subscription object, which can be unsubscribed from like so:

import { Subscription } from 'rxjs/Subscription';
...
export class SomeListener {
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe('someMessage', (payload) => {
      console.log(payload);
      this.subscription.unsubscribe();
    });
  }
}

Also see this answer: https://stackoverflow.com/a/36782616/1861779

Plunker example: Message Service

PHP Sort a multidimensional array by element containing date

http://us2.php.net/manual/en/function.array-multisort.php see third example:

<?php

$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);

?>

fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.

How can I upgrade specific packages using pip and a requirements file?

This solved the issue for me:

pip install -I --upgrade psutil --force

Afterwards just uninstall psutil with the new version and hop you can suddenly install the older version (:

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

I have got the same error but I have resolved the issue in the following ways:

  1. Provide all the mandatory filed of your bean/model class
  2. Don't violet the concept of the unique constraint, Provide unique value in Unique constraints.

What is the meaning of the term "thread-safe"?

Instead of thinking of code or classes as thread safe or not, I think it is more helpful to think of actions as being thread-safe. Two actions are thread safe if they will be behave as specified when run from arbitrary threading contexts. In many cases, classes will support some combinations of actions in thread-safe fashion and others not.

For example, many collections like array-lists and hash sets will guarantee that if they are initially accessed exclusively with one thread, and they are never modified after a reference becomes visible to any other threads, they may be read in arbitrary fashion by any combination of threads without interference.

More interestingly, some hash-set collections such as the original non-generic one in .NET, may offer a guarantee that as long as no item is ever removed, and provided that only one thread ever writes to them, any thread that tries to read the collection will behave as though accessing a collection where updates might be delayed and occur in arbitrary order, but which will otherwise behave normally. If thread #1 adds X and then Y, and thread #2 looks for and sees Y and then X, it would be possible for thread #2 to see that Y exists but X doesn't; whether or not such behavior is "thread-safe" would depend upon whether thread #2 is prepared to deal with that possibility.

As a final note, some classes--especially blocking communications libraries--may have a "close" or "Dispose" method which is thread-safe with respect to all other methods, but no other methods that are thread-safe with respect to each other. If a thread performs a blocking read request and a user of the program clicks "cancel", there would be no way for a close request to be issued by the thread that's attempting to perform the read. The close/dispose request, however, may asynchronously set a flag which will cause the read request to be canceled as soon as possible. Once close is performed on any thread, the object would become useless, and all attempts at future actions would fail immediately, but being able to asynchronously terminate any attempted I/O operations is better than require that the close request be synchronized with the read (since if the read blocks forever, the synchronization request would be likewise blocked).

Read a plain text file with php

$file="./doc.txt";
$doc=file_get_contents($file);

$line=explode("\n",$doc);
foreach($line as $newline){
    echo '<h3 style="color:#453288">'.$newline.'</h3><br>';

}

String Resource new line /n not possible?

Very simple you have to just put
\n where ever you want to break line in your string resource.

For example

String s = my string resource have \n line break here;

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

How do I set default terminal to terminator?

From within a terminal, try

sudo update-alternatives --config x-terminal-emulator

Select the desired terminal from the list of alternatives.

Create two threads, one display odd & other even numbers

package javaapplication45;

public class JavaApplication45 extends Thread {

    public static void main(String[] args) {
        //even numbers
        Thread t1 = new Thread() {
            public void run() {
                for (int i = 1; i <= 20; i++) {
                    if (i % 2 == 0) {
                        System.out.println("even thread " + i);
                    }
                }
            }
        };
        t1.start();
        //odd numbers
        Thread t2 = new Thread() {
            public void run() {
                for (int i = 1; i <= 20; i++) {
                    if (i % 2 != 0) {
                        System.out.println("odd thread " + i);
                    }
                }
            }
        };
        t2.start();

    }

}

How to write a cursor inside a stored procedure in SQL Server 2008

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

How to center align the cells of a UICollectionView?

In Swift, the following will distribute cells evenly by applying the correct amount of padding on the sides of each cell. Of course, you need to know/set your cell width first.

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    insetForSectionAtIndex section: Int) -> UIEdgeInsets {

        var cellWidth : CGFloat = 110;

        var numberOfCells = floor(self.view.frame.size.width / cellWidth);
        var edgeInsets = (self.view.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1);

        return UIEdgeInsetsMake(0, edgeInsets, 60.0, edgeInsets);
}

How to find the difference in days between two dates?

echo $(date +%d/%h/%y) date_today
echo " The other date is 1970/01/01"
TODAY_DATE="1970-01-01"
BEFORE_DATE=$(date +%d%h%y)
echo "THE DIFFERNS IS " $(( ($(date -d $BEFORE_DATE +%s) - $(date -d $TODAY_DATE +%s)) )) SECOUND

use it to get your date today and your sec since the date you want. if you want it with days just divide it with 86400

echo $(date +%d/%h/%y) date_today
echo " The other date is 1970/01/01"
TODAY_DATE="1970-01-01"
BEFORE_DATE=$(date +%d%h%y)
echo "THE DIFFERNS IS " $(( ($(date -d $BEFORE_DATE +%s) - $(date -d $TODAY_DATE +%s))/ 86400)) SECOUND

Draw line in UIView

Based on Guy Daher's answer.

I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.

I would do nil check if statement:

class CustomView: UIView 
{    
    override func draw(_ rect: CGRect) 
    {
        super.draw(rect)
        if let context = UIGraphicsGetCurrentContext()
        {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

JavaFX: How to get stage from controller during initialization?

The simplest way to get stage object in controller is:

  1. Add an extra method in own created controller class like (it will be a setter method to set the stage in controller class),

    private Stage myStage;
    public void setStage(Stage stage) {
         myStage = stage;
    }
    
  2. Get controller in start method and set stage

    FXMLLoader loader = new FXMLLoader(getClass().getResource("MyFXML.fxml"));
    OwnController controller = loader.getController();
    controller.setStage(this.stage);
    
  3. Now you can access the stage in controller

Cannot find the '@angular/common/http' module

Important Update:

HttpModule and Http from @angular/http has been deprecated since Angular V5, should of using HttpClientModule and HttpClient from @angular/common/http instead, refer CHANGELOG.


For Angular version previous from **@4.3.0, You should inject Http from @angular/http, and HttpModule is for importing at your NgModule's import array.

import {HttpModule} from '@angular/http';

@NgModule({
  ...
  imports: [HttpModule]
})

Inject http at component or service

import { Http } from '@angular/http';

constructor(private http: Http) {}

For Angular version after(include) 4.3.0, you can use HttpClient from @angular/common/http instead of Http from @angular/http. Don't forget to import HttpClientModule at your NgModule's import array first.

Refer @echonax's answer.

How to get json key and value in javascript?

var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}

var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);

Pipe to/from the clipboard in Bash script

There are different clipboards in Linux; the X server has one, the window manager might have another one, etc. There is no standard device.

Oh, yes, on CLI, the screen program has its own clipboard as well, as do some other applications like Emacs and vi.

In X, you can use xclip.

You can check this thread for other possible answers: http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2004-07/0919.html

How to calculate md5 hash of a file using javascript

I don't believe there is a way in javascript to access the contents of a file upload. So you therefore cannot look at the file contents to generate an MD5 sum.

You can however send the file to the server, which can then send an MD5 sum back or send the file contents back .. but that's a lot of work and probably not worthwhile for your purposes.

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

This worked for me after i tryed many solutions:
For some reason the adb process didn't restart itself after installing new packages. Manualy killing adb.exe and attempt to import the project another time solved this problem for me.

What is the difference between attribute and property?

<property attribute="attributeValue">proopertyValue</property>

would be one way to look at it.

In C#

[Attribute]
public class Entity
{
    private int Property{get; set;};

ansible: lineinfile for several lines?

It's not ideal, but you're allowed multiple calls to lineinfile. Using that with insert_after, you can get the result you want:

- name: Set first line at EOF (1/3)
  lineinfile: dest=/path/to/file regexp="^string 1" line="string 1"
- name: Set second line after first (2/3)
  lineinfile: dest=/path/to/file regexp="^string 2" line="string 2" insertafter="^string 1"
- name: Set third line after second (3/3)
  lineinfile: dest=/path/to/file regexp="^string 3" line="string 3" insertafter="^string 2"

How to retrieve the dimensions of a view?

Even though the proposed solution works, it might not be the best solution for every case because based on the documentation for ViewTreeObserver.OnGlobalLayoutListener

Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.

which means it gets called many times and not always the view is measured (it has its height and width determined)

An alternative is to use ViewTreeObserver.OnPreDrawListener which gets called only when the view is ready to be drawn and has all of its measurements.

final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnPreDrawListener(new OnPreDrawListener() {

    @Override
    public void onPreDraw() {
        tv.getViewTreeObserver().removeOnPreDrawListener(this);
        // Your view will have valid height and width at this point
        tv.getHeight();
        tv.getWidth();
    }

});

How to simulate a real mouse click using java?

With all respect the most likely thing is that you are mistaken about why the click is being 'rejected'. Why do you think some program is trying to determine if it's human or not? The Robot class (have used it a lot) should send messages that the operating system has no way to distinguish from a user doing the click.

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

How to reload/refresh jQuery dataTable?

if using datatable v1.10.12 then simply calling .draw() method and passing your required draw types ie full-reset, page then you will re-draw your dt with new data

let dt = $("#my-datatable").datatable()

// do some action

dt.draw('full-reset')

for more check out datatable docs

How to get the element clicked (for the whole document)?

$(document).click(function (e) {
    alert($(e.target).text());
});

How to make a UILabel clickable?

For swift 3.0 You can also change gesture long press time duration

label.isUserInteractionEnabled = true
let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:))) 
longPress.minimumPressDuration = 0.2
label.addGestureRecognizer(longPress)

Unable to open debugger port in IntelliJ

You must set CHMOD +x (execute for *.sh or *.bat files). For example, I am using macOS

cd /Users/donhuvy/Documents/tools/apache-tomcat-9.0.12/bin
sudo chmod +x *.sh

Then IntelliJ IDEA, and Apache Tomcat running or debugging just good.

How can I style an Android Switch?

You can customize material styles by setting different color properties. For example custom application theme

<style name="CustomAppTheme" parent="Theme.AppCompat">
    <item name="android:textColorPrimaryDisableOnly">#00838f</item>
    <item name="colorAccent">#e91e63</item>
</style>

Custom switch theme

<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
    <item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
    <item name="android:colorControlActivated">#1b5e20</item>
    <item name="android:colorForeground">#f57f17</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>

You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples

custom switch track and thumb

How to add fonts to create-react-app based projects?

Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

or

<style>
    @import url('https://fonts.googleapis.com/css?family=Roboto');
</style>

Cannot convert lambda expression to type 'string' because it is not a delegate type

My case it solved i was using

@Html.DropDownList(model => model.TypeId ...)  

using

@Html.DropDownListFor(model => model.TypeId ...) 

will solve it

mailto link multiple body lines

To get body lines use escape()

body_line =  escape("\n");

so

href = "mailto:[email protected]?body=hello,"+body_line+"I like this.";

How to get the number of columns from a JDBC ResultSet?

You can get columns number from ResultSetMetaData:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();

Typescript: Type 'string | undefined' is not assignable to type 'string'

You trying to set variable name1, witch type set as strict string (it MUST be string) with value from object field name, witch value type set as optional string (it can be string or undefined, because of question sign). If you really need this behavior, you have to change type of name1 like this:

let name1: string | undefined = person.name;

And it'll be ok;

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

The simplest solution might be to install Java 8 in parallel to Java 9 (if not still still existant) and specify the JVM to be used explicitly in eclipse.ini. You can find a description of this setting including a description how to find eclipse.ini on a Mac at Eclipsepedia

iPhone App Icons - Exact Radius?

I see a lot of "px" discussion but no one is talking percentages which is the fixed number you want to calculate by.

22.37% is the key percentage here. Multiply any of the image sizes mentioned above in by 0.2237 and you will get the correct pixel radius for that size.

Before iOS 8, Apple used less rounding, using 15.625%.

EDIT: Thanks @Chris Prince for commenting with the iOS 8/9/10 radius percentage: 22.37%

Multiple argument IF statement - T-SQL

You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)

DECLARE @StartDate AS DATETIME

DECLARE @EndDate AS DATETIME

SET @StartDate = NULL
SET @EndDate = NULL

IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL) 
    BEGIN
        print 'yoyoyo'
    END

IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2) 
    BEGIN
        print 'Oh hey there'
    END

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

Your java version is 1.5 (you have jdk 1.5). The jar requires java version 1.7 (you should have jdk 1.7). You should download and install the 1.7 jdk from this website:

http://www.oracle.com/technetwork/java/javase/downloads/java-se-jdk-7-download-432154.html

How to scroll to an element in jQuery?

You can extend jQuery functionalities like this:

jQuery.fn.extend({
scrollToMe: function () {
    var x = jQuery(this).offset().top - 100;
    jQuery('html,body').animate({scrollTop: x}, 500);
}});

and then:

$('...').scrollToMe();

easy ;-)

Is there an alternative sleep function in C to milliseconds?

Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM complications.

sigtimedwait and sigwaitinfo offer similar behavior.

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

This is not an error. This is a warning. The difference is pretty huge. This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.

Eclipse WTP adds a custom attribute source to the project related <Context> element in the server.xml of Tomcat which identifies the source of the context (the actual project in the workspace which is deployed to the particular server). This way Eclipse can correlate the deployed webapplication with an project in the workspace. Since Tomcat version 6.0.16, any unspecified XML tags and attributes in the server.xml will produce a warning during Tomcat's startup, even though there is no DTD nor XSD for server.xml.

Just ignore it. Your web project is fine. It should run fine. This issue is completely unrelated to JSF.

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

sum two columns in R

You can do this :

    df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi  = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

Import SQL dump into PostgreSQL database

Here is the command you are looking for.

psql -h hostname -d databasename -U username -f file.sql

Cannot read property 'length' of null (javascript)

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

Good tool for testing socket connections?

Hercules is fantastic. It's a fully functioning tcp/udp client/server, amazing for debugging sockets. More details on the web site.

Calculating bits required to store decimal number

The largest number that can be represented by an n digit number in base b is bn - 1. Hence, the largest number that can be represented in N binary digits is 2N - 1. We need the smallest integer N such that:

2N - 1 = bn - 1
? 2N = bn

Taking the base 2 logarithm of both sides of the last expression gives:

log2 2N = log2 bn
? N = log2 bn
? N = log bn / log 2

Since we want the smallest integer N that satisfies the last relation, to find N, find log bn / log 2 and take the ceiling.

In the last expression, any base is fine for the logarithms, so long as both bases are the same. It is convenient here, since we are interested in the case where b = 10, to use base 10 logarithms taking advantage of log1010n == n.

For n = 3:

N = ?3 / log10 2? = 10

For n = 4:

N = ?4 / log10 2? = 14

For n = 6:

N = ?6 / log10 2? = 20

And in general, for n decimal digits:

N = ?n / log10 2?

Finding all positions of substring in a larger string in C#

Based on the code I've used for finding multiple instances of a string within a larger string, your code would look like:

List<int> inst = new List<int>();
int index = 0;
while (index >=0)
{
    index = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index);
    inst.Add(index);
    index++;
}

Convert UTF-8 encoded NSData to NSString

The Swift version from String to Data and back to String:

Xcode 10.1 • Swift 4.2.1

extension Data {
    var string: String? {
        return String(data: self, encoding: .utf8)
    }
}

extension StringProtocol {
    var data: Data {
        return Data(utf8)
    }
}

extension String {
    var base64Decoded: Data? {
        return Data(base64Encoded: self)
    }
}

Playground

let string = "Hello World"                                  // "Hello World"
let stringData = string.data                                // 11 bytes
let base64EncodedString = stringData.base64EncodedString()  // "SGVsbG8gV29ybGQ="
let stringFromData = stringData.string                      // "Hello World"

let base64String = "SGVsbG8gV29ybGQ="
if let data = base64String.base64Decoded {
    print(data)                                    //  11 bytes
    print(data.base64EncodedString())              // "SGVsbG8gV29ybGQ="
    print(data.string ?? "nil")                    // "Hello World"
}

let stringWithAccent = "Olá Mundo"                          // "Olá Mundo"
print(stringWithAccent.count)                               // "9"
let stringWithAccentData = stringWithAccent.data            // "10 bytes" note: an extra byte for the acute accent
let stringWithAccentFromData = stringWithAccentData.string  // "Olá Mundo\n"

How to set TLS version on apache HttpClient

Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code

RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);

SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);

HttpClient client = builder.build();

Use the following JVM argument to verify

-Djavax.net.debug=all

How do I REALLY reset the Visual Studio window layout?

If you want to reset your development environment of your visual studio, then you can use Import and Export setting wizard. see this for all steps:

http://www.authorcode.com/forums/topic/how-to-reset-development-environment-settings-of-your-visual-studio/

String Pattern Matching In Java

You can use the Pattern class for this. If you want to match only word characters inside the {} then you can use the following regex. \w is a shorthand for [a-zA-Z0-9_]. If you are ok with _ then use \w or else use [a-zA-Z0-9].

String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
    System.out.println(matcher.group(0)); //prints /{item}/
} else {
    System.out.println("Match not found");
}

PHP error: Notice: Undefined index:

You're attempting to access indicies within an array which are not set. This raises a notice.

Mostly likely you're noticing it now because your code has moved to a server where php.ini has error_reporting set to include E_NOTICE. Either suppress notices by setting error_reporting to E_ALL & ~E_NOTICE (not recommended), or verify that the index exists before you attempt to access it:

$month = array_key_exists('month', $_POST) ? $_POST['month'] : null;

Hashcode and Equals for Hashset

You should read up on how to ensure that you've implemented equals and hashCode properly. This is a good starting point: What issues should be considered when overriding equals and hashCode in Java?

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

In my case it happened when adding a new application to IIS that needed to be proxied with Apache.

I needed to set ProxyHTMLEnable On to ProxyHTMLEnable Off to get the content. (It looks like some js code most have triggered the error, but this gave me at least something to work from.)

IIS is sending the page content Content-Encoding: gzip

<Proxy "http://192.168.1.1:81">
    ProxyHTMLEnable On   #> change this to Off
    ProxyHTMLURLMap  ...  ...
</Proxy>

Need to ZIP an entire directory using Node.js

You can try in a simple way:

Install zip-dir :

npm install zip-dir

and use it

var zipdir = require('zip-dir');

let foldername =  src_path.split('/').pop() 
    zipdir(<<src_path>>, { saveTo: 'demo.zip' }, function (err, buffer) {

    });

Difference between Groovy Binary and Source release?

A source release will be compiled on your own machine while a binary release must match your operating system.

source releases are more common on linux systems because linux systems can dramatically vary in cpu, installed library versions, kernelversions and nearly every linux system has a compiler installed.

binary releases are common on ms-windows systems. most windows machines do not have a compiler installed.

bootstrap jquery show.bs.modal event won't fire

Ensure that you are loading jQuery before you use Bootstrap. Sounds basic, but I was having issues catching these modal events and turns out the error was not with my code but that I was loading Bootstrap before jQuery.

Command to change the default home directory of a user

You can do it with:

/etc/passwd

Edit the user home directory and then move the required files and directories to it:

cp/mv -r /home/$user/.bash* /home/newdir

.bash_profile
.ssh/ 

Set the correct permission

chmod -R $user:$user /home/newdir/.bash*

Database, Table and Column Naming Conventions?

Very late to the party but I still wanted to add my two cents about column prefixes

There seem to be two main arguments for using the table_column (or tableColumn) naming standard for columns, both based on the fact that the column name itself will be unique across your whole database:

1) You do not have to specify table names and/or column aliases in your queries all the time

2) You can easily search your whole code for the column name

I think both arguments are flawed. The solution for both problems without using prefixes is easy. Here's my proposal:

Always use the table name in your SQL. E.g., always use table.column instead of column.

It obviously solves 2) as you can now just search for table.column instead of table_column.

But I can hear you scream, how does it solve 1)? It was exactly about avoiding this. Yes, it was, but the solution was horribly flawed. Why? Well, the prefix solution boils down to:
To avoid having to specify table.column when there's ambiguity, you name all your columns table_column!
But this means you will from now on ALWAYS have to write the column name every time you specify a column. But if you have to do that anyways, what's the benefit over always explicitly writing table.column? Exactly, there is no benefit, it's the exact same number of characters to type.

edit: yes, I am aware that naming the columns with the prefix enforces the correct usage whereas my approach relies on the programmers

How do I prompt for Yes/No/Cancel input in a Linux shell script?

more generic would be:

function menu(){
    title="Question time"
    prompt="Select:"
    options=("Yes" "No" "Maybe")
    echo "$title"
    PS3="$prompt"
    select opt in "${options[@]}" "Quit/Cancel"; do
        case "$REPLY" in
            1 ) echo "You picked $opt which is option $REPLY";;
            2 ) echo "You picked $opt which is option $REPLY";;
            3 ) echo "You picked $opt which is option $REPLY";;
            $(( ${#options[@]}+1 )) ) clear; echo "Goodbye!"; exit;;
            *) echo "Invalid option. Try another one.";continue;;
         esac
     done
     return
}

How to find the statistical mode?

Here is my data.table solution that returns row-wise modes for a complete table. I use it to infer row class. It takes care of the new-ish set() function in data.table and should be pretty fast. It does not manage NA though but that could be added by looking at the numerous other solutions on this page.

majorityVote <- function(mat_classes) {
  #mat_classes = dt.pour.centroids_num
  dt.modes <- data.table(mode = integer(nrow(mat_classes)))
  for (i in 1:nrow(mat_classes)) {
    cur.row <- mat_classes[i]
    cur.mode <- which.max(table(t(cur.row)))
    set(dt.modes, i=i, j="mode", value = cur.mode)
  }

  return(dt.modes)
}

Possible usage:

newClass <- majorityVote(my.dt)  # just a new vector with all the modes

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Running a shell script through Cygwin on Windows

Just wanted to add that you can do this to apply dos2unix fix for all files under a directory, as it saved me heaps of time when we had to 'fix' a bunch of our scripts.

find . -type f -exec dos2unix.exe {} \;

I'd do it as a comment to Roman's answer, but I don't have access to commenting yet.

CodeIgniter: How to use WHERE clause and OR clause

You can use this :

$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);

How can I share Jupyter notebooks with non-programmers?

The "best" way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the Jupyter Notebook Viewer. When privacy is more of an issue then there are alternatives but it's certainly more complex; there's no built-in way to do this in Jupyter alone, but a couple of options are:

Host your own nbviewer

GitHub and the Jupyter Notebook Veiwer both use the same tool to render .ipynb files into static HTML, this tool is nbviewer.

The installation instructions are more complex than I'm willing to go into here but if your company/team has a shared server that doesn't require password access then you could host the nbviewer on that server and direct it to load from your credentialed server. This will probably require some more advanced configuration than you're going to find in the docs.

Set up a deployment script

If you don't necessarily need live updating HTML then you could set up a script on your credentialed server that will simply use Jupyter's built-in export options to create the static HTML files and then send those to a more publicly accessible server.

How to unpack pkl file?

Handy one-liner

pkl() (
  python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl

Will print __str__ for the pickled object.

The generic problem of visualizing an object is of course undefined, so if __str__ is not enough, you will need a custom script.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

I encountered a similar problem, I moved the project directory, resulting in installation failure, my solution is as follows: Build->ReBuild

How to open an Excel file in C#?

Microsoft.Office.Interop.Excel.Application excapp;

excapp = new Microsoft.Office.Interop.Excel.Application();

object misval=System.Reflection.Missing.Value;

Workbook wrkbuk = new Workbook();

Worksheet wrksht = new Worksheet();

wrkbuk = excapp.Workbooks._Open(@"C:\Users\...\..._template_v1.0.xlsx", misval, misval, 
misval, misval, misval, misval, misval, misval, misval, misval, misval, misval);

wrksht = (Microsoft.Office.Interop.Excel.Worksheet)wrkbuk.Worksheets.get_Item(2);

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

Android: remove notification from notification bar

A short one Liner of this is:

NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)

Or to cancel all notifications is:

NotificationManagerCompat.from(context).cancelAll()

Made for AndroidX or Support Libraries.

How to delete all the rows in a table using Eloquent?

The best way for accomplishing this operation in Laravel 3 seems to be the use of the Fluent interface to truncate the table as shown below

DB::query("TRUNCATE TABLE mytable");

Nexus 5 USB driver

I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.

When I plugged it, there was no yellow exclamation mark within the device manager. So for me, the drivers was OK. But the device was not listed within my eclipse ddms. After a little bit of searching, It was just an option to change in the device settings. By default, the Nexus 5 usb computer connection is in MTP mode (Media Device).

What you have to do is:

  1. Unplug the device from the computer
  2. Go to Settings -> Storage.
  3. In the ActionBar, click the option menu and choose "USB computer connection".
  4. Check "Camera (PTP)" connection.
  5. Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.
  6. Finally you should see it now in the ddms and voilà.

I hope this will help!

wp-admin shows blank page, how to fix it?

I also had a blank screen for my blog. The solution was to copy up a backup copy of wp-config,php somehow the 'live' wp-config.php had been replaced with a file size of zero.

In my case I had the same problem. Helped remove the wp-config.php file. Wordpress created new wp-config.php file and wp-admin is working flawlessly now. Rename plugins, themes folder does not help.

Filter spark DataFrame on string contains

You can use contains (this works with an arbitrary sequence):

df.filter($"foo".contains("bar"))

like (SQL like with SQL simple regular expression whith _ matching an arbitrary character and % matching an arbitrary sequence):

df.filter($"foo".like("bar"))

or rlike (like with Java regular expressions):

df.filter($"foo".rlike("bar"))

depending on your requirements. LIKE and RLIKE should work with SQL expressions as well.