Programs & Examples On #Mason

HTML::Mason, or Mason for short, is a Perl-based templating system for generating dynamic HTML or other content.

Xcode 10 Error: Multiple commands produce

If you develop private cocoapod, and had already added it via Podfile,

remove it from Embedded Binaries section:

Embedded Binaries in test app

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

toBe(true) vs toBeTruthy() vs toBeTrue()

As you read through the examples below, just keep in mind this difference

true === true // true
"string" === true // false
1 === true // false
{} === true // false

But

Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true

1. expect(statement).toBe(true)

Assertion passes when the statement passed to expect() evaluates to true

expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass

In all other cases cases it would fail

expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail

Even though all of these statements would evaluate to true when doing Boolean():

So you can think of it as 'strict' comparison

2. expect(statement).toBeTrue()

This one does exactly the same type of comparison as .toBe(true), but was introduced in Jasmine recently in version 3.5.0 on Sep 20, 2019

3. expect(statement).toBeTruthy()

toBeTruthy on the other hand, evaluates the output of the statement into boolean first and then does comparison

expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail

And IN ALL OTHER CASES it would pass, for example

expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass

How do I toggle an element's class in pure JavaScript?

Here is a code for IE >= 9 by using split(" ") on the className :

function toggleClass(element, className) {
    var arrayClass = element.className.split(" ");
    var index = arrayClass.indexOf(className);

    if (index === -1) {
        if (element.className !== "") {
            element.className += ' '
        }
        element.className += className;
    } else {
        arrayClass.splice(index, 1);
        element.className = "";
        for (var i = 0; i < arrayClass.length; i++) {
            element.className += arrayClass[i];
            if (i < arrayClass.length - 1) {
                element.className += " ";
            }
        }
    }
}

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

Evenly distributing n points on a sphere

edit: This does not answer the question the OP meant to ask, leaving it here in case people find it useful somehow.

We use the multiplication rule of probability, combined with infinitessimals. This results in 2 lines of code to achieve your desired result:

longitude: f = uniform([0,2pi))
azimuth:   ? = -arcsin(1 - 2*uniform([0,1]))

(defined in the following coordinate system:)

enter image description here

Your language typically has a uniform random number primitive. For example in python you can use random.random() to return a number in the range [0,1). You can multiply this number by k to get a random number in the range [0,k). Thus in python, uniform([0,2pi)) would mean random.random()*2*math.pi.


Proof

Now we can't assign ? uniformly, otherwise we'd get clumping at the poles. We wish to assign probabilities proportional to the surface area of the spherical wedge (the ? in this diagram is actually f):

enter image description here

An angular displacement df at the equator will result in a displacement of df*r. What will that displacement be at an arbitrary azimuth ?? Well, the radius from the z-axis is r*sin(?), so the arclength of that "latitude" intersecting the wedge is df * r*sin(?). Thus we calculate the cumulative distribution of the area to sample from it, by integrating the area of the slice from the south pole to the north pole.

enter image description here (where stuff=df*r)

We will now attempt to get the inverse of the CDF to sample from it: http://en.wikipedia.org/wiki/Inverse_transform_sampling

First we normalize by dividing our almost-CDF by its maximum value. This has the side-effect of cancelling out the df and r.

azimuthalCDF: cumProb = (sin(?)+1)/2 from -pi/2 to pi/2

inverseCDF: ? = -sin^(-1)(1 - 2*cumProb)

Thus:

let x by a random float in range [0,1]
? = -arcsin(1-2*x)

Why does modern Perl avoid UTF-8 by default?

While reading this thread, I often get the impression that people are using "UTF-8" as a synonym to "Unicode". Please make a distinction between Unicode's "Code-Points" which are an enlarged relative of the ASCII code and Unicode's various "encodings". And there are a few of them, of which UTF-8, UTF-16 and UTF-32 are the current ones and a few more are obsolete.

Please, UTF-8 (as well as all other encodings) exists and have meaning in input or in output only. Internally, since Perl 5.8.1, all strings are kept as Unicode "Code-points". True, you have to enable some features as admiringly covered previously.

Convert string to BigDecimal in java

String currency = "135.69";
System.out.println(new BigDecimal(currency));

//will print 135.69

What is @RenderSection in asp.net MVC

If you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()
        @RenderSection("scripts", required: false)
    </body>
</html>

then you can have an index.cshtml content view like this

@section scripts {
     <script type="text/javascript">alert('hello');</script>
}

the required indicates whether or not the view using the layout page must have a scripts section

jQuery select change show/hide div event

Use following JQuery. Demo

$(function() {
    $('#row_dim').hide(); 
    $('#type').change(function(){
        if($('#type').val() == 'parcel') {
            $('#row_dim').show(); 
        } else {
            $('#row_dim').hide(); 
        } 
    });
});

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

How to set image width to be 100% and height to be auto in react native?

For image tag you can use this type of style, it worked for me:

imageStyle: {
    width: Dimensions.get('window').width - 23,
    resizeMode: "contain",
    height: 211,
 },

Test for existence of nested JavaScript object key

A shorter, ES5 version of @CMS's excellent answer:

// Check the obj has the keys in the order mentioned. Used for checking JSON results.  
var checkObjHasKeys = function(obj, keys) {
  var success = true;
  keys.forEach( function(key) {
    if ( ! obj.hasOwnProperty(key)) {
      success = false;
    }
    obj = obj[key];
  })
  return success;
}

With a similar test:

var test = { level1:{level2:{level3:'result'}}};
utils.checkObjHasKeys(test, ['level1', 'level2', 'level3']); // true
utils.checkObjHasKeys(test, ['level1', 'level2', 'foo']); // false

How can I build for release/distribution on the Xcode 4?

XCode>Product>Schemes>Edit Schemes>Run>Build Configuration

How to push a single file in a subdirectory to Github (not master)

Let me start by saying that the way git works is you are not pushing/fetching files; well, at least not directly.

You are pushing/fetching refs, that point to commits. Then a commit in git is a reference to a tree of objects (where files are represented as objects, among other objects).

So, when you are pushing a commit, what git does it pushes a set of references like in this picture:

git commits

If you didn't push your master branch yet, the whole history of the branch will get pushed.

So, in your example, when you commit and push your file, the whole master branch will be pushed, if it was not pushed before.

To do what you asked for, you need to create a clean branch with no history, like in this answer.

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

how to get the 30 days before date from Todays Date

Try adding this to your where clause:

dateadd(day, -30, getdate())

Get POST data in C#/ASP.NET

The following is OK in HTML4, but not in XHTML. Check your editor.

<input type=button value="Submit" />

How to convert an Array to a Set in Java

After you do Arrays.asList(array) you can execute Set set = new HashSet(list);

Here is a sample method, you can write:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

Calling virtual functions inside constructors

Do you know the crash error from Windows explorer?! "Pure virtual function call ..."
Same problem ...

class AbstractClass 
{
public:
    AbstractClass( ){
        //if you call pureVitualFunction I will crash...
    }
    virtual void pureVitualFunction() = 0;
};

Because there is no implemetation for the function pureVitualFunction() and the function is called in the constructor the program will crash.

How to evaluate a math expression given in string form?

This is another interesting alternative https://github.com/Shy-Ta/expression-evaluator-demo

The usage is very simple and gets the job done, for example:

  ExpressionsEvaluator evalExpr = ExpressionsFactory.create("2+3*4-6/2");  
  assertEquals(BigDecimal.valueOf(11), evalExpr.eval()); 

What SOAP client libraries exist for Python, and where is the documentation for them?

I believe soaplib has deprecated its SOAP client ('sender') in favor of suds. At this point soaplib is focused on being a web framework agnostic SOAP server ('receiver'). Currently soaplib is under active development and is usually discussed in the Python SOAP mailing list:

http://mail.python.org/mailman/listinfo/soap

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

Using margin / padding to space <span> from the rest of the <p>

Try in html:

style="display: inline-block; margin-top: 50px;"

or in css:

display: inline-block;
margin-top: 50px;

How can I get the count of line in a file in an efficient way?

If the already posted answers aren't fast enough you'll probably have to look for a solution specific to your particular problem.

For example if these text files are logs that are only appended to and you regularly need to know the number of lines in them you could create an index. This index would contain the number of lines in the file, when the file was last modified and how large the file was then. This would allow you to recalculate the number of lines in the file by skipping over all the lines you had already seen and just reading the new lines.

Smooth GPS data

I have transformed the Java code from @Stochastically to Kotlin

class KalmanLatLong
{
    private val MinAccuracy: Float = 1f

    private var Q_metres_per_second: Float = 0f
    private var TimeStamp_milliseconds: Long = 0
    private var lat: Double = 0.toDouble()
    private var lng: Double = 0.toDouble()
    private var variance: Float =
        0.toFloat() // P matrix.  Negative means object uninitialised.  NB: units irrelevant, as long as same units used throughout

    fun KalmanLatLong(Q_metres_per_second: Float)
    {
        this.Q_metres_per_second = Q_metres_per_second
        variance = -1f
    }

    fun get_TimeStamp(): Long { return TimeStamp_milliseconds }
    fun get_lat(): Double { return lat }
    fun get_lng(): Double { return lng }
    fun get_accuracy(): Float { return Math.sqrt(variance.toDouble()).toFloat() }

    fun SetState(lat: Double, lng: Double, accuracy: Float, TimeStamp_milliseconds: Long)
    {
        this.lat = lat
        this.lng = lng
        variance = accuracy * accuracy
        this.TimeStamp_milliseconds = TimeStamp_milliseconds
    }

    /// <summary>
    /// Kalman filter processing for lattitude and longitude
    /// https://stackoverflow.com/questions/1134579/smooth-gps-data/15657798#15657798
    /// </summary>
    /// <param name="lat_measurement_degrees">new measurement of lattidude</param>
    /// <param name="lng_measurement">new measurement of longitude</param>
    /// <param name="accuracy">measurement of 1 standard deviation error in metres</param>
    /// <param name="TimeStamp_milliseconds">time of measurement</param>
    /// <returns>new state</returns>
    fun Process(lat_measurement: Double, lng_measurement: Double, accuracy: Float, TimeStamp_milliseconds: Long)
    {
        var accuracy = accuracy
        if (accuracy < MinAccuracy) accuracy = MinAccuracy

        if (variance < 0)
        {
            // if variance < 0, object is unitialised, so initialise with current values
            this.TimeStamp_milliseconds = TimeStamp_milliseconds
            lat = lat_measurement
            lng = lng_measurement
            variance = accuracy * accuracy
        }
        else
        {
            // else apply Kalman filter methodology

            val TimeInc_milliseconds = TimeStamp_milliseconds - this.TimeStamp_milliseconds

            if (TimeInc_milliseconds > 0)
            {
                // time has moved on, so the uncertainty in the current position increases
                variance += TimeInc_milliseconds.toFloat() * Q_metres_per_second * Q_metres_per_second / 1000
                this.TimeStamp_milliseconds = TimeStamp_milliseconds
                // TO DO: USE VELOCITY INFORMATION HERE TO GET A BETTER ESTIMATE OF CURRENT POSITION
            }

            // Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
            // NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
            val K = variance / (variance + accuracy * accuracy)
            // apply K
            lat += K * (lat_measurement - lat)
            lng += K * (lng_measurement - lng)
            // new Covarariance  matrix is (IdentityMatrix - K) * Covarariance
            variance = (1 - K) * variance
        }
    }
}

How to find the size of a table in SQL?

I know that in SQL 2012 (may work in other versions) you can do the following:

  1. Right click on the database name in the Object Explorer.
  2. Select Reports > Standard Reports > Disk Usage by Top Tables.

That will give you a list of the top 1000 tables and then you can order it by data size etc.

How to create User/Database in script for Docker Postgres

EDIT - since Jul 23, 2015

The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder.

So all you need is to create the following sql script:

init.sql

CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;

and add it in your Dockerfile:

Dockerfile

FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB environment variables:

docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres

or with a Dockerfile:

FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

for images older than Jul 23, 2015

From the documentation of the postgres Docker image, it is said that

[...] it will source any *.sh script found in that directory [/docker-entrypoint-initdb.d] to do further initialization before starting the service

What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".

After that there is another useful piece of information:

If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.

Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:

NOTE, this has changed recently in the following commit. This will work with the latest change:

export PGUSER=postgres
psql <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Previously, the use of --single mode was required:

gosu postgres postgres --single <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Append text to textarea with javascript

Give this a try:

<!DOCTYPE html>
<html>
<head>
    <title>List Test</title>
    <style>
        li:hover {
            cursor: hand; cursor: pointer;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                $('#alltext').append($(this).text());
            });
        });
    </script>
</head>
<body>

    <h2>List items</h2>
    <ol>
        <li>Hello</li>
        <li>World</li>
        <li>Earthlings</li>
    </ol>
    <form>
        <textarea id="alltext"></textarea>
    </form>

</body>
</html>

Change the background color of CardView programmatically

Use the property card_view:cardBackgroundColor:

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_gravity="center"
    card_view:cardCornerRadius="4dp"
    android:layout_margin="10dp"
    card_view:cardBackgroundColor="#fff"
    >

Map<String, String>, how to print both the "key string" and "value string" together

final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
        .stream()
        //depending on how you want to join K and V use different delimiter
        .map(entry -> 
        String.join(":", entry.getKey(),entry.getValue()))
        .forEach(System.out::println);

Eclipse Java Missing required source folder: 'src'

Right Click Project -> New -> Folder -> Folder Name: src -> Finish

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

The same result can be achieved using Lodash.

_x000D_
_x000D_
var result1 = [_x000D_
    {id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
    {id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
    {id:3, name:'Peter', type:'user', username:'pete'},_x000D_
    {id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
    {id:2, name:'John', email:'[email protected]'},_x000D_
    {id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var result3 = _(result1) _x000D_
        .differenceBy(result2, 'id', 'name')_x000D_
        .map(_.partial(_.pick, _, 'id', 'name'))_x000D_
        .value();_x000D_
_x000D_
console.log(result3);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

You can get the desired result applying a difference between both arrays using the properties "id" and "name" as a way to "link" elements between them. If any of those properties are different, the elements are considered different (improbably in your case because id seems to be unique).

Lastly, you have to map the result in order to "omit" the undesired properties of the object.

Hope it helps.

How to know/change current directory in Python shell?

If you import os you can use os.getcwd to get the current working directory, and you can use os.chdir to change your directory

ORA-01438: value larger than specified precision allows for this column

From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):

ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.

http://ora-06512.ora-code.com/:

ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.

Apply pandas function to column to create multiple new columns?

Building off of user1827356 's answer, you can do the assignment in one pass using df.merge:

df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})), 
    left_index=True, right_index=True)

    textcol  feature1  feature2
0  0.772692  1.772692 -0.227308
1  0.857210  1.857210 -0.142790
2  0.065639  1.065639 -0.934361
3  0.819160  1.819160 -0.180840
4  0.088212  1.088212 -0.911788

EDIT: Please be aware of the huge memory consumption and low speed: https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/ !

Beautiful Soup and extracting a div and its contents by ID

I used:

soup.findAll('tag', attrs={'attrname':"attrvalue"})

As my syntax for find/findall; that said, unless there are other optional parameters between the tag and attribute list, this shouldn't be different.

How do I trim whitespace from a string?

If you want to trim specified number of spaces from left and right, you could do this:

def remove_outer_spaces(text, num_of_leading, num_of_trailing):
    text = list(text)
    for i in range(num_of_leading):
        if text[i] == " ":
            text[i] = ""
        else:
            break

    for i in range(1, num_of_trailing+1):
        if text[-i] == " ":
            text[-i] = ""
        else:
            break
    return ''.join(text)

txt1 = "   MY name is     "
print(remove_outer_spaces(txt1, 1, 1))  # result is: "  MY name is    "
print(remove_outer_spaces(txt1, 2, 3))  # result is: " MY name is  "
print(remove_outer_spaces(txt1, 6, 8))  # result is: "MY name is"

bootstrap 4 file input doesn't show the file name

This code works for me:

<script type="application/javascript">
    $('#elementID').change(function(event){
        var fileName = event.target.files[0].name;
        if (event.target.nextElementSibling!=null){
            event.target.nextElementSibling.innerText=fileName;
        }
    });
</script>

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

Here's another option for you. I tested it by creating a sample application, I then put a GroupBox and a GroupBox inside the initial GroupBox. Inside the nested GroupBox I put 3 TextBox controls and a button. This is the code I used (even includes the recursion you were looking for)

public IEnumerable<Control> GetAll(Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll(ctrl,type))
                              .Concat(controls)
                              .Where(c => c.GetType() == type);
}

To test it in the form load event I wanted a count of all controls inside the initial GroupBox

private void Form1_Load(object sender, EventArgs e)
{
    var c = GetAll(this,typeof(TextBox));
    MessageBox.Show("Total Controls: " + c.Count());
}

And it returned the proper count each time, so I think this will work perfectly for what you're looking for :)

remove / reset inherited css from an element

From what I understand you want to use a div that inherits from no class but yours. As mentioned in the previous reply you cannot completely reset a div inheritance. However, what worked for me with that issue was to use another element - one that is not frequent and certainly not used in the current html page. A good example, is to use instead of then customize it to look just like your ideal would.

area { background-color : red; }

Zip lists in Python

In Python 3 zip returns an iterator instead and needs to be passed to a list function to get the zipped tuples:

x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]

Then to unzip them back just conjugate the zipped iterator:

x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')

If the original form of list is needed instead of tuples:

x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

How do I get PHP errors to display?

This will work:

<?php
     error_reporting(E_ALL);
     ini_set('display_errors', 1);    
?>

Import an existing git project into GitLab?

I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:

To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named Kint (under namespace raveren) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.git

The commands are OS agnostic.

In a new directory:

git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror

Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:

git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all

*This assumes that you did not rename your remote master from origin, otherwise, change the first two lines to reflect it.

sys.argv[1] meaning in script

Just adding to Frederic's answer, for example if you call your script as follows:

./myscript.py foo bar

sys.argv[0] would be "./myscript.py" sys.argv[1] would be "foo" and sys.argv[2] would be "bar" ... and so forth.

In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".

How do I get whole and fractional parts from double in JSP/Java?

String value = "3.06";

if(!value.isEmpty()){
    if(value.contains(".")){    
        String block = value.substring(0,value.indexOf("."));
        System.out.println(block);
    }else{
        System.out.println(value);
    }
}

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Here is an alternative way if the data frame just contains numbers.

_x000D_
_x000D_
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
_x000D_
_x000D_

but the most reliable way of converting a data frame to a matrix is using data.matrix() function.

Unable to locate tools.jar

I had the same problem and copying C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar to C:\Program Files\Java\jre6\lib\ext worked for me

How to show full object in Chrome console?

You might get better results if you try:

console.log(JSON.stringify(functor));

How can I remove a button or make it invisible in Android?

First make the button invisible in xml file.Then set button visible in java code if needed.

Button resetButton=(Button)findViewById(R.id.my_button_del);
resetButton.setVisibility(View.VISIBLE); //To set visible

Xml:

<Button
android:text="Delete"
android:id="@+id/my_button_del"
android:layout_width="72dp" 
android:layout_height="40dp"
android:visibility="invisible"/>

How do I extract data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

Find the IP address of the client in an SSH session

who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'


export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0

I use this to determine my DISPLAY variable for the session when logging in via ssh and need to display remote X.

Is it possible to assign numeric value to an enum in Java?

I realize this is an older question, but it comes up first in a Google search, and among the excellent answers provided, I didn't see anything fully comprehensive, so I did a little more digging and I ended up writing an enum class that not only allowed me to assign multiple custom values to the enum constants, I even added a method that allows me to assign values to them on the fly during code execution.

This enum class is for a "server" program that I run on a Raspberry Pi. The program receives commands from a client then it executes terminal commands that make adjustments to a webcam that is affixed to my 3D printer.

Using the Linux program 'v4l2-ctl' on the Pi, you can extract all of the possible adjustment commands for a given attached webcam, which also provides the setting datatype, the min and max values, the number of value steps in a given value range etc., so I took all of those and put them in an enum and created an enum interface that makes it easy to both set and get values for each command as well as a simple method to get the actual terminal command that is executed (using the Process and Runtime classes) in order to adjust the setting.

It is a rather large class and I apologize for that, but for me, it's always easier to learn something when I can see it working in full context, so I decided not to scale it down. However, even though it's large, it is definitely simple and it should be obvious what's happening in the class with minimal effort.

package constants;

import java.util.HashMap;
import java.util.Map;

public enum PICam {
    BRIGHTNESS                  ("brightness",                  0,      "int",      0,      100,    1,  50),
    CONTRAST                    ("contrast",                    1,      "int",      100,    100,    1,  0),
    SATURATION                  ("saturation",                  2,      "int",      100,    100,    1,  0),
    RED_BALANCE                 ("red_balance",                 3,      "intmenu",  1,      7999,   1,  1000),
    BLUE_BALANCE                ("blue_balance",                4,      "int",      1,      7999,   1,  1000),
    HORIZONTAL_FLIP             ("horizontal_flip",             5,      "bool",     0,      1,      1,  0),
    VERTICAL_FLIP               ("vertical_flip",               6,      "bool",     0,      1,      1,  0),
    POWER_LINE_FREQUENCY        ("power_line_frequency",        7,      "menu",     0,      3,      1,  1),
    SHARPNESS                   ("sharpness",                   8,      "int",      100,    100,    1,  0),
    COLOR_EFFECTS               ("color_effects",               9,      "menu",     0,      15,     1,  0),
    ROTATE                      ("rotate",                      10,     "int",      0,      360,    90, 0),
    COLOR_EFFECTS_CBCR          ("color_effects_cbcr",          11,     "int",      0,      65535,  1,  32896),
    VIDEO_BITRATE_MODE          ("video_bitrate_mode",          12,     "menu",     0,      1,      1,  0),
    VIDEO_BITRATE               ("video_bitrate",               13,     "int",      25000,  25000000,   25000,  10000000),
    REPEAT_SEQUENCE_HEADER      ("repeat_sequence_header",      14,     "bool",     0,      1,      1,  0),
    H264_I_FRAME_PERIOD         ("h_264_i_frame_period",        15,     "int",      0,      2147483647,1,   60),
    H264_LEVEL                  ("h_264_level",                 16,     "menu",     0,      11,     1,  11),
    H264_PROFILE                ("h_264_profile",               17,     "menu",     0,      4,      1,  4),
    AUTO_EXPOSURE               ("auto_exposure",               18,     "menu",     0,      3,      1,  0),
    EXPOSURE_TIME_ABSOLUTE      ("exposure_time_absolute",      19,     "int",      1,      10000,  1,  1000),
    EXPOSURE_DYNAMIC_FRAMERATE  ("exposure_dynamic_framerate",  20,     "bool",     0,      1,      1,  0),
    AUTO_EXPOSURE_BIAS          ("auto_exposure_bias",          21,     "intmenu",  0,      24,     1,  12),
    WHITE_BALANCE_AUTO_PRESET   ("white_balance_auto_preset",   22,     "menu",     0,      9,      1,  1),
    IMAGE_STABILIZATION         ("image_stabilization",         23,     "bool",     0,      1,      1,  0),
    ISO_SENSITIVITY             ("iso_sensitivity",             24,     "intmenu",  0,      4,      1,  0),
    ISO_SENSITIVITY_AUTO        ("iso_sensitivity_auto",        25,     "menu",     0,      1,      1,  1),
    EXPOSURE_METERING_MODE      ("exposure_metering_mode",      26,     "menu",     0,      2,      1,  0),
    SCENE_MODE                  ("scene_mode",                  27,     "menu",     0,      13,     1,  0),
    COMPRESSION_QUALITY         ("compression_quality",         28,     "int",      1,      100,    1,  30);


    private static final Map<String, PICam>    LABEL_MAP       = new HashMap<>();
    private static final Map<Integer, PICam>   INDEX_MAP       = new HashMap<>();
    private static final Map<String, PICam>    TYPE_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   MIN_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   MAX_MAP         = new HashMap<>();
    private static final Map<Integer, PICam>   STEP_MAP        = new HashMap<>();
    private static final Map<Integer, PICam>   DEFAULT_MAP     = new HashMap<>();
    private static final Map<Integer, Integer> THIS_VALUE_MAP  = new HashMap<>();

    private static final String                baseCommandLine = "/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=";

    static {
        for (PICam e: values()) {
            LABEL_MAP.put(e.label, e);
            INDEX_MAP.put(e.index, e);
            TYPE_MAP.put(e.type, e);
            MIN_MAP.put(e.min, e);
            MAX_MAP.put(e.max, e);
            STEP_MAP.put(e.step, e);
            DEFAULT_MAP.put(e.defaultValue, e);
        }
    }

    public final String label;
    public final int index;
    public final String type;
    public final int min;
    public final int max;
    public final int step;
    public final int defaultValue;

    private PICam(String label, int index, String type, int min, int max, int step, int defaultValue) {
        this.label = label;
        this.index = index;
        this.type = type;
        this.min = min;
        this.max = max;
        this.step = step;
        this.defaultValue = defaultValue;
    }

    public static void setValue(Integer index, Integer value) {
        if (THIS_VALUE_MAP.containsKey(index)) THIS_VALUE_MAP.replace(index, value);
        else THIS_VALUE_MAP.put(index, value);
    }

    public Integer getValue (Integer index) {
        return THIS_VALUE_MAP.getOrDefault(index, null);
    }

    public static PICam getLabel(String label) {
        return LABEL_MAP.get(label);
    }

    public static PICam getType(String type) {
        return TYPE_MAP.get(type);
    }

    public static PICam getMin(int min) {
        return MIN_MAP.get(min);
    }

    public static PICam getMax(int max) {
        return MAX_MAP.get(max);
    }

    public static PICam getStep(int step) {
        return STEP_MAP.get(step);
    }

    public static PICam getDefault(int defaultValue) {
        return DEFAULT_MAP.get(defaultValue);
    }

    public static String getCommandFor(int index, int newValue) {
        PICam picam = INDEX_MAP.get(index);
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam picam, Integer newValue) {
        String commandValue = "";
        if ("bool".equals(picam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + INDEX_MAP.get(picam.index).label + "=" + commandValue;
    }

    public static String getCommandFor(PICam piCam) {
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }

    public static String getCommandFor(Integer index) {
        PICam piCam = INDEX_MAP.get(index);
        int    newValue     = piCam.defaultValue;
        String commandValue = "";
        if ("bool".equals(piCam.type)) {
            commandValue = (newValue == 0) ? "false" : "true";
        }
        else {
            commandValue = String.valueOf(newValue);
        }
        return baseCommandLine + piCam.label + "=" + commandValue;
    }
}

Here are some ways that the class can be interacted with:

This code:

public static void test() {
    PICam.setValue(0,127); //Set brightness to 125
    PICam.setValue(PICam.SHARPNESS,143); //Set sharpness to 125
    String command1 = PICam.getSetCommandStringFor(PICam.BRIGHTNESS); //Get command line string to include the brightness value that we previously set referencing it by enum constant.
    String command2 = PICam.getSetCommandStringFor(0); //Get command line string to include the brightness value that we previously set referencing it by index number.
    String command3 = PICam.getDefaultCamString(PICam.BRIGHTNESS); //Get command line string with the default value
    String command4 = PICam.getSetCommandStringFor(PICam.SHARPNESS); //Get command line string with the sharpness value that we previously set.
    String command5 = PICam.getDefaultCamString(PICam.SHARPNESS); //Get command line string with the default sharpness value.
    System.out.println(command1);
    System.out.println(command2);
    System.out.println(command3);
    System.out.println(command4);
    System.out.println(command5);
}

Produces these results:

/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=127
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=brightness=50
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=143
/usr/bin/v4l2-ctl -d /dev/video0 --set-ctrl=sharpness=0

Pandas read in table without headers

In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None and usecols=[3,6] for the 4th and 7th columns:

df = pd.read_csv(file_path, header=None, usecols=[3,6])

See the docs

How to search text using php if ($text contains "World")

The best solution is my method:

In my method, only full words are detected,But in other ways it is not.

for example:

$text='hello world!'; 

if(strpos($text, 'wor') === FALSE) { 
   echo '"wor" not found in string'; 
}

Result: strpos returned true!!! but in my method return false.

My method:

public function searchInLine($txt,$word){

    $txt=strtolower($txt);
    $word=strtolower($word);
    $word_length=strlen($word);
    $string_length=strlen($txt);
    if(strpos($txt,$word)!==false){
        $indx=strpos($txt,$word);
        $last_word=$indx+$word_length;
        if($indx==0){
            if(strpos($txt,$word." ")!==false){
                return true;
            }
            if(strpos($txt,$word.".")!==false){
                return true;
            }
            if(strpos($txt,$word.",")!==false){
                return true;
            }
            if(strpos($txt,$word."?")!==false){
                return true;
            }
            if(strpos($txt,$word."!")!==false){
                return true;
            }
        }else if($last_word==$string_length){
            if(strpos($txt," ".$word)!==false){
                return true;
            }
            if(strpos($txt,".".$word)!==false){
                return true;
            }
            if(strpos($txt,",".$word)!==false){
                return true;
            }
            if(strpos($txt,"?".$word)!==false){
                return true;
            }
            if(strpos($txt,"!".$word)!==false){
                return true;
            }

        }else{
            if(strpos($txt," ".$word." ")!==false){
                return true;
            }
            if(strpos($txt," ".$word.".")!==false){
                return true;
            }
            if(strpos($txt," ".$word.",")!==false){
                return true;
            }
            if(strpos($txt," ".$word."!")!==false){
                return true;
            }
            if(strpos($txt," ".$word."?")!==false){
                return true;
            }
        }
        }

    return false;
}

What is the MySQL VARCHAR max size?

You can use TEXT type, which is not limited to 64KB.

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

Removing App ID from Developer Connection

Update: You can now remove an App ID (as noted by @Guru in the comments).

In the past, this was not possible: I had the same problem, and the folks at Apple replied that they will leave all of the App ID you create associated to your login, to keep track of a sort of history related to your login.

It seems that they finally changed idea about.

CSS selector for text input fields?

input[type=text]

This will select all the input type text in a web-page.

jQuery textbox change event doesn't fire until textbox loses focus?

$(this).bind('input propertychange', function() {
        //your code here
    });

This is works for typing, paste, right click mouse paste etc.

Calculate the execution time of a method

 using System.Diagnostics;
 class Program
 {
    static void Test1()
    {
        for (int i = 1; i <= 100; i++)
        {
            Console.WriteLine("Test1 " + i);
        }
    }
  static void Main(string[] args)
    {

        Stopwatch sw = new Stopwatch();
        sw.Start();
        Test1();
        sw.Stop();
        Console.WriteLine("Time Taken-->{0}",sw.ElapsedMilliseconds);
   }
 }

How do I sort a table in Excel if it has cell references in it?

Another solution is to: (1) copy the whole table - paste as a link in the same spreadsheet, from now on work only on the 'linked table' (2) copy the column with values to be sorted and paste values only just next to the table you want to sort (3) select the table and replace all = with e.g. #, this will change reference in a static text (4) sort the table by the pasted values (5) replace back all # with =, the references are back Done! It goes pretty fast when using excel shortcuts

Valid to use <a> (anchor tag) without href attribute?

Yes, it is valid to use the anchor tag without a href attribute.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

Yes, you can use class and other attributes, but you can not use target, download, rel, hreflang, and type.

The target, download, rel, hreflang, and type attributes must be omitted if the href attribute is not present.

As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a> without href. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.

Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link).

Source: W3C HTML5 Recommendation

Learning Ruby on Rails

Ruby: I used Learn to program (in a weekend), Ruby Visual QuickStart (believe it or not this QS book was "off the hook" excellent). This took about a week.

Rails: I just went through Learn Rails in one "aggressive" week. Definitely feel I have the nuts and bolts. It's 2009 which I deemed important!

Now I plan to combine a more advanced book with a real project.

IDE: VIM with rails plugin is great if you're a vim addict. Otherwise, try any suggested above.

Of course railscast, etc., are useful for most up to date stuff.

Setting timezone in Python

It's not an answer, but...

To get datetime components individually, better use datetime.timetuple:

time = datetime.now()
time.timetuple()
#-> time.struct_time(
#    tm_year=2014, tm_mon=9, tm_mday=7, 
#    tm_hour=2, tm_min=38, tm_sec=5, 
#    tm_wday=6, tm_yday=250, tm_isdst=-1
#)

It's now easy to get the parts:

ts = time.timetuple()
ts.tm_year
ts.tm_mon
ts.tm_mday
ts.tm_hour
ts.tm_min
ts.tm_sec

How to update specific key's value in an associative array in PHP?

This will work too!

foreach($data as &$value) {
  $value['transaction_date'] = date('d/m/Y', $value['transaction_date']);
}

Yay for alternatives!

How To Convert A Number To an ASCII Character?

I was googling about how to convert an int to char, that got me here. But my question was to convert for example int of 6 to char of '6'. For those who came here like me, this is how to do it:

int num = 6;
num.ToString().ToCharArray()[0];

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

How can I get the corresponding table header (th) from a table cell (td)?

var $th = $("table thead tr th").eq($td.index())

It would be best to use an id to reference the table if there is more than one.

Automatic vertical scroll bar in WPF TextBlock?

Something better would be:

<Grid Width="Your-specified-value" >
    <ScrollViewer>
         <TextBlock Width="Auto" TextWrapping="Wrap" />
    </ScrollViewer>
</Grid>

This makes sure that the text in your textblock does not overflow and overlap the elements below the textblock as may be the case if you do not use the grid. That happened to me when I tried other solutions even though the textblock was already in a grid with other elements. Keep in mind that the width of the textblock should be Auto and you should specify the desired with in the Grid element. I did this in my code and it works beautifully. HTH.

ASP.NET Core Web API Authentication

You can implement a middleware which handles Basic authentication.

public async Task Invoke(HttpContext context)
{
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
    {
        var token = authHeader.Substring("Basic ".Length).Trim();
        System.Console.WriteLine(token);
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
        {
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        }
    }
    else
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
    }
    await _next(context);
}

This code is written in a beta version of asp.net core. Hope it helps.

Removing carriage return and new-line from the end of a string in c#

This should work ...

var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

Attempt to set a non-property-list object as an NSUserDefaults

It seems rather wasteful to me to run through the array and encode the objects into NSData yourself. Your error BC_Person is a non-property-list object is telling you that the framework doesn't know how to serialize your person object.

So all that is needed is to ensure that your person object conforms to NSCoding then you can simply convert your array of custom objects into NSData and store that to defaults. Heres a playground:

Edit: Writing to NSUserDefaults is broken on Xcode 7 so the playground will archive to data and back and print an output. The UserDefaults step is included in case its fixed at a later point

//: Playground - noun: a place where people can play

import Foundation

class Person: NSObject, NSCoding {
    let surname: String
    let firstname: String

    required init(firstname:String, surname:String) {
        self.firstname = firstname
        self.surname = surname
        super.init()
    }

    //MARK: - NSCoding -
    required init(coder aDecoder: NSCoder) {
        surname = aDecoder.decodeObjectForKey("surname") as! String
        firstname = aDecoder.decodeObjectForKey("firstname") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(firstname, forKey: "firstname")
        aCoder.encodeObject(surname, forKey: "surname")
    }
}

//: ### Now lets define a function to convert our array to NSData

func archivePeople(people:[Person]) -> NSData {
    let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(people as NSArray)
    return archivedObject
}

//: ### Create some people

let people = [Person(firstname: "johnny", surname:"appleseed"),Person(firstname: "peter", surname: "mill")]

//: ### Archive our people to NSData

let peopleData = archivePeople(people)

if let unarchivedPeople = NSKeyedUnarchiver.unarchiveObjectWithData(peopleData) as? [Person] {
    for person in unarchivedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Failed to unarchive people")
}

//: ### Lets try use NSUserDefaults
let UserDefaultsPeopleKey = "peoplekey"
func savePeople(people:[Person]) {
    let archivedObject = archivePeople(people)
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(archivedObject, forKey: UserDefaultsPeopleKey)
    defaults.synchronize()
}

func retrievePeople() -> [Person]? {
    if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsPeopleKey) as? NSData {
        return NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [Person]
    }
    return nil
}

if let retrievedPeople = retrievePeople() {
    for person in retrievedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Writing to UserDefaults is still broken in playgrounds")
}

And Voila, you have stored an array of custom objects into NSUserDefaults

String length in bytes in JavaScript

This would work for BMP and SIP/SMP characters.

    String.prototype.lengthInUtf8 = function() {
        var asciiLength = this.match(/[\u0000-\u007f]/g) ? this.match(/[\u0000-\u007f]/g).length : 0;
        var multiByteLength = encodeURI(this.replace(/[\u0000-\u007f]/g)).match(/%/g) ? encodeURI(this.replace(/[\u0000-\u007f]/g, '')).match(/%/g).length : 0;
        return asciiLength + multiByteLength;
    }

    'test'.lengthInUtf8();
    // returns 4
    '\u{2f894}'.lengthInUtf8();
    // returns 4
    '???? ?????'.lengthInUtf8();
    // returns 19, each Arabic/Persian alphabet character takes 2 bytes. 
    '??,JavaScript ??'.lengthInUtf8();
    // returns 26, each Chinese character/punctuation takes 3 bytes. 

How can I initialise a static Map?

I like the anonymous class syntax; it's just less code. However, one major con I have found is that you won't be able to serialize that object via remoting. You will get an exception about not being able to find the anonymous class on the remote side.

How to correctly use "section" tag in HTML5?

The answer is in the current spec:

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.

The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

Reference:

Also see:

It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div> is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").

A better example, from my understanding, might look something like this:

<div id="content">
  <article>
     <h2>How to use the section tag</h2>
     <section id="disclaimer">
         <h3>Disclaimer</h3>
         <p>Don't take my word for it...</p>
     </section>
     <section id="examples">
       <h3>Examples</h3>
       <p>But here's how I would do it...</p>
     </section>
     <section id="closing_notes">
       <h3>Closing Notes</h3>
       <p>Well that was fun. I wonder if the spec will change next week?</p>
     </section>
  </article>
</div>

Note that <div>, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

This is rather commonly caused by Avast.

I can usually run my projects in Release regardless, but when running in debug it would pretty regularly fail.

I just add an exclusion for my projects folder and the problem seems to go away. I assume this might also be cause by other antivirus software.

Selecting text in an element (akin to highlighting with your mouse)

I was searching for the same thing, my solution was this:

$('#el-id').focus().select();

How to decompile a whole Jar file?

Note: This solution only works for Mac and *nix users.

I also tried to find Jad with no luck. My quick solution was to download MacJad that contains jad. Once you downloaded it you can find jad in [where-you-downloaded-macjad]/MacJAD/Contents/Resources/jad.

"Unmappable character for encoding UTF-8" error

The compiler is using the UTF-8 character encoding to read your source file. But the file must have been written by an editor using a different encoding. Open your file in an editor set to the UTF-8 encoding, fix the quote mark, and save it again.

Alternatively, you can find the Unicode point for the character and use a Unicode escape in the source code. For example, the character A can be replaced with the Unicode escape \u0041.

By the way, you don't need to use the begin- and end-line anchors ^ and $ when using the matches() method. The entire sequence must be matched by the regular expression when using the matches() method. The anchors are only useful with the find() method.

How to define a relative path in java

I was having issues attaching screenshots to ExtentReports using a relative path to my image file. My current directory when executing is "C:\Eclipse 64-bit\eclipse\workspace\SeleniumPractic". Under this, I created the folder ExtentReports for both the report.html and the image.png screenshot as below.

private String className = getClass().getName();
private String outputFolder = "ExtentReports\\";
private String outputFile = className  + ".html";
ExtentReports report;
ExtentTest test;

@BeforeMethod
    //  initialise report variables
    report = new ExtentReports(outputFolder + outputFile);
    test = report.startTest(className);
    // more setup code

@Test
    // test method code with log statements

@AfterMethod
    // takeScreenShot returns the relative path and filename for the image
    String imgFilename = GenericMethods.takeScreenShot(driver,outputFolder);
    String imagePath = test.addScreenCapture(imgFilename);
    test.log(LogStatus.FAIL, "Added image to report", imagePath);

This creates the report and image in the ExtentReports folder, but when the report is opened and the (blank) image inspected, hovering over the image src shows "Could not load the image" src=".\ExtentReports\QXKmoVZMW7.png".

This is solved by prefixing the relative path and filename for the image with the System Property "user.dir". So this works perfectly and the image appears in the html report.

Chris

String imgFilename = GenericMethods.takeScreenShot(driver,System.getProperty("user.dir") + "\\" + outputFolder);
String imagePath = test.addScreenCapture(imgFilename);
test.log(LogStatus.FAIL, "Added image to report", imagePath);

Start a fragment via Intent within a Fragment

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

String, StringBuffer, and StringBuilder

  • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
  • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
  • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

See an example here.

How to find the socket connection state in C?

You should try to use: getpeername function.

now when the connection is down you will get in errno: ENOTCONN - The socket is not connected. which means for you DOWN.

else (if no other failures) there the return code will 0 --> which means UP.

resources: man page: http://man7.org/linux/man-pages/man2/getpeername.2.html

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

I already tried all of the possible solutions on stackoverflow and didn't work What I tried:

  1. Disable Hyper-V in windows feature
  2. Disable Hyper-V with command
  3. Disable Device Guard
  4. etc etc Above solution still give me information about Hyper-V in System Information and the HAXM still failed to install.

But finally I found the solution, you have to disable Hyper-V from System Configuration:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

Check System Information then Hyper-V is off now

Selenium webdriver click google search

There would be multiple ways to find an element (in your case the third Google Search result).

One of the ways would be using Xpath

#For the 3rd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[3]/div/h3/a")).click();
#For the 1st Link
driver.findElement(By.xpath(".//*[@id='rso']/li[2]/div/h3/a")).click();
#For the 2nd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[1]/div/h3/a")).click();

The other options are

By.ByClassName 
By.ByCssSelector 
By.ById
By.ByLinkText
By.ByName
By.ByPartialLinkText 
By.ByTagName 

To better understand each one of them, you should try learning Selenium on something simpler than the Google Search Result page.

Example - http://www.google.com/intl/gu/contact/

To Interact with the Text input field with the placeholder "How can we help? Ask here." You could do it this way -

# By.ByClassName 
driver.findElement(By.ClassName("searchbox")).sendKeys("Hey!");
# By.ByCssSelector 
driver.findElement(By.CssSelector(".searchbox")).sendKeys("Hey!");
# By.ById
driver.findElement(By.Id("query")).sendKeys("Hey!");
# By.ByName
driver.findElement(By.Name("query")).sendKeys("Hey!");
# By.ByXpath
driver.findElement(By.xpath(".//*[@id='query']")).sendKeys("Hey!");

How to move screen without moving cursor in Vim?

  • zz - move current line to the middle of the screen
    (Careful with zz, if you happen to have Caps Lock on accidentally, you will save and exit vim!)
  • zt - move current line to the top of the screen
  • zb - move current line to the bottom of the screen

jQuery text() and newlines

I would suggest to work with the someElem element directly, as replacements with .html() would replace other HTML tags within the string as well.

Here is my function:

function nl2br(el) {
  var lines = $(el).text().split(/\n/);
  $(el).empty();
  for (var i = 0 ; i < lines.length ; i++) {
    if (i > 0) $(el).append('<br>');
    $(el).append(document.createTextNode(lines[i]));
  }
  return el;
}

Call it by:

someElem = nl2br(someElem);

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

How to select data where a field has a min value in MySQL?

To make it simpler

SELECT *,MIN(price) FROM prod LIMIT 1

  • Put * so it will display the all record of the minimum value

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

Clearing a string buffer/builder after loop

The easiest way to reuse the StringBuffer is to use the method setLength()

public void setLength(int newLength)

You may have the case like

StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb

Fastest way to zero out a 2d array in C?

int array[N][M] = {0};

...at least in GCC 4.8.

What is the difference between map and flatMap and a good use case for each?

Generally we use word count example in hadoop. I will take the same use case and will use map and flatMap and we will see the difference how it is processing the data.

Below is the sample data file.

hadoop is fast
hive is sql on hdfs
spark is superfast
spark is awesome

The above file will be parsed using map and flatMap.

Using map

>>> wc = data.map(lambda line:line.split(" "));
>>> wc.collect()
[u'hadoop is fast', u'hive is sql on hdfs', u'spark is superfast', u'spark is awesome']

Input has 4 lines and output size is 4 as well, i.e., N elements ==> N elements.

Using flatMap

>>> fm = data.flatMap(lambda line:line.split(" "));
>>> fm.collect()
[u'hadoop', u'is', u'fast', u'hive', u'is', u'sql', u'on', u'hdfs', u'spark', u'is', u'superfast', u'spark', u'is', u'awesome']

The output is different from map.


Let's assign 1 as value for each key to get the word count.

  • fm: RDD created by using flatMap
  • wc: RDD created using map
>>> fm.map(lambda word : (word,1)).collect()
[(u'hadoop', 1), (u'is', 1), (u'fast', 1), (u'hive', 1), (u'is', 1), (u'sql', 1), (u'on', 1), (u'hdfs', 1), (u'spark', 1), (u'is', 1), (u'superfast', 1), (u'spark', 1), (u'is', 1), (u'awesome', 1)]

Whereas flatMap on RDD wc will give the below undesired output:

>>> wc.flatMap(lambda word : (word,1)).collect()
[[u'hadoop', u'is', u'fast'], 1, [u'hive', u'is', u'sql', u'on', u'hdfs'], 1, [u'spark', u'is', u'superfast'], 1, [u'spark', u'is', u'awesome'], 1]

You can't get the word count if map is used instead of flatMap.

As per the definition, difference between map and flatMap is:

map: It returns a new RDD by applying given function to each element of the RDD. Function in map returns only one item.

flatMap: Similar to map, it returns a new RDD by applying a function to each element of the RDD, but output is flattened.

How do I automatically resize an image for a mobile site?

For me, it worked best to add this in image css: max-width:100%; and NOT specify image width and height in html parameters. This adjusted the width to fit in device screen while adjusting height automatically. Otherwise height might be distorted.

How to add a scrollbar to an HTML5 table?

use this table into a DIV

<div class="tbl_container">
<table> .... </table>
</div>


.tbl_container{ overflow:auto; width: 500px;height: 200px; }

and beside this if you want to make it more beautiful and attractive use the jscollpane to customized your scrollbar..

How can I pass a username/password in the header to a SOAP WCF Service

Suppose you are calling a web service using HttpWebRequest and HttpWebResponse, because .Net client doest support the structure of the WSLD that your are trying to consume.

In that case you can add the security credentials on the headers like:

<soap:Envelpe>
<soap:Header>
    <wsse:Security soap:mustUnderstand='true' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'><wsse:UsernameToken wsu:Id='UsernameToken-3DAJDJSKJDHFJASDKJFKJ234JL2K3H2K3J42'><wsse:Username>YOU_USERNAME/wsse:Username><wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>YOU_PASSWORD</wsse:Password><wsse:Nonce EncodingType='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary'>3WSOKcKKm0jdi3943ts1AQ==</wsse:Nonce><wsu:Created>2015-01-12T16:46:58.386Z</wsu:Created></wsse:UsernameToken></wsse:Security>
</soapHeather>
<soap:Body>
</soap:Body>


</soap:Envelope>

You can use SOAPUI to get the wsse Security, using the http log.

Be careful because it is not a safe scenario.

Best way to store data locally in .NET (C#)

Without knowing what your data looks like, i.e. the complexity, size, etc...XML is easy to maintain and easily accessible. I would NOT use an Access database, and flat files are more difficult to maintain over the long haul, particularly if you are dealing with more than one data field/element in your file.

I deal with large flat-file data feeds in good quantities daily, and even though an extreme example, flat-file data is much more difficult to maintain than the XML data feeds I process.

A simple example of loading XML data into a dataset using C#:

DataSet reportData = new DataSet();

reportData.ReadXml(fi.FullName);

You can also check out LINQ to XML as an option for querying the XML data...

HTH...

Multiple Where clauses in Lambda expressions

You can include it in the same where statement with the && operator...

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
    && l.InternalName != String.Empty)

You can use any of the comparison operators (think of it like doing an if statement) such as...

List<Int32> nums = new List<int>();

nums.Add(3);
nums.Add(10);
nums.Add(5);

var results = nums.Where(x => x == 3 || x == 10);

...would bring back 3 and 10.

how to convert binary string to decimal?

ES6 supports binary numeric literals for integers, so if the binary string is immutable, as in the example code in the question, one could just type it in as it is with the prefix 0b or 0B:

var binary = 0b1101000; // code for 104
console.log(binary); // prints 104

Java Array Sort descending?

First you need to sort your array using:

Collections.sort(myArray);

Then you need to reverse the order from ascending to descending using:

Collections.reverse(myArray);

Change the spacing of tick marks on the axis of a plot?

I just discovered the Hmisc package:

Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.

library(Hmisc)    
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

No events get triggered when the element is having disabled attribute.

None of the below will get triggered.

$("[disabled]").click( function(){ console.log("clicked") });//No Impact
$("[disabled]").hover( function(){ console.log("hovered") });//No Impact
$("[disabled]").dblclick( function(){ console.log("double clicked") });//No Impact

While readonly will be triggered.

$("[readonly]").click( function(){ console.log("clicked") });//log - clicked
$("[readonly]").hover( function(){ console.log("hovered") });//log - hovered
$("[readonly]").dblclick( function(){ console.log("double clicked") });//log - double clicked

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

you may check this equation i think it will help

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

Oracle: How to filter by date and time in a where clause

Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.

Update:

You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.

X-Frame-Options Allow-From multiple domains

Not exactly the same, but could work for some cases: there is another option ALLOWALL which will effectively remove the restriction, which might be a nice thing for testing/pre-production environments

Convert command line argument to string

It's simple. Just do this:

#include <iostream>
#include <vector>
#include <string.h>

int main(int argc, char *argv[])
{
    std::vector<std::string> argList;
    for(int i=0;i<argc;i++)
        argList.push_back(argv[i]);
    //now you can access argList[n]
}

@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

its because of Headerfiles define what the class contains (Members, data-structures) and cpp files implement it.

And of course, the main reason for this is that you could include one .h File multiple times in other .h files, but this would result in multiple definitions of a class, which is invalid.

How to change the remote a branch is tracking?

This is the easiest command:

git push --set-upstream <new-origin> <branch-to-track>

For example, given the command git remote -v produces something like:

origin  ssh://[email protected]/~myself/projectr.git (fetch)
origin  ssh://[email protected]/~myself/projectr.git (push)
team    ssh://[email protected]/vbs/projectr.git (fetch)
team    ssh://[email protected]/vbs/projectr.git (push)

To change to tracking the team instead:

git push --set-upstream team master

Check if a value exists in ArrayList

public static void linktest()
{
    System.setProperty("webdriver.chrome.driver","C://Users//WDSI//Downloads/chromedriver.exe");
    driver=new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://toolsqa.wpengine.com/");
    //List<WebElement> allLinkElements=(List<WebElement>) driver.findElement(By.xpath("//a"));
    //int linkcount=allLinkElements.size();
    //System.out.println(linkcount);
    List<WebElement> link = driver.findElements(By.tagName("a"));
    String data="HOME";
    int linkcount=link.size();
    System.out.println(linkcount);
    for(int i=0;i<link.size();i++) { 
        if(link.get(i).getText().contains(data)) {
            System.out.println("true");         
        }
    } 
}

Disable pasting text into HTML form

Using jquery, you can avoid copy paste and cut using this

$('.textboxClass').on('copy paste cut', function(e) {
    e.preventDefault();
});

Changing the page title with Jquery

There's no need to use jQuery to change the title. Try:

document.title = "blarg";

See this question for more details.

To dynamically change on button click:

$(selectorForMyButton).click(function(){
    document.title = "blarg";
});

To dynamically change in loop, try:

var counter = 0;

var titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
}, 100);

To string the two together so that it dynamically changes on button click, in a loop:

var counter = 0;

$(selectorForMyButton).click(function(){
  titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
  }, 100);
});

Trying to include a library, but keep getting 'undefined reference to' messages

If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in

extern "C" void foo();

Convert iterator to pointer?

The direct answer to your question is yes. If foo is a vector, you can do this: &foo[1].

This only works for vectors however, because the standard says that vectors implement storage by using contigious memory.

But you still can (and probably should) pass iterators instead of raw pointers because it is more expressive. Passing iterators does not make a copy of the vector.

Search an array for matching attribute

In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.

Shims can be found here: MDN Array.filter or ES5-shim

var result = restaurants.filter(function (chain) {
    return chain.restaurant.food === "chicken";
})[0].restaurant.name;

Retrieving parameters from a URL

The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def') directly to get your value from the object..

Open a PDF using VBA in Excel

Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .

Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook

Application.ScreenUpdating = False

Set Basebk = ThisWorkbook

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & "\"
mFolder = diaFolder.SelectedItems(1) & "\"
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & "\"
Filename = Dir(subFldr & "\*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
   Workbooks.Open Filename:=subFldr & "\" & Filename, ReadOnly:=True
   For Each Sheet In ActiveWorkbook.Sheets
   Set Actbk = ActiveWorkbook
   s = ActiveWorkbook.Name
   HK = Left(s, Len(s) - 4)
   If InStrRev(HK, "_S") <> 0 Then
   HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
   Else
   HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
   End If
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
   ActiveSheet.Name = HK

   ' Open pdf file to copy SIC Decsription
   pathAndFileName = subFlodr & J
   adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("0:00:2")

    SendKeys "%vpc"
    SendKeys "^a", True
    Application.Wait Now + TimeValue("00:00:2")

    ' send key to copy
     SendKeys "^c"
    ' wait 2 secs
     Application.Wait Now + TimeValue("00:00:2")
      ' activate this workook and paste the data
        ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(HK)
        Range("O1:O5").Select
        ws.Paste

        Application.Wait Now + TimeValue("00:00:3")
        Application.CutCopyMode = False
        Application.Wait Now + TimeValue("00:00:3")
       Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
       ' send key to close pdf file
        SendKeys "^q"
       Application.Wait Now + TimeValue("00:00:3")
 Next Sheet
 Workbooks(Filename).Close SaveAs = True
 Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub

I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement

Regards, Hema Kasturi

Password encryption/decryption code in .NET

One of the simplest methods of encryption (if you absolutely MUST make one up yourself since .NET has such awesome encryption libraries already [as provided by Cogwheel just before me]) is to XOR the ASCII value of each character of the input string against a known "key" value. XOR functionality in C# is accomplished using the ^ key I believe.

Then you can convert the values back from the result of the XOR to ASCII Chars, and store them in the database. This is not highly secure, but it is one of the easiest encryption methods.

Also, if using an access database, I've found that some characters when put in front of a string make the entire field unreadable when opening the database itself. But the field is still readable by your app even though it is blank to a malicious user. But who uses access anymore anyway right?

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

In your terminal type:

code --diff file1.txt file2.txt

A tab will open up in VS Code showing the differences in the two files.

How to change the Spyder editor background to dark?

In Spyder 2.3.8 on Ubuntu, I found several settings to do this - each one for a different part of the window... Seems that you can't make all areas dark though.

Editor

Inspector

Console

History

IPython

And the final result looks like this:

Final

grep for special characters in Unix

You could try removing any alphanumeric characters and space. And then use -n will give you the line number. Try following:

grep -vn "^[a-zA-Z0-9 ]*$" application.log

What is the standard exception to throw in Java for not supported/implemented operations?

If you create a new (not yet implemented) function in NetBeans, then it generates a method body with the following statement:

throw new java.lang.UnsupportedOperationException("Not supported yet.");

Therefore, I recommend to use the UnsupportedOperationException.

How to send a GET request from PHP?

Guzzle is a very well known library which makes it extremely easy to do all sorts of HTTP calls. See https://github.com/guzzle/guzzle. Install with composer require guzzlehttp/guzzle and run composer install. Now code below is enough for a http get call.

$client = new \GuzzleHttp\Client();
$response = $client->get('https://example.com/path/to/resource');

echo $response->getStatusCode();
echo $response->getBody();

Show values from a MySQL database table inside a HTML table on a webpage

OOP Style : At first connection with database.

<?php
class database
{

 public $host = "localhost";
 public $user = "root";
 public $pass = "";
 public $db   = "db";
 public $link;

 public function __construct()
 {
    $this->connect();
 }

 private function connect()
 {
   $this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->link;
 }

 public function select($query)
 {
    $result = $this->link->query($query) or die($this->link->error.__LINE__);

    if($result->num_rows>0)
    {
      return $result;
    } 
    else 
    {
      return false;
    }
}
?>

Then :

    <?php
        $db = new database();

        $query = "select * from data";
        $result = $db->select($query);

        echo "<table>";
         echo "<tr>";
            echo "<th>Name </th>";
            echo "<th>Roll </th>";
         echo "</tr>";
         while($row = mysqli_fetch_array($result)) 
         {
            echo "<tr>";
            echo "<td> $row[name]</td>";
            echo "<td> $row[roll]</td>";
            echo "</tr>";
         }
       echo "</table>";
 ?>

Using import fs from 'fs'

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

Without explicitly providing the type as in command.Parameters.Add("@ID", SqlDbType.Int);, it will try to implicitly convert the input to what it is expecting.

The downside of this, is that the implicit conversion may not be the most optimal of conversions and may cause a performance hit.

There is a discussion about this very topic here: http://forums.asp.net/t/1200255.aspx/1

Installing PHP Zip Extension

The PHP5 version do not support in Ubuntu 18.04+ versions, so you have to do that configure manually from the source files. If you are using php-5.3.29,

# cd /usr/local/src/php-5.3.29
# ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-mysql=MySQL_LOCATION/mysql --prefix=/usr/local/apache/php --with-config-file-path=/usr/local/apache/php --disable-cgi --with-zlib --with-gettext --with-gdbm --with-curl --enable-zip --with-xml --with-json --enable-shmop
# make
# make install

Restart the Apache server and check phpinfo function on the browser <?php echo phpinfo(); ?>

Note: Please change the MySQL_Location: --with-mysql=MySQL_LOCATION/mysql

How does the communication between a browser and a web server take place?

Your browser first resolves the servername via DNS to an IP. Then it opens a TCP connection to the webserver and tries to communicate via HTTP. Usually that is on TCP-port 80 but you can specify a different one (http://server:portnumber).

HTTP looks like this:

Once it is connected, it sends the request, which looks like:

GET /site HTTP/1.0
Header1: bla
Header2: blub
{emptyline}

E.g., a header might be Authorization or Range. See here for more.

Then the server responds like this:

200 OK
Header3: foo
Header4: bar

content following here...

E.g., a header might be Date or Content-Type. See here for more.

Look at Wikipedia for HTTP for some more information about this protocol.

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

PHP upload image

  <?php 
 $target_dir = "images/";
    echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $post_tmp_img = $_FILES["image"]["tmp_name"];
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $post_imag = $_FILES["image"]["name"];
        move_uploaded_file($post_tmp_img,"../images/$post_imag");
 ?>

What does += mean in Python?

FYI: it looks like you might have an infinite loop in your example...

if cnt > 0 and len(aStr) > 1:
    while cnt > 0:                  
        aStr = aStr[1:]+aStr[0]
        cnt += 1
  • a condition of entering the loop is that cnt is greater than 0
  • the loop continues to run as long as cnt is greater than 0
  • each iteration of the loop increments cnt by 1

The net result is that cnt will always be greater than 0 and the loop will never exit.

How to remove all CSS classes using jQuery/JavaScript?

Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.

This jQuery filter will remove the class "highlightCriteria" only for the input or select fields that have this class.

$form.find('input,select').filter(function () {
    if((!!this.value) && (!!this.name)) {
        $("#"+this.id).removeClass("highlightCriteria");
    }
});

How do I use WPF bindings with RelativeSource?

If an element is not part of the visual tree, then RelativeSource will never work.

In this case, you need to try a different technique, pioneered by Thomas Levesque.

He has the solution on his blog under [WPF] How to bind to data when the DataContext is not inherited. And it works absolutely brilliantly!

In the unlikely event that his blog is down, Appendix A contains a mirror copy of his article.

Please do not comment here, please comment directly on his blog post.

Appendix A: Mirror of blog post

The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…

Let’s illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding ShowPrice,
                Converter={StaticResource visibilityConverter}}"/>

Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)

The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of the DataGrid.

We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding DataContext.ShowPrice,
                Converter={StaticResource visibilityConverter},
                RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>

Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to the IsChecked property by specifying the element name:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding IsChecked,
                Converter={StaticResource visibilityConverter},
                ElementName=chkShowPrice}"/>

But none of these workarounds seems to work, we always get the same result…

At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider

The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…

The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:

public class BindingProxy : Freezable
{
    #region Overrides of Freezable
 
    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }
 
    #endregion
 
    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }
 
    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

The last step is to specify this BindingProxy object (easily accessible with StaticResource) as the Source for the binding:

<DataGridTextColumn Header="Price" Binding="{Binding Price}" IsReadOnly="False"
                Visibility="{Binding Data.ShowPrice,
                Converter={StaticResource visibilityConverter},
                Source={StaticResource proxy}}"/>

Note that the binding path has been prefixed with “Data”, since the path is now relative to the BindingProxy object.

The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice property.

Connect to mysql on Amazon EC2 from a remote server

A helpful step in tracking down this problem is to identify which bind-address MySQL is actually set to. You can do this with netstat:

netstat -nat |grep :3306

This helped me zero in on my problem, because there are multiple mysql config files, and I had edited the wrong one. Netstat showed mysql was still using the wrong config:

ubuntu@myhost:~$  netstat -nat |grep :3306
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN

So I grepped the config directories for any other files which might be overriding my setting and found:

ubuntu@myhost:~$  sudo grep -R bind /etc/mysql
/etc/mysql/mysql.conf.d/mysqld.cnf:bind-address         = 127.0.0.1
/etc/mysql/mysql.cnf:bind-address = 0.0.0.0
/etc/mysql/my.cnf:bind-address = 0.0.0.0

D'oh! This showed me the setting I had adjusted was the wrong config file, so I edited the RIGHT file this time, confirmed it with netstat, and was in business.

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

It's mentioned in the Documentation clearly as below: https://github.com/nodejs/node-gyp#installation

Option 1: Install all the required tools and configurations using Microsoft's windows-build-tools using npm install --global --production windows-build-tools from an elevated PowerShell or CMD.exe (run as Administrator).

npm install --global --production windows-build-tools 

How can I set the default value for an HTML <select> element?

In case you want to have a default text as a sort of placeholder/hint but not considered a valid value (something like "complete here", "select your nation" ecc.) you can do something like this:

_x000D_
_x000D_
<select>_x000D_
  <option value="" selected disabled hidden>Choose here</option>_x000D_
  <option value="1">One</option>_x000D_
  <option value="2">Two</option>_x000D_
  <option value="3">Three</option>_x000D_
  <option value="4">Four</option>_x000D_
  <option value="5">Five</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How To Save Canvas As An Image With canvas.toDataURL()?

You can try this; create a dummy HTML anchor, and download the image from there like...

// Convert canvas to image
document.getElementById('btn-download').addEventListener("click", function(e) {
    var canvas = document.querySelector('#my-canvas');

    var dataURL = canvas.toDataURL("image/jpeg", 1.0);

    downloadImage(dataURL, 'my-canvas.jpeg');
});

// Save | Download image
function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

How can I profile C++ code running on Linux?

Use -pg flag when compiling and linking the code and run the executable file. While this program is executed, profiling data is collected in the file a.out.
There is two different type of profiling

1- Flat profiling:
by running the command gprog --flat-profile a.out you got the following data
- what percentage of the overall time was spent for the function,
- how many seconds were spent in a function—including and excluding calls to sub-functions,
- the number of calls,
- the average time per call.

2- graph profiling
us the command gprof --graph a.out to get the following data for each function which includes
- In each section, one function is marked with an index number.
- Above function , there is a list of functions that call the function .
- Below function , there is a list of functions that are called by the function .

To get more info you can look in https://sourceware.org/binutils/docs-2.32/gprof/

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

I think it's from gradle-wrapper.properties file : make distribution url distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip and do not upgarde to : distributionUrl=https\://services.gradle.org/distributions/gradle-4 ....

How to tell Jackson to ignore a field during serialization if its value is null?

If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

will result in:

[{myObject},null]

to get this:

[{myObject}]

one can do something like:

mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
                throws IOException
        {
            //IGNORES NULL VALUES!
        }
    });

TIP: If you're using DropWizard you can retrieve the ObjectMapper being used by Jersey using environment.getObjectMapper()

How to var_dump variables in twig templates?

{{ dump() }} doesn't work for me. PHP chokes. Nesting level too deep I guess.

All you really need to debug Twig templates if you're using a debugger is an extension like this.

Then it's just a matter of setting a breakpoint and calling {{ inspect() }} wherever you need it. You get the same info as with {{ dump() }} but in your debugger.

Installing a pip package from within a Jupyter Notebook not working

The problem is that pyarrow is saved by pip into dist-packages (in your case /usr/local/lib/python2.7/dist-packages). This path is skipped by Jupyter so pip won't help.

As a solution I suggest adding in the first block

import sys
sys.path.append('/usr/local/lib/python2.7/dist-packages')

or whatever is path or python version. In case of Python 3.5 this is

import sys
sys.path.append("/usr/local/lib/python3.5/dist-packages")

How to emit an event from parent to child?

In a parent component you can use @ViewChild() to access child component's method/variable.

@Component({
  selector: 'app-number-parent',
  templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
    @ViewChild(NumberComponent)
    private numberComponent: NumberComponent;
    increase() {
       this.numberComponent.increaseByOne();
    }
    decrease() {
       this.numberComponent.decreaseByOne();
    }
} 

Update:

Angular 8 onwards -

@ViewChild(NumberComponent, { static: false })

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

Is there an addHeaderView equivalent for RecyclerView?

There is one more solution that covers all the use cases above: CompoundAdapter: https://github.com/negusoft/CompoundAdapter-android

You can create a AdapterGroup that holds your Adapter as it is, along with an adapter with a single item to represent the header. The code is easy and readable:

AdapterGroup adapterGroup = new AdapterGroup();
adapterGroup.addAdapter(SingleAdapter.create(R.layout.header));
adapterGroup.addAdapter(new CommentAdapter(...));

recyclerView.setAdapter(adapterGroup);

AdapterGroup allows nesting too, so for a adapter with sections, you may create a AdapterGroup per section. Then put all the sections in a root AdapterGroup.

Remove spaces from a string in VB.NET

This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))

Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim) 

What is the non-jQuery equivalent of '$(document).ready()'?

A little thing I put together

domready.js

(function(exports, d) {
  function domReady(fn, context) {

    function onReady(event) {
      d.removeEventListener("DOMContentLoaded", onReady);
      fn.call(context || exports, event);
    }

    function onReadyIe(event) {
      if (d.readyState === "complete") {
        d.detachEvent("onreadystatechange", onReadyIe);
        fn.call(context || exports, event);
      }
    }

    d.addEventListener && d.addEventListener("DOMContentLoaded", onReady) ||
    d.attachEvent      && d.attachEvent("onreadystatechange", onReadyIe);
  }

  exports.domReady = domReady;
})(window, document);

How to use it

<script src="domready.js"></script>
<script>
  domReady(function(event) {
    alert("dom is ready!");
  });
</script>

You can also change the context in which the callback runs by passing a second argument

function init(event) {
  alert("check the console");
  this.log(event);
}

domReady(init, console);

How to get HttpRequestMessage data

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.

Laravel 5.4 Specific Table Migration

You can only run this command in your terminal

php artisan migrate --path=database/migrations/2020_10_01_164611_create_asset_info_table.php

After migrations you should put the particular file name. or if you have any folder inside migration then just add that folder name after the migration.

Like this

php artisan migrate --path=database/migrations/yourfolder/2020_10_01_164611_create_asset_info_table.php

I hope this will help you a lil bit. Happy Coding.

Structure of a PDF file?

If You want to parse PDF using Python please have a look at PDFMINER. This is the best library to parse PDF files till date.

How to export a MySQL database to JSON?

Also, If you are exporting in application layer don't forget to limit results. For example if you've 10M rows, you should get results part by part.

How can I get a list of all classes within current module in Python?

I don't know if there's a 'proper' way to do it, but your snippet is on the right track: just add import foo to foo.py, do inspect.getmembers(foo), and it should work fine.

How can you profile a Python script?

I just developed my own profiler inspired from pypref_time:

https://github.com/modaresimr/auto_profiler

By adding a decorator it will show a tree of time-consuming functions

@Profiler(depth=4, on_disable=show)

Install by: pip install auto_profiler

Example

import time # line number 1
import random

from auto_profiler import Profiler, Tree

def f1():
    mysleep(.6+random.random())

def mysleep(t):
    time.sleep(t)

def fact(i):
    f1()
    if(i==1):
        return 1
    return i*fact(i-1)


def show(p):
    print('Time   [Hits * PerHit] Function name [Called from] [Function Location]\n'+\
          '-----------------------------------------------------------------------')
    print(Tree(p.root, threshold=0.5))
    
@Profiler(depth=4, on_disable=show)
def main():
    for i in range(5):
        f1()

    fact(3)


if __name__ == '__main__':
    main()

Example Output


Time   [Hits * PerHit] Function name [Called from] [function location]
-----------------------------------------------------------------------
8.974s [1 * 8.974]  main  [auto-profiler/profiler.py:267]  [/test/t2.py:30]
+-- 5.954s [5 * 1.191]  f1  [/test/t2.py:34]  [/test/t2.py:14]
¦   +-- 5.954s [5 * 1.191]  mysleep  [/test/t2.py:15]  [/test/t2.py:17]
¦       +-- 5.954s [5 * 1.191]  <time.sleep>
|
|
|   # The rest is for the example recursive function call fact
+-- 3.020s [1 * 3.020]  fact  [/test/t2.py:36]  [/test/t2.py:20]
    +-- 0.849s [1 * 0.849]  f1  [/test/t2.py:21]  [/test/t2.py:14]
    ¦   +-- 0.849s [1 * 0.849]  mysleep  [/test/t2.py:15]  [/test/t2.py:17]
    ¦       +-- 0.849s [1 * 0.849]  <time.sleep>
    +-- 2.171s [1 * 2.171]  fact  [/test/t2.py:24]  [/test/t2.py:20]
        +-- 1.552s [1 * 1.552]  f1  [/test/t2.py:21]  [/test/t2.py:14]
        ¦   +-- 1.552s [1 * 1.552]  mysleep  [/test/t2.py:15]  [/test/t2.py:17]
        +-- 0.619s [1 * 0.619]  fact  [/test/t2.py:24]  [/test/t2.py:20]
            +-- 0.619s [1 * 0.619]  f1  [/test/t2.py:21]  [/test/t2.py:14]

How to Create a real one-to-one relationship in SQL Server

There is one way I know how to achieve a strictly* one-to-one relationship without using triggers, computed columns, additional tables, or other 'exotic' tricks (only foreign keys and unique constraints), with one small caveat.

I will borrow the chicken-and-the-egg concept from the accepted answer to help me explain the caveat.

It is a fact that either a chicken or an egg must come first (in current DBs anyway). Luckily this solution does not get political and does not prescribe which has to come first - it leaves it up to the implementer.

The caveat is that the table which allows a record to 'come first' technically can have a record created without the corresponding record in the other table; however, in this solution, only one such record is allowed. When only one record is created (only chicken or egg), no more records can be added to any of the two tables until either the 'lonely' record is deleted or a matching record is created in the other table.

Solution:

Add foreign keys to each table, referencing the other, add unique constraints to each foreign key, and make one foreign key nullable, the other not nullable and also a primary key. For this to work, the unique constrain on the nullable column must only allow one null (this is the case in SQL Server, not sure about other databases).

CREATE TABLE dbo.Egg (
    ID int identity(1,1) not null,
    Chicken int null,
    CONSTRAINT [PK_Egg] PRIMARY KEY CLUSTERED ([ID] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE dbo.Chicken (
    Egg int not null,
    CONSTRAINT [PK_Chicken] PRIMARY KEY CLUSTERED ([Egg] ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE dbo.Egg  WITH NOCHECK ADD  CONSTRAINT [FK_Egg_Chicken] FOREIGN KEY([Chicken]) REFERENCES [dbo].[Chicken] ([Egg])
GO
ALTER TABLE dbo.Chicken  WITH NOCHECK ADD  CONSTRAINT [FK_Chicken_Egg] FOREIGN KEY([Egg]) REFERENCES [dbo].[Egg] ([ID])
GO
ALTER TABLE dbo.Egg WITH NOCHECK ADD CONSTRAINT [UQ_Egg_Chicken] UNIQUE([Chicken])
GO
ALTER TABLE dbo.Chicken WITH NOCHECK ADD CONSTRAINT [UQ_Chicken_Egg] UNIQUE([Egg])
GO

To insert, first an egg must be inserted (with null for Chicken). Now, only a chicken can be inserted and it must reference the 'unclaimed' egg. Finally, the added egg can be updated and it must reference the 'unclaimed' chicken. At no point can two chickens be made to reference the same egg or vice-versa.

To delete, the same logic can be followed: update egg's Chicken to null, delete the newly 'unclaimed' chicken, delete the egg.

This solution also allows swapping easily. Interestingly, swapping might be the strongest argument for using such a solution, because it has a potential practical use. Normally, in most cases, a one-to-one relationship of two tables is better implemented by simply refactoring the two tables into one; however, in a potential scenario, the two tables may represent truly distinct entities, which require a strict one-to-one relationship, but need to frequently swap 'partners' or be re-arranged in general, while still maintaining the one-to-one relationship after re-arrangement. If the more common solution were used, all data columns of one of the entities would have to be updated/overwritten for all pairs being re-arranged, as opposed to this solution, where only one column of foreign keys need to be re-arranged (the nullable foreign key column).

Well, this is the best I could do using standard constraints (don't judge :) Maybe someone will find it useful.

Integrating MySQL with Python in Windows

This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState! you then just pypm install mysql-python and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes. This is the only way to go on windows. Really.

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

CSS to select/style first word

Pure CSS solution:

Use the :first-line pseudo-class.

display:block;
Width:40-100px; /* just enough for one word, depends on font size */
Overflow:visible; /* so longer words don't get clipped.*/
float:left; /* so it will flow with the paragraph. */
position:relative; /* for typeset adjustments. */

Didn't test that. Pretty sure it will work fine for you tho. I've applied block rules to pseudo-classes before. You might be stuck with a fixed width for every first word, so text-align:center; and give it a nice background or something to deal with the negative space.

Hope that works for you. :)

-Motekye

trigger click event from angularjs directive

This is how I was able to trigger a button click when the page loads.

<li ng-repeat="a in array">
  <a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
    {{a.name}}
  </a>
</li>

A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.

angular
    .module("myApp")
        .directive('onLoadClicker', function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    index: '=index'
                },
                link: function($scope, iElm) {
                    if ($scope.index == 0) {
                        $timeout(function() {

                            iElm.triggerHandler('click');

                        }, 0);
                    }
                }
            };
        });

This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click(); Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.

Creating an empty Pandas DataFrame, then filling it?

Assume a dataframe with 19 rows

index=range(0,19)
index

columns=['A']
test = pd.DataFrame(index=index, columns=columns)

Keeping Column A as a constant

test['A']=10

Keeping column b as a variable given by a loop

for x in range(0,19):
    test.loc[[x], 'b'] = pd.Series([x], index = [x])

You can replace the first x in pd.Series([x], index = [x]) with any value

read word by word from file in C++

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

Change HTML email body font type and size in VBA

I did a little research and was able to write this code:

strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today.  All assigned firms are complete.  Please feel free to respond with any questions.<p>Thank you.</BODY>"

apparently by setting the "font-size=11pt" instead of setting the font size <font size=5>, It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.

This link from simpLE MAn gave me some good info.

How to send only one UDP packet with netcat?

I had the same problem but I use -w 0 option to send only one packet and quit. You should use this command :

echo -n "hello" | nc -4u -w0 localhost 8000

Where are Magento's log files located?

These code lines can help you quickly enable log setting in your magento site.

INSERT INTO `core_config_data` (`config_id`, `scope`, `scope_id`, `path`, `value`) VALUES
('', 'default', 0, 'dev/log/active', '1'),
('', 'default', 0, 'dev/log/file', 'system.log'),
('', 'default', 0, 'dev/log/exception_file', 'exception.log');

Then you can see them inside the folder: /var/log under root installation.

More detail in this blog

How to print to console when using Qt

What variables do you want to print? If you mean QStrings, those need to be converted to c-Strings. Try:

std::cout << myString.toAscii().data();

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

In Python 2 (3 has different syntax):

What if you can't instantiate your Parent class before you need to call one of its methods?

Use super(ChildClass, self).method() to access parent methods.

class ParentClass(object):
    def method_to_call(self, arg_1):
        print arg_1

class ChildClass(ParentClass):
    def do_thing(self):
        super(ChildClass, self).method_to_call('my arg')

Sorting Characters Of A C++ String

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());

get the selected index value of <select> tag in php

$gender = $_POST['gender'];
echo $gender;  

it will echoes the selected value.

How to deal with missing src/test/java source folder in Android/Maven project?

I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).

It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:

<classpathentry kind="src" output="bin/classes" path="src/test/java">
  <attributes>
    <attribute name="maven.pomderived" value="true"/>
  </attributes>
</classpathentry>

As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:

enter image description here

There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

How can I read large text files in Python, line by line, without loading it into memory?

f=open('filename','r').read()
f1=f.split('\n')
for i in range (len(f1)):
    do_something_with(f1[i])

hope this helps.

Adding an onclick function to go to url in JavaScript?

HTML

<input type="button" value="My Button" 
onclick="location.href = 'https://myurl'" />

MVC

<input type="button" value="My Button" 
onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />

Pyspark: Exception: Java gateway process exited before sending the driver its port number

This usually happens if you do not have java installed in your machine.

Go to command prompt and check the version of your java: type : java -version

you should get output sth like this

java version "1.8.0_241" Java(TM) SE Runtime Environment (build 1.8.0_241-b07) Java HotSpot(TM) 64-Bit Server VM (build 25.241-b07, mixed mode)

If not, go to orcale and download jdk. Check this video on how to download java and add it to the buildpath.

https://www.youtube.com/watch?v=f7rT0h1Q5Wo

Difference between .dll and .exe?

The difference is that an EXE has an entry point, a "main" method that will run on execution.

The code within a DLL needs to be called from another application.

What is the best way to seed a database in Rails?

Updating since these answers are slightly outdated (although some still apply).

Simple feature added in rails 2.3.4, db/seeds.rb

Provides a new rake task

rake db:seed

Good for populating common static records like states, countries, etc...

http://railscasts.com/episodes/179-seed-data

*Note that you can use fixtures if you had already created them to also populate with the db:seed task by putting the following in your seeds.rb file (from the railscast episode):

require 'active_record/fixtures'
Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "operating_systems")

For Rails 3.x use 'ActiveRecord::Fixtures' instead of 'Fixtures' constant

require 'active_record/fixtures'
ActiveRecord::Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "fixtures_file_name")

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How to round a number to significant figures in Python

I ran into this as well but I needed control over the rounding type. Thus, I wrote a quick function (see code below) that can take value, rounding type, and desired significant digits into account.

import decimal
from math import log10, floor

def myrounding(value , roundstyle='ROUND_HALF_UP',sig = 3):
    roundstyles = [ 'ROUND_05UP','ROUND_DOWN','ROUND_HALF_DOWN','ROUND_HALF_UP','ROUND_CEILING','ROUND_FLOOR','ROUND_HALF_EVEN','ROUND_UP']

    power =  -1 * floor(log10(abs(value)))
    value = '{0:f}'.format(value) #format value to string to prevent float conversion issues
    divided = Decimal(value) * (Decimal('10.0')**power) 
    roundto = Decimal('10.0')**(-sig+1)
    if roundstyle not in roundstyles:
        print('roundstyle must be in list:', roundstyles) ## Could thrown an exception here if you want.
    return_val = decimal.Decimal(divided).quantize(roundto,rounding=roundstyle)*(decimal.Decimal(10.0)**-power)
    nozero = ('{0:f}'.format(return_val)).rstrip('0').rstrip('.') # strips out trailing 0 and .
    return decimal.Decimal(nozero)


for x in list(map(float, '-1.234 1.2345 0.03 -90.25 90.34543 9123.3 111'.split())):
    print (x, 'rounded UP: ',myrounding(x,'ROUND_UP',3))
    print (x, 'rounded normal: ',myrounding(x,sig=3))

How to delete/remove nodes on Firebase

Firebase.remove() like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:

parent = ref.parent()
parent.on('child_removed', function (snapshot) {
    // removed!
})
ref.remove()

According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove method:

ref.remove(function (error) {
    if (!error) {
        // removed!
    }
}

How to log cron jobs?

* * * * * myjob.sh >> /var/log/myjob.log 2>&1

will log all output from the cron job to /var/log/myjob.log

You might use mail to send emails. Most systems will send unhandled cron job output by email to root or the corresponding user.

Parameterize an SQL IN clause

Here's a quick-and-dirty technique I have used:

SELECT * FROM Tags
WHERE '|ruby|rails|scruffy|rubyonrails|'
LIKE '%|' + Name + '|%'

So here's the C# code:

string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
const string cmdText = "select * from tags where '|' + @tags + '|' like '%|' + Name + '|%'";

using (SqlCommand cmd = new SqlCommand(cmdText)) {
   cmd.Parameters.AddWithValue("@tags", string.Join("|", tags);
}

Two caveats:

  • The performance is terrible. LIKE "%...%" queries are not indexed.
  • Make sure you don't have any |, blank, or null tags or this won't work

There are other ways to accomplish this that some people may consider cleaner, so please keep reading.

ISO C90 forbids mixed declarations and code in C

-Wdeclaration-after-statement minimal reproducible example

main.c

#!/usr/bin/env bash

set -eux

cat << EOF > main.c
#include <stdio.h>

int main(void) {
    puts("hello");
    int a = 1;
    printf("%d\n", a);
    return 0;
}
EOF

Give warning:

gcc -std=c89 -Wdeclaration-after-statement -Werror main.c
gcc -std=c99 -Wdeclaration-after-statement -Werror main.c
gcc -std=c89 -pedantic -Werror main.c

Don't give warning:

gcc -std=c89 -pedantic -Wno-declaration-after-statement -Werror main.c
gcc -std=c89 -Wno-declaration-after-statement -Werror main.c
gcc -std=c99 -pedantic -Werror main.c
gcc -std=c89 -Wall -Wextra -Werror main.c
# https://stackoverflow.com/questions/14737104/what-is-the-default-c-mode-for-the-current-gcc-especially-on-ubuntu/53063656#53063656
gcc -pedantic -Werror main.c

The warning:

main.c: In function ‘main’:
main.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     int a = 1;
     ^~~

Tested on Ubuntu 16.04, GCC 6.4.0.

OnClick in Excel VBA

Clearly, there is no perfect answer. However, if you want to allow the user to

  1. select certain cells
  2. allow them to change those cells, and
  3. trap each click,even repeated clicks on the same cell,

then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.

One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.

If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'prevent Select event triggering again when we extend the selection below
  Application.EnableEvents = False
  Target.Resize(1, 2).Select
  Application.EnableEvents = True
End Sub

How to add an element to a list?

import json

myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}

Whats the CSS to make something go to the next line in the page?

It depends why the something is on the same line in the first place.

clear in the case of floats, display: block in the case of inline content naturally flowing, nothing will defeat position: absolute as the previous element will be taken out of the normal flow by it.

XML Parser for C

My personal preference is libxml2. It's very easy to use but I never bothered to benchmark it, as I've only used it for configuration file parsing.

How to upgrade scikit-learn package in anaconda

So to upgrade scikit-learn package, you have to follow below process

Step-1: Open your terminal(Ctrl+Alt+t)

Step-2: Now for checking currently installed packages along with the versions installed on your conda environment by typing conda list

Step-3: Now for upgrade type below command

conda update scikit-learn

Hope it helps!!

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

Generally, EXC_BAD_INSTRUCTION means that there was an assertion failure in your code. A wild guess, your Screen.text is not an integer. Double check its type.

(grep) Regex to match non-ASCII characters?

You don't really need a regex.

printf "%s\n" *[!\ -~]*

This will show file names with control characters in their names, too, but I consider that a feature.

If you don't have any matching files, the glob will expand to just itself, unless you have nullglob set. (The expression does not match itself, so technically, this output is unambiguous.)

Why would one omit the close tag?

Pros

Cons

  • Avoids headache with adding inadvertently whitespaces after the closing tag, because it breaks the header() function behavior... Some editors or FTP clients / servers are also known to change automatically the end of files (at least, it's their default configuration)
  • PHP manual says closing tag is optional, and Zend even forbids it.

Conclusion

I would say that the arguments in favor of omitting the tag look stronger (helps to avoid big headache with header() + it's PHP/Zend "recommendation"). I admit that this isn't the most "beautiful" solution I've ever seen in terms of syntax consistency, but what could be better ?

How can I declare dynamic String array in Java

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

for each loop in groovy

as simple as:

tmpHM.each{ key, value -> 
  doSomethingWithKeyAndValue key, value
}

How to create folder with PHP code?

You can create it easily:

$structure = './depth1/depth2/depth3/';
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}

How can I add comments in MySQL?

From here you can use

#  For single line comments
-- Also for single line, must be followed by space/control character
/*
    C-style multiline comment
*/

How to list all functions in a Python module?

Once you've imported the module, you can just do:

help(modulename)

... To get the docs on all the functions at once, interactively. Or you can use:

dir(modulename)

... To simply list the names of all the functions and variables defined in the module.

Inserting data into a MySQL table using VB.NET

You need to use ?param instead of @param when performing queries to MySQL

 str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
        sqlCommand.Connection = SQLConnection
        sqlCommand.CommandText = str_carSql
        sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
        sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
        sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
        sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
        sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
        sqlCommand.ExecuteNonQuery()

Change the catch block to see the actual exception:

  Catch ex As Exception
         MsgBox(ex.Message)   
          Return False

    End Try

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

Situation:

  • You have local uncommitted changes
  • You pull from the master repo
  • You get the error "Checkout conflict with files: xy"

Solution:

  • Stage and commit (at least) the files xy
  • Pull again
  • If automerge is possible, everything is ok.
  • If not, the pull merges the files and inserts the merge-conflict markers (<<<<<<, >>>>)
    • Manually edit the conflicting files
  • Commit and push

Fastest way to iterate over all the chars in a String

The first one using str.charAt should be faster.

If you dig inside the source code of String class, we can see that charAt is implemented as follows:

public char charAt(int index) {
    if ((index < 0) || (index >= count)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index + offset];
}

Here, all it does is index an array and return the value.

Now, if we see the implementation of toCharArray, we will find the below:

public char[] toCharArray() {
    char result[] = new char[count];
    getChars(0, count, result, 0);
    return result;
}

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
    if (srcBegin < 0) {
        throw new StringIndexOutOfBoundsException(srcBegin);
    }
    if (srcEnd > count) {
        throw new StringIndexOutOfBoundsException(srcEnd);
    }
    if (srcBegin > srcEnd) {
        throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
    }
    System.arraycopy(value, offset + srcBegin, dst, dstBegin,
         srcEnd - srcBegin);
}

As you see, it is doing a System.arraycopy which is definitely going to be a tad slower than not doing it.

Passing an array by reference

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints

Disabling Log4J Output in Java

You can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is one undocumented level called OFF which is a higher level than FATAL, and turns off all logging.

You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily. Here's a post to get you started on that.

You might also want to read the Log4J FAQ, because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.

Multiple commands in an alias for bash

On windows, in Git\etc\bash.bashrc I use (at the end of the file)

a(){
    git add $1  
    git status
}

and then in git bash simply write

$ a Config/