Programs & Examples On #Private members

In object oriented programming, private members are those data fields, properties, or methods of a class that are only accessible from within the class itself.

Private properties in JavaScript ES6 classes

The answer is "No". But you can create private access to properties like this:

(The suggestion that Symbols could be used to ensure privacy was true in an earlier version of the ES6 spec but is no longer the case:https://mail.mozilla.org/pipermail/es-discuss/2014-January/035604.html and https://stackoverflow.com/a/22280202/1282216. For a longer discussion about Symbols and privacy see: https://curiosity-driven.org/private-properties-in-javascript)

Private Variables and Methods in Python

The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)

class Foo:
    def __init__(self):
        self.__privateField = 4;
        print self.__privateField # yields 4 no problem

foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'

It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.

Accessing private member variables from prototype-defined functions

I know it has been more than 1 decade since this was was asked, but I just put my thinking on this for the n-th time in my programmer life, and found a possible solution that I don't know if I entirely like yet. I have not seen this methodology documented before, so I will name it the "private/public dollar pattern" or _$ / $ pattern.

var ownFunctionResult = this.$("functionName"[, arg1[, arg2 ...]]);
var ownFieldValue = this._$("fieldName"[, newValue]);

var objectFunctionResult = objectX.$("functionName"[, arg1[, arg2 ...]]);

//Throws an exception. objectX._$ is not defined
var objectFieldValue = objectX._$("fieldName"[, newValue]);

The concept uses a ClassDefinition function that returns a Constructor function that returns an Interface object. The interface's only method is $ which receives a name argument to invoke the corresponding function in the constructor object, any additional arguments passed after name are passed in the invocation.

The globally-defined helper function ClassValues stores all fields in an object as needed. It defines the _$ function to access them by name. This follows a short get/set pattern so if value is passed, it will be used as the new variable value.

var ClassValues = function (values) {
  return {
    _$: function _$(name, value) {
      if (arguments.length > 1) {
        values[name] = value;
      }

      return values[name];
    }
  };
};

The globally defined function Interface takes an object and a Values object to return an _interface with one single function $ that examines obj to find a function named after the parameter name and invokes it with values as the scoped object. The additional arguments passed to $ will be passed on the function invocation.

var Interface = function (obj, values, className) {
  var _interface = {
    $: function $(name) {
      if (typeof(obj[name]) === "function") {
        return obj[name].apply(values, Array.prototype.splice.call(arguments, 1));
      }

      throw className + "." + name + " is not a function.";
    }
  };

  //Give values access to the interface.
  values.$ = _interface.$;

  return _interface;
};

In the sample below, ClassX is assigned to the result of ClassDefinition, which is the Constructor function. Constructor may receive any number of arguments. Interface is what external code gets after calling the constructor.

var ClassX = (function ClassDefinition () {
  var Constructor = function Constructor (valA) {
    return Interface(this, ClassValues({ valA: valA }), "ClassX");
  };

  Constructor.prototype.getValA = function getValA() {
    //private value access pattern to get current value.
    return this._$("valA");
  };

  Constructor.prototype.setValA = function setValA(valA) {
    //private value access pattern to set new value.
    this._$("valA", valA);
  };

  Constructor.prototype.isValAValid = function isValAValid(validMessage, invalidMessage) {
    //interface access pattern to call object function.
    var valA = this.$("getValA");

    //timesAccessed was not defined in constructor but can be added later...
    var timesAccessed = this._$("timesAccessed");

    if (timesAccessed) {
      timesAccessed = timesAccessed + 1;
    } else {
      timesAccessed = 1;
    }

    this._$("timesAccessed", timesAccessed);

    if (valA) {
      return "valA is " + validMessage + ".";
    }

    return "valA is " + invalidMessage + ".";
  };

  return Constructor;
}());

There is no point in having non-prototyped functions in Constructor, although you could define them in the constructor function body. All functions are called with the public dollar pattern this.$("functionName"[, param1[, param2 ...]]). The private values are accessed with the private dollar pattern this._$("valueName"[, replacingValue]);. As Interface does not have a definition for _$, the values cannot be accessed by external objects. Since each prototyped function body's this is set to the values object in function $, you will get exceptions if you call Constructor sibling functions directly; the _$ / $ pattern needs to be followed in prototyped function bodies too. Below sample usage.

var classX1 = new ClassX();
console.log("classX1." + classX1.$("isValAValid", "valid", "invalid"));
console.log("classX1.valA: " + classX1.$("getValA"));
classX1.$("setValA", "v1");
console.log("classX1." + classX1.$("isValAValid", "valid", "invalid"));
var classX2 = new ClassX("v2");
console.log("classX1.valA: " + classX1.$("getValA"));
console.log("classX2.valA: " + classX2.$("getValA"));
//This will throw an exception
//classX1._$("valA");

And the console output.

classX1.valA is invalid.
classX1.valA: undefined
classX1.valA is valid.
classX1.valA: v1
classX2.valA: v2

The _$ / $ pattern allows full privacy of values in fully-prototyped classes. I don't know if I will ever use this, nor if it has flaws, but hey, it was a good puzzle!

Image scaling causes poor quality in firefox/internet explorer but not chrome

Seems Chrome downscaling is best but the real question is why use such a massive image on the web if you use show is so massively scaled down? Downloadtimes as seen on the test page above are terrible. Especially for responsive websites a certain amount of scaling makes sense, actually more a scale up than scale down though. But never in such a (sorry pun) scale.

Seems this is more a theoretical problem which Chrome seems to deal with nicely but actually should not happen and actually should not be used in practice IMHO.

Possible to change where Android Virtual Devices are saved?

The environmental variable ANDROID_AVD_HOME can be used to define the directory in which the AVD Manager shall look for AVD INI files and can therefore be used to change the location of the virtual devices;

The default value is %USERPROFILE%\.android\avd on Windows (or ~/.android/avd on Linux).

One can also create a link for the whole directory %USERPROFILE%\.android on Windows (or a sym-link for directory ~/.android on Linux).

When moving AVDs, the path entry in AVD INI file needs to be updated accordingly.

Angularjs $q.all

$http is a promise too, you can make it simpler:

return $q.all(tasks.map(function(d){
        return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
    }));

Add 2 hours to current time in MySQL?

SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time

How to list all AWS S3 objects in a bucket using Java

Listing Keys Using the AWS SDK for Java

http://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html

import java.io.IOException;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;

public class ListKeys {
    private static String bucketName = "***bucket name***";

    public static void main(String[] args) throws IOException {
        AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
        try {
            System.out.println("Listing objects");
            final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName);
            ListObjectsV2Result result;
            do {               
               result = s3client.listObjectsV2(req);

               for (S3ObjectSummary objectSummary : 
                   result.getObjectSummaries()) {
                   System.out.println(" - " + objectSummary.getKey() + "  " +
                           "(size = " + objectSummary.getSize() + 
                           ")");
               }
               System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
               req.setContinuationToken(result.getNextContinuationToken());
            } while(result.isTruncated() == true ); 

         } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, " +
                    "which means your request made it " +
                    "to Amazon S3, but was rejected with an error response " +
                    "for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, " +
                    "which means the client encountered " +
                    "an internal error while trying to communicate" +
                    " with S3, " +
                    "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }
    }
}

Split string into array of characters?

You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv

Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)

which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function

Checking if a worksheet-based checkbox is checked

Building on the previous answers, you can leverage the fact that True is -1 and False is 0 and shorten your code like this:

Sub Button167_Click()
  Range("Y12").Value = _
    Abs(Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0)
End Sub

If the checkbox is checked, .Value = 1.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns True.

Applying the Abs function converts True to 1.

If the checkbox is unchecked, .Value = -4146.

Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0 returns False.

Applying the Abs function converts False to 0.

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Try this, it worked for me.

mongod --storageEngine=mmpav1

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

We demonstrate features of lmfit while solving both problems.

Given

import lmfit

import numpy as np

import matplotlib.pyplot as plt


%matplotlib inline
np.random.seed(123)
# General Functions
def func_log(x, a, b, c):
    """Return values from a general log function."""
    return a * np.log(b * x) + c


# Data
x_samp = np.linspace(1, 5, 50)
_noise = np.random.normal(size=len(x_samp), scale=0.06)
y_samp = 2.5 * np.exp(1.2 * x_samp) + 0.7 + _noise
y_samp2 = 2.5 * np.log(1.2 * x_samp) + 0.7 + _noise

Code

Approach 1 - lmfit Model

Fit exponential data

regressor = lmfit.models.ExponentialModel()                # 1    
initial_guess = dict(amplitude=1, decay=-1)                # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit    

plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here

Approach 2 - Custom Model

Fit log data

regressor = lmfit.Model(func_log)                          # 1
initial_guess = dict(a=1, b=.1, c=.1)                      # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit

plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here


Details

  1. Choose a regression class
  2. Supply named, initial guesses that respect the function's domain

You can determine the inferred parameters from the regressor object. Example:

regressor.param_names
# ['decay', 'amplitude']

To make predictions, use the ModelResult.eval() method.

model = results.eval
y_pred = model(x=np.array([1.5]))

Note: the ExponentialModel() follows a decay function, which accepts two parameters, one of which is negative.

enter image description here

See also ExponentialGaussianModel(), which accepts more parameters.

Install the library via > pip install lmfit.

Skip to next iteration in loop vba

For i = 2 To 24
  Level = Cells(i, 4)
  Return = Cells(i, 5)

  If Return = 0 And Level = 0 Then GoTo NextIteration
  'Go to the next iteration
  Else
  End If
  ' This is how you make a line label in VBA - Do not use keyword or
  ' integer and end it in colon
  NextIteration:
Next

Checking if a list of objects contains a property with a specific value

Further to the other answers suggesting LINQ, another alternative in this case would be to use the FindAll instance method:

List<SampleClass> results = myList.FindAll(x => x.Name == nameToExtract);

I do not want to inherit the child opacity from the parent in CSS

As others have mentioned in this and other similar threads, the best way to avoid this problem is to use RGBA/HSLA or else use a transparent PNG.

But, if you want a ridiculous solution, similar to the one linked in another answer in this thread (which is also my website), here's a brand new script I wrote that fixes this problem automatically, called thatsNotYoChild.js:

http://www.impressivewebs.com/fixing-parent-child-opacity/

Basically it uses JavaScript to remove all children from the parent div, then reposition the child elements back to where they should be without actually being children of that element anymore.

To me, this should be a last resort, but I thought it would be fun to write something that did this, if anyone wants to do this.

(HTML) Download a PDF file instead of opening them in browser when clicked

The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.

from unix timestamp to datetime

I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:

const today = moment(1557697070824.94).toObject();

You should obtain an object with this properties:

today: {
  date: 15,
  hours: 2,
  milliseconds: 207,
  minutes: 31,
  months: 4
  seconds: 22,
  years: 2019
}

It is very useful when you have to calculate dates.

How do you use bcrypt for hashing passwords in PHP?


Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.


Everyone wants to make this more complicated than it is. The crypt() function does most of the work.

function blowfishCrypt($password,$cost)
{
    $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
//    $salt=sprintf('$2a$%02d$',$cost);
    //Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
    mt_srand();
    for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
    return crypt($password,$salt);
}

Example:

$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password

I know it should be obvious, but please don't use 'password' as your password.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

IN Clause with NULL or IS NULL

I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0

SELECT *
FROM (SELECT CASE WHEN id_field IS NULL 
                THEN 0 
                ELSE id_field 
            END AS id_field
      FROM tbl_name) AS tbl
WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)

How to highlight a selected row in ngRepeat?

I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.

<ul ng-repeat="vote in votes" ...>
    <li data-choice="selected" data-value="vote.id">...</li>
</ul>

Solution: http://jsfiddle.net/brandonmilleraz/5fr9V/

twitter bootstrap typeahead ajax example

I went through this post and everything didnt want to work correctly and eventually pieced the bits together from a few answers so I have a 100% working demo and will paste it here for reference - paste this into a php file and make sure includes are in the right place.

<?php if (isset($_GET['typeahead'])){
    die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('index.php?typeahead', { query: query }, function (data) {
            return process(JSON.parse(data).options);
        });
    }
});
</script>

T-SQL Subquery Max(Date) and Joins

All other answers must work, but using your same syntax (and understanding why the error)

SELECT * FROM MyParts LEFT JOIN MyPrice ON MyParts.Partid = MyPrice.Partid WHERE 
MyPart.PriceDate = (SELECT MAX(MyPrice2.PriceDate) FROM MyPrice as MyPrice2 
WHERE MyPrice2.Partid =  MyParts.Partid)

Sorting a Dictionary in place with respect to keys

By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.

Rounding a double to turn it into an int (java)

Rounding double to the "nearest" integer like this:

1.4 -> 1

1.6 -> 2

-2.1 -> -2

-1.3 -> -1

-1.5 -> -2

private int round(double d){
    double dAbs = Math.abs(d);
    int i = (int) dAbs;
    double result = dAbs - (double) i;
    if(result<0.5){
        return d<0 ? -i : i;            
    }else{
        return d<0 ? -(i+1) : i+1;          
    }
}

You can change condition (result<0.5) as you prefer.

How can I embed a YouTube video on GitHub wiki pages?

Adding a link with the thumbnail, originally used by YouTube is a solution, that works. The thumbnail, used by YouTube is accessible the following way:

  • if the official video link is: https://www.youtube.com/watch?v=5yLzZikS15k
  • then the thumbnail is: https://img.youtube.com/vi/5yLzZikS15k/0.jpg

Following this logic, the code below produces flawless results:

_x000D_
_x000D_
<div align="left">
      <a href="https://www.youtube.com/watch?v=5yLzZikS15k">
         <img src="https://img.youtube.com/vi/5yLzZikS15k/0.jpg" style="width:100%;">
      </a>
</div>
_x000D_
_x000D_
_x000D_

Writing a VLOOKUP function in vba

How about just using:

result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]

Note the [ and ].

How would one write object-oriented code in C?

The C stdio FILE sub-library is an excellent example of how to create abstraction, encapsulation, and modularity in unadulterated C.

Inheritance and polymorphism - the other aspects often considered essential to OOP - do not necessarily provide the productivity gains they promise and reasonable arguments have been made that they can actually hinder development and thinking about the problem domain.

Generate unique random numbers between 1 and 100

  1. Populate an array with the numbers 1 through 100.
  2. Shuffle it.
  3. Take the first 8 elements of the resulting array.

Trying to detect browser close event

Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.

The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

For me, the fix was to upgrade the version of System.Web.Optimization to 1.1.0.0 When I was at version 1.0.0.0 it would never resolve a .map file in a subdirectory (i.e. correctly minify and bundle scripts in a subdirectory)

Authenticating in PHP using LDAP through Active Directory

I do this simply by passing the user credentials to ldap_bind().

http://php.net/manual/en/function.ldap-bind.php

If the account can bind to LDAP, it's valid; if it can't, it's not. If all you're doing is authentication (not account management), I don't see the need for a library.

Simulate string split function in Excel formula

Some great worksheet-fu in the other answers but I think they've overlooked that you can define a user-defined function (udf) and call this from the sheet or a formula.

The next problem you have is to decide either to work with a whole array or with element.

For example this UDF function code

Public Function UdfSplit(ByVal sText As String, Optional ByVal sDelimiter As String = " ", Optional ByVal lIndex As Long = -1) As Variant
    Dim vSplit As Variant
    vSplit = VBA.Split(sText, sDelimiter)
    If lIndex > -1 Then
        UdfSplit = vSplit(lIndex)
    Else
        UdfSplit = vSplit
    End If
End Function

allows single elements with the following in one cell

=UdfSplit("EUR/USD","/",0)

or one can use a blocks of cells with

=UdfSplit("EUR/USD","/")

Get selected element's outer HTML

$("#myNode").parent(x).html(); 

Where 'x' is the node number, beginning with 0 as the first one, should get the right node you want, if you're trying to get a specific one. If you have child nodes, you should really be putting an ID on the one you want, though, to just zero in on that one. Using that methodology and no 'x' worked fine for me.

How do I wait for a promise to finish before returning the variable of a function?

You're not actually using promises here. Parse lets you use callbacks or promises; your choice.

To use promises, do the following:

query.find().then(function() {
    console.log("success!");
}, function() {
    console.log("error");
});

Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then() call. So far this would be exactly the same as regular callbacks.

To actually make good use of promises is when you chain them, like this:

query.find().then(function() {
    console.log("success!");

    return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
    console.log("error");
}).then(function() {
    console.log("success on second callback!");
}, function() {
    console.log("error on second callback");
});

What are alternatives to document.write?

As a recommended alternative to document.write you could use DOM manipulation to directly query and add node elements to the DOM.

Check if string contains a value in array

$owned_urls= array('website1.com', 'website2.com', 'website3.com');
    $string = 'my domain name is website3.com';
    for($i=0; $i < count($owned_urls); $i++)
    {
        if(strpos($string,$owned_urls[$i]) != false)
            echo 'Found';
    }   

Is it possible to modify a string of char in C?

No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g.

char a[] = "This is a string";

Or alternately, you could allocate memory using malloc e.g.

char *a = malloc(100);
strcpy(a, "This is a string");
free(a); // deallocate memory once you've done

Create an enum with string values

TypeScript 2.1 +

Lookup types, introduced in TypeScript 2.1 allow another pattern for simulating string enums:

// String enums in TypeScript 2.1
const EntityType = {
    Foo: 'Foo' as 'Foo',
    Bar: 'Bar' as 'Bar'
};

function doIt(entity: keyof typeof EntityType) {
    // ...
}

EntityType.Foo          // 'Foo'
doIt(EntityType.Foo);   // 
doIt(EntityType.Bar);   // 
doIt('Foo');            // 
doIt('Bad');            //  

TypeScript 2.4 +

With version 2.4, TypeScript introduced native support for string enums, so the solution above is not needed. From the TS docs:

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

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

You are better off using an iterator instead. Relevant: http://docs.python.org/library/fileinput.html

From the docs:

import fileinput
for line in fileinput.input("filename"):
    process(line)

This will avoid copying the whole file into memory at once.

REST, HTTP DELETE and parameters

It's an old question, but here are some comments...

  1. In SQL, the DELETE command accepts a parameter "CASCADE", which allows you to specify that dependent objects should also be deleted. This is an example of a DELETE parameter that makes sense, but 'man rm' could provide others. How would these cases possibly be implemented in REST/HTTP without a parameter?
  2. @Jan, it seems to be a well-established convention that the path part of the URL identifies a resource, whereas the querystring does not (at least not necessarily). Examples abound: getting the same resource but in a different format, getting specific fields of a resource, etc. If we consider the querystring as part of the resource identifier, it is impossible to have a concept of "different views of the same resource" without turning to non-RESTful mechanisms such as HTTP content negotiation (which can be undesirable for many reasons).

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

In my situation, the Oracle 11.2 32-bit client was installed on my 64-bit Windows 2008 R2 OS.

My solution: In the Advanced Settings for the Application Pool assigned to my ASP.NET application, I set Enable 32-Bit Applications to True.

Please see below for the standalone .ashx test script that I used to test the ability to connect to Oracle. Before making the Application Pool change, its response was:

[Running as 64-bit] Connection failed.

...and after the Application Pool change:

[Running as 32-bit] Connection succeeded.

TestOracle.ashx – Script to Test an Oracle Connection via System.Data.OracleClient:

To use: Change the user, password and host variables as appropriate.

Note that this script can be used in a standalone fashion without disturbing your ASP.NET web application project file. Just drop it in your application folder.

<%@ WebHandler Language="C#" Class="Handler1" %>
<%@ Assembly Name="System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" %>

using System;
using System.Data.OracleClient;
using System.Web;

public class Handler1 : IHttpHandler
{
    private static readonly string m_User = "USER";
    private static readonly string m_Password = "PASSWORD";
    private static readonly string m_Host = "HOST";

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string result = TestOracleConnection();
        context.Response.Write(result);
    }

    public bool IsReusable
    {
        get { return false; }
    }

    private string TestOracleConnection()
    {
        string result = IntPtr.Size == 8 ?
            "[Running as 64-bit]" : "[Running as 32-bit]";

        try
        {
            string connString = String.Format(
              "Data Source={0};Password={1};User ID={2};",
              m_Host, m_User, m_Password);

            OracleConnection oradb = new OracleConnection();
            oradb.ConnectionString = connString;
            oradb.Open();
            oradb.Close();
            result += " Connection succeeded.";
        }
        catch
        {
            result += " Connection failed.";
        }

        return result;
    }
}

Android Paint: .measureText() vs .getTextBounds()

My experience with this is that getTextBounds will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText assumes one line.

In order to get accurate measuring results, you should use the StaticLayout to render the text and pull out the measurements.

For example:

String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;

StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();

int *array = new int[n]; what is this function actually doing?

The statement basically does the following:

  1. Creates a integer array of 'n' elements
  2. Allocates the memory in HEAP memory of the process as you are using new operator to create the pointer
  3. Returns a valid address (if the memory allocation for the required size if available at the point of execution of this statement)

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

It could also be possible that you have created the "Products" in your login schema and you were trying to execute the same in a different schema (probably dbo)

Steps to resolve this issue

1)open the management studio 2) Locate the object in the explorer and identify the schema under which your object is? ( it is the text before your object name ). In the image below its the "dbo" and my object name is action status

highlighted part is schema name

if you see it like "yourcompanydoamin\yourloginid" then you should you can modify the permission on that specific schema and not any other schema.

you may refer to "Ownership and User-Schema Separation in SQL Server"

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Convert double to float in Java

Float.parseFloat(String.valueOf(your_number)

Convert from ASCII string encoded in Hex to plain ASCII?

No need to import any library:

>>> bytearray.fromhex("7061756c").decode()
'paul'

How to execute a java .class from the command line

With Java 11 you won't have to go through this rigmarole anymore!

Instead, you can do this:

> java MyApp.java

You don't have to compile beforehand, as it's all done in one step.

You can get the Java 11 JDK here: JDK 11 GA Release

Using $_POST to get select option value from HTML

<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>

try this

<?php 
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>

Split / Explode a column of dictionaries into separate columns with pandas

  • The fastest method to normalize a column of flat, one-level dicts, as per the timing analysis performed by Shijith in this answer:
    • df.join(pd.DataFrame(df.pop('Pollutants').values.tolist()))
    • It will not resolve other issues with columns of list or dicts that are addressed below, such as rows with NaN, or nested dicts.
  1. pd.json_normalize(df.Pollutants) is significantly faster than df.Pollutants.apply(pd.Series)
    • See the %%timeit below. For 1M rows, .json_normalize is 47 times faster than .apply.
  2. Whether reading data from a file, or from an object returned by a database, or API, it may not be clear if the dict column has dict or str type.
    • If the dictionaries in the column are str type, they must be converted back to a dict type, using ast.literal_eval.
  3. Use pd.json_normalize to convert the dicts, with keys as headers and values for rows.
    • Has additional parameters (e.g. record_path & meta) for dealing with nested dicts.
  4. Use pandas.DataFrame.join to combine the original DataFrame, df, with the columns created using pd.json_normalize
    • If the index isn't integers (as in the example), first use df.reset_index() to get an index of integers, before doing the normalize and join.
  5. Finally, use pandas.DataFrame.drop, to remove the unneeded column of dicts
  • As a note, if the column has any NaN, they must be filled with an empty dict
import pandas as pd
from ast import literal_eval
import numpy as np

data = {'Station ID': [8809, 8810, 8811, 8812, 8813, 8814],
        'Pollutants': ['{"a": "46", "b": "3", "c": "12"}', '{"a": "36", "b": "5", "c": "8"}', '{"b": "2", "c": "7"}', '{"c": "11"}', '{"a": "82", "c": "15"}', np.nan]}

df = pd.DataFrame(data)

# display(df)
   Station ID                        Pollutants
0        8809  {"a": "46", "b": "3", "c": "12"}
1        8810   {"a": "36", "b": "5", "c": "8"}
2        8811              {"b": "2", "c": "7"}
3        8812                       {"c": "11"}
4        8813            {"a": "82", "c": "15"}
5        8814                               NaN

# replace NaN with '{}' if the column is strings, otherwise replace with {}
# df.Pollutants = df.Pollutants.fillna('{}')  # if the NaN is in a column of strings
df.Pollutants = df.Pollutants.fillna({i: {} for i in df.index})  # if the column is not strings

# Convert the column of stringified dicts to dicts
# skip this line, if the column contains dicts
df.Pollutants = df.Pollutants.apply(literal_eval)

# reset the index if the index is not unique integers from 0 to n-1
# df.reset_index(inplace=True)  # uncomment if needed

# normalize the column of dictionaries and join it to df
df = df.join(pd.json_normalize(df.Pollutants))

# drop Pollutants
df.drop(columns=['Pollutants'], inplace=True)

# display(df)
   Station ID    a    b    c
0        8809   46    3   12
1        8810   36    5    8
2        8811  NaN    2    7
3        8812  NaN  NaN   11
4        8813   82  NaN   15
5        8814  NaN  NaN  NaN

%%timeit

# dataframe with 1M rows
dfb = pd.concat([df]*200000).reset_index(drop=True)

%%timeit
dfb.join(pd.json_normalize(dfb.Pollutants))
[out]:
5.44 s ± 32.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
pd.concat([dfb.drop(columns=['Pollutants']), dfb.Pollutants.apply(pd.Series)], axis=1)
[out]:
4min 17s ± 2.44 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

Checking whether a variable is an integer or not

The simplest way is:

if n==int(n):
    --do something--    

Where n is the variable

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

Javascript - How to extract filename from a file input control

var path = document.getElementById('upload').value;//take path
var tokens= path.split('\\');//split path
var filename = tokens[tokens.length-1];//take file name

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Today I faced Fatal signal 11 (SIGSEGV), code 1, fault addr 0x8 in tid 18161 issue and I struggle half day to solve this.

I tried many things clearing cache and deleting .gradle file and all.

Finally I disable Instant Run and now I am not getting this issue again. Now my application is working after enabling instant run also. It may be the instant run problem, Try with disabling and enabling instant run

From this answer:

Go to Android Studio Settings or Preferences (for MAC) -> Build,Execution,Deployment -> Instant Run.

Then deselect the "Enable Instant Run" checkbox at the top.

Val and Var in Kotlin

val : must add or initialized value but can't change. var: it's variable can ba change in any line in code.

How to make a GUI for bash scripts?

there is a command called dialog which uses the ncurses library. "Dialog is a program that will let you to present a variety of questions or display messages using dialog boxes from a shell script. These types of dialog boxes are implemented (though not all are necessarily compiled into dialog)"

see http://pwet.fr/man/linux/commandes/dialog

Absolute Positioning & Text Alignment

position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case, everything was set up correctly, but my Docker infrastructure needed more RAM. I'm using Docker for Mac, where default RAM was around 1 GB, and as MySQL uses around 1.5Gb of RAM ( and probably was crashing ??? ), changing the Docker RAM utilization level to 3-4 Gb solved the issue.

How to display a confirmation dialog when clicking an <a> link?

USING PHP, HTML AND JAVASCRIPT for prompting

Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

Tkinter example code for multiple windows, why won't buttons load correctly?

I tried to use more than two windows using the Rushy Panchal example above. The intent was to have the change to call more windows with different widgets in them. The butnew function creates different buttons to open different windows. You pass as argument the name of the class containing the window (the second argument is nt necessary, I put it there just to test a possible use. It could be interesting to inherit from another window the widgets in common.

import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.master.geometry("400x400")
        self.frame = tk.Frame(self.master)
        self.butnew("Window 1", "ONE", Demo2)
        self.butnew("Window 2", "TWO", Demo3)
        self.frame.pack()

    def butnew(self, text, number, _class):
        tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()

    def new_window(self, number, _class):
        self.newWindow = tk.Toplevel(self.master)
        _class(self.newWindow, number)


class Demo2:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("400x400+400+400")
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.label = tk.Label(master, text=f"this is window number {number}")
        self.label.pack()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

class Demo3:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("400x400+400+400")
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.label = tk.Label(master, text=f"this is window number {number}")
        self.label.pack()
        self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
        self.label2.pack()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()




def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Open the new window only once

To avoid having the chance to press multiple times the button having multiple windows... that are the same window, I made this script (take a look at this page too)

import tkinter as tk


def new_window1():
    global win1
    try:
        if win1.state() == "normal": win1.focus()
    except:
        win1 = tk.Toplevel()
        win1.geometry("300x300+500+200")
        win1["bg"] = "navy"
        lb = tk.Label(win1, text="Hello")
        lb.pack()


win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()

Update built-in vim on Mac OS X

Like Eric, I used homebrew, but I used the default recipe. So:

brew install mercurial
brew install vim

And after restarting the terminal homebrew's vim should be the default. If not, you should update your $PATH so that /usr/local/bin is before /usr/bin. E.g. add the following to your .profile:

export PATH=/usr/local/bin:$PATH

How to save local data in a Swift app?

Swift 5+

None of the answers really cover in detail the default built in local storage capabilities. It can do far more than just strings.

You have the following options straight from the apple documentation for 'getting' data from the defaults.

func object(forKey: String) -> Any?
//Returns the object associated with the specified key.

func url(forKey: String) -> URL?
//Returns the URL associated with the specified key.

func array(forKey: String) -> [Any]?
//Returns the array associated with the specified key.

func dictionary(forKey: String) -> [String : Any]?
//Returns the dictionary object associated with the specified key.

func string(forKey: String) -> String?
//Returns the string associated with the specified key.

func stringArray(forKey: String) -> [String]?
//Returns the array of strings associated with the specified key.

func data(forKey: String) -> Data?
//Returns the data object associated with the specified key.

func bool(forKey: String) -> Bool
//Returns the Boolean value associated with the specified key.

func integer(forKey: String) -> Int
//Returns the integer value associated with the specified key.

func float(forKey: String) -> Float
//Returns the float value associated with the specified key.

func double(forKey: String) -> Double
//Returns the double value associated with the specified key.

func dictionaryRepresentation() -> [String : Any]
//Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.

Here are the options for 'setting'

func set(Any?, forKey: String)
//Sets the value of the specified default key.

func set(Float, forKey: String)
//Sets the value of the specified default key to the specified float value.

func set(Double, forKey: String)
//Sets the value of the specified default key to the double value.

func set(Int, forKey: String)
//Sets the value of the specified default key to the specified integer value.

func set(Bool, forKey: String)
//Sets the value of the specified default key to the specified Boolean value.

func set(URL?, forKey: String)
//Sets the value of the specified default key to the specified URL.

If are storing things like preferences and not a large data set these are perfectly fine options.

Double Example:

Setting:

let defaults = UserDefaults.standard
var someDouble:Double = 0.5
defaults.set(someDouble, forKey: "someDouble")

Getting:

let defaults = UserDefaults.standard
var someDouble:Double = 0.0
someDouble = defaults.double(forKey: "someDouble")

What is interesting about one of the getters is dictionaryRepresentation, this handy getter will take all your data types regardless what they are and put them into a nice dictionary that you can access by it's string name and give the correct corresponding data type when you ask for it back since it's of type 'any'.

You can store your own classes and objects also using the func set(Any?, forKey: String) and func object(forKey: String) -> Any? setter and getter accordingly.

Hope this clarifies more the power of the UserDefaults class for storing local data.

On the note of how much you should store and how often, Hardy_Germany gave a good answer on that on this post, here is a quote from it

As many already mentioned: I'm not aware of any SIZE limitation (except physical memory) to store data in a .plist (e.g. UserDefaults). So it's not a question of HOW MUCH.

The real question should be HOW OFTEN you write new / changed values... And this is related to the battery drain this writes will cause.

IOS has no chance to avoid a physical write to "disk" if a single value changed, just to keep data integrity. Regarding UserDefaults this cause the whole file rewritten to disk.

This powers up the "disk" and keep it powered up for a longer time and prevent IOS to go to low power state.

Something else to note as mentioned by user Mohammad Reza Farahani from this post is the asynchronous and synchronous nature of userDefaults.

When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.

For example if you save and quickly close the program you may notice it does not save the results, this is because it's persisting asynchronously. You might not notice this all the time so if you plan on saving before quitting the program you may want to account for this by giving it some time to finish.

Maybe someone has some nice solutions for this they can share in the comments?

Get current URL path in PHP

You want $_SERVER['REQUEST_URI']. From the docs:

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

pandas get column average/mean

Additionally if you want to get the round value after finding the mean.

#Create a DataFrame
df1 = {
    'Subject':['semester1','semester2','semester3','semester4','semester1',
               'semester2','semester3'],
   'Score':[62.73,47.76,55.61,74.67,31.55,77.31,85.47]}
df1 = pd.DataFrame(df1,columns=['Subject','Score'])

rounded_mean = round(df1['Score'].mean()) # specified nothing as decimal place
print(rounded_mean) # 62

rounded_mean_decimal_0 = round(df1['Score'].mean(), 0) # specified decimal place as 0
print(rounded_mean_decimal_0) # 62.0

rounded_mean_decimal_1 = round(df1['Score'].mean(), 1) # specified decimal place as 1
print(rounded_mean_decimal_1) # 62.2

Manually map column names with class properties

Taken from the Dapper Tests which is currently on Dapper 1.42.

// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping), 
                                    (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);

Helper class to get name off the Description attribute (I personally have used Column like @kalebs example)

static string GetDescriptionFromAttribute(MemberInfo member)
{
   if (member == null) return null;

   var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
   return attrib == null ? null : attrib.Description;
}

Class

public class TypeWithMapping
{
   [Description("B")]
   public string A { get; set; }

   [Description("A")]
   public string B { get; set; }
}

How to escape special characters of a string with single backslashes

Just assuming this is for a regular expression, use re.escape.

Insert array into MySQL database with PHP

Let's not forget the most important thing to learn out of a question like this: SQL Injection.

Use PDO and prepared statements.

Click here for a tutorial on PDO.

XmlSerializer giving FileNotFoundException at constructor

Function XmlSerializer.FromTypes does not throw the exception, but it leaks the memory. Thats why you need to cache such serializer for every type to avoid memory leaking for every instance created.

Create your own XmlSerializer factory and use it simply:

XmlSerializer serializer = XmlSerializerFactoryNoThrow.Create(typeof(MyType));

The factory looks likes:

public static class XmlSerializerFactoryNoThrow
{
    public static Dictionary<Type, XmlSerializer> _cache = new Dictionary<Type, XmlSerializer>();

    private static object SyncRootCache = new object();        

    /// <summary>
    /// //the constructor XmlSerializer.FromTypes does not throw exception, but it is said that it causes memory leaks
    /// http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor
    /// That is why I use dictionary to cache the serializers my self.
    /// </summary>
    public static XmlSerializer Create(Type type)
    {
        XmlSerializer serializer;

        lock (SyncRootCache)
        {
            if (_cache.TryGetValue(type, out serializer))
                return serializer;
        }

        lock (type) //multiple variable of type of one type is same instance
        {
            //constructor XmlSerializer.FromTypes does not throw the first chance exception           
            serializer = XmlSerializer.FromTypes(new[] { type })[0];
            //serializer = XmlSerializerFactoryNoThrow.Create(type);
        }

        lock (SyncRootCache)
        {
            _cache[type] = serializer;
        }
        return serializer;
    }       
}

More complicated version without possibility of memory leak (please someone review the code):

    public static XmlSerializer Create(Type type)
    {
        XmlSerializer serializer;

        lock (SyncRootCache)
        {
            if (_cache.TryGetValue(type, out serializer))
                return serializer;
        }

        lock (type) //multiple variable of type of one type is same instance
        {
            lock (SyncRootCache)
            {
                if (_cache.TryGetValue(type, out serializer))
                    return serializer;
            }
            serializer = XmlSerializer.FromTypes(new[] { type })[0];
            lock (SyncRootCache)
            {
                _cache[type] = serializer;
            }
        }          
        return serializer;
    }       
}

Hiding a button in Javascript

<script>
    $('#btn_hide').click( function () {
      $('#btn_hide').hide();
    });
</script>
<input type="button" id="btn_hide"/>

this will be enough

How do you get the logical xor of two variables in Python?

  • Python logical or: A or B: returns A if bool(A) is True, otherwise returns B
  • Python logical and: A and B: returns A if bool(A) is False, otherwise returns B

To keep most of that way of thinking, my logical xor definintion would be:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
    else:
        return a or b

That way it can return a, b, or False:

>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'

How to detect string which contains only spaces?

Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.

if (!str.trim().length) {
  console.log('str is empty!');
}

You can read more about trim here.

How to find and restore a deleted file in a Git repository

For the best way to do that, try it.


First, find the commit id of the commit that deleted your file. It will give you a summary of commits which deleted files.

git log --diff-filter=D --summary

git checkout 84sdhfddbdddf~1

Note: 84sdhfddbddd is your commit id

Through this you can easily recover all deleted files.

Programmatically create a UIView with color gradient

My solution is to create UIView subclass with CAGradientLayer accessible as a readonly property. This will allow you to customize your gradient how you want and you don't need to handle layout changes yourself. Subclass implementation:

@interface GradientView : UIView

@property (nonatomic, readonly) CAGradientLayer *gradientLayer;

@end

@implementation GradientView

+ (Class)layerClass
{
    return [CAGradientLayer class];
}

- (CAGradientLayer *)gradientLayer
{
    return (CAGradientLayer *)self.layer;
}

@end

Usage:

self.iconBackground = [GradientView new];
[self.background addSubview:self.iconBackground];
self.iconBackground.gradientLayer.colors = @[(id)[UIColor blackColor].CGColor, (id)[UIColor whiteColor].CGColor];
self.iconBackground.gradientLayer.startPoint = CGPointMake(1.0f, 1.0f);
self.iconBackground.gradientLayer.endPoint = CGPointMake(0.0f, 0.0f);

How to dynamically remove items from ListView on a button click?

      private List<DataValue> datavalue=new ArrayList<Datavalue>;

     @Override
    public View getView(int position, View view, ViewGroup viewGroup) {

            view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                datavalue.remove(position);
                notifyDataSetChanged();
            }
        });
    }
    }

Why calling react setState method doesn't mutate the state immediately?

You could try using ES7 async/await. For instance using your example:

handleChange: async function(event) {
    console.log(this.state.value);
    await this.setState({value: event.target.value});
    console.log(this.state.value);
}

Error message: "'chromedriver' executable needs to be available in the path"

We have to add path string, begin with the letter r before the string, for raw string. I tested this way, and it works.

driver = webdriver.Chrome(r"C:/Users/michael/Downloads/chromedriver_win32/chromedriver.exe")

How to truncate text in Angular2?

Truncate Pipe with optional params:

  • limit - string max length
  • completeWords - Flag to truncate at the nearest complete word, instead of character
  • ellipsis - appended trailing suffix

-

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
    if (completeWords) {
      limit = value.substr(0, limit).lastIndexOf(' ');
    }
    return value.length > limit ? value.substr(0, limit) + ellipsis : value;
  }
}

Don't forget to add a module entry.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

Usage

Example String:

public longStr = 'A really long string that needs to be truncated';

Markup:

  <h1>{{longStr | truncate }}</h1> 
  <!-- Outputs: A really long string that... -->

  <h1>{{longStr | truncate : 12 }}</h1> 
  <!-- Outputs: A really lon... -->

  <h1>{{longStr | truncate : 12 : true }}</h1> 
  <!-- Outputs: A really... -->

  <h1>{{longStr | truncate : 12 : false : '***' }}</h1> 
  <!-- Outputs: A really lon*** -->

How to force a list to be vertical using html css

CSS

li {
   display: inline-block;
}

Works for me also.

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

How to get AM/PM from a datetime in PHP

Perfect answer for AM/PM live time solution

<?php echo date('h:i A', time())?>

WAMP won't turn green. And the VCRUNTIME140.dll error

Since you already had a running version of WAMP and it stopped working, you probably had VCRUNTIME140.dll already installed. In that case:

  1. Open Programs and Features
  2. Right-click on the respective Microsoft Visual C++ 20xx Redistributable installers and choose "Change"
  3. Choose "Repair". Do this for both x86 and x64

This did the trick for me.

Definition of int64_t

int64_t is typedef you can find that in <stdint.h> in C

How do I compare two variables containing strings in JavaScript?

instead of using the == sign, more safer use the === sign when compare, the code that you post is work well

Non-recursive depth first search algorithm

DFS:

list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
  currentnode = nodes_to_visit.take_first();
  nodes_to_visit.prepend( currentnode.children );
  //do something
}

BFS:

list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
  currentnode = nodes_to_visit.take_first();
  nodes_to_visit.append( currentnode.children );
  //do something
}

The symmetry of the two is quite cool.

Update: As pointed out, take_first() removes and returns the first element in the list.

fopen deprecated warning

If you want it to be used on many platforms, you could as commented use defines like:

#if defined(_MSC_VER) || defined(WIN32)  || defined(_WIN32) || defined(__WIN32__) \
                        || defined(WIN64)    || defined(_WIN64) || defined(__WIN64__) 

        errno_t err = fopen_s(&stream,name, "w");

#endif

#if defined(unix)        || defined(__unix)      || defined(__unix__) \
                        || defined(linux)       || defined(__linux)     || defined(__linux__) \
                        || defined(sun)         || defined(__sun) \
                        || defined(BSD)         || defined(__OpenBSD__) || defined(__NetBSD__) \
                        || defined(__FreeBSD__) || defined __DragonFly__ \
                        || defined(sgi)         || defined(__sgi) \
                        || defined(__MACOSX__)  || defined(__APPLE__) \
                        || defined(__CYGWIN__) 

        stream = fopen(name, "w");

#endif

Is there a performance difference between a for loop and a for-each loop?

The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.

I think the article is now here: new location

The link shown here was dead.

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Using variables inside strings

Use the following methods

1: Method one

var count = 123;
var message = $"Rows count is: {count}";

2: Method two

var count = 123;
var message = "Rows count is:" + count;

3: Method three

var count = 123;
var message = string.Format("Rows count is:{0}", count);

4: Method four

var count = 123;
var message = @"Rows
                count
                is:{0}" + count;

5: Method five

var count = 123;
var message = $@"Rows 
                 count 
                 is: {count}";

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

unix - count of columns in file

you may try:

head -1 stores.dat | grep -o \|  | wc -l

Android: How to detect double-tap?

Equivalent C# code which i used to implement same functionality and can even customize to accept N number of Taps

public interface IOnTouchInterface
{
    void ViewTapped();
}

public class MultipleTouchGestureListener : Java.Lang.Object, View.IOnTouchListener
{
    int clickCount = 0;
    long startTime;
    static long MAX_DURATION = 500;
    public int NumberOfTaps { get; set; } = 7;

    readonly IOnTouchInterface interfc;

    public MultipleTouchGestureListener(IOnTouchInterface tch)
    {
        this.interfc = tch;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        switch (e.Action)
        {
            case MotionEventActions.Down:
                clickCount++;
                if(clickCount == 1)
                    startTime = Utility.CurrentTimeSince1970;
                break;
            case MotionEventActions.Up:
                var currentTime = Utility.CurrentTimeSince1970;
                long time = currentTime - startTime;
                if(time <= MAX_DURATION * NumberOfTaps)
                {
                    if (clickCount == NumberOfTaps)
                    {
                        this.interfc.ViewTapped();
                        clickCount = 0;
                    }
                }
                else
                {
                    clickCount = 0;
                }
                break;
        }
        return true;
    }
}

public static class Utility
{
    public static long CurrentTimeSince1970
    {
        get
        {
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
            DateTime dtNow = DateTime.Now;
            TimeSpan result = dtNow.Subtract(dt);
            long seconds = (long)result.TotalMilliseconds;
            return seconds;
        }
    }
}

Currently Above code accepts 7 as number of taps before it raises the View Tapped event. But it can be customized with any number

Windows service on Local Computer started and then stopped error

Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:

protected override void OnStart(string[] args)
{
     System.Diagnostics.Debugger.Launch();
     ...
}

than you could attach your visual studio to the process and have better debug abilities.

hope this was helpful, good luck

PHP Fatal error: Using $this when not in object context

$foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();

Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.

Disable validation of HTML5 form elements

If you mark a form element as required="" then novalidate="" does not help.

A way to circumvent the required validation is to disable the element.

How To Run PHP From Windows Command Line in WAMPServer

In windows, put your php.exe file in windows/system32 or any other system executable folders and then go to command line and type php and hit enter following it, if it doesnt generate any error then you are ready to use PHP on command line. If you have set your php.exe somewhere else than default system folders then you need to set the path of it in the environment variables! You can get there in following path....

control panel -> System -> Edith the environment variables of your account -> Environment Vaiables -> path -> edit then set the absolute path of your php.exe there and follow the same procedure as in first paragraph, if nothing in the error department, then you are ready to use php from command line!

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

Here it is:

rfc2616#section-10.4.1 - 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

rfc7231#section-6.5.1 - 6.5.1. 400 Bad Request

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Refers to malformed (not wellformed) cases!

rfc4918 - 11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Conclusion

Rule of thumb: [_]00 covers the most general case and cases that are not covered by designated code.

422 fits best object validation error (precisely my recommendation:)
As for semantically erroneous - Think of something like "This username already exists" validation.

400 is incorrectly used for object validation

Getting HTML elements by their attribute names

In jQuery this is so:

$("span['property'=v:name]"); // for selecting your span element

Inserting one list into another list in java?

no... Once u have executed the statement anotherList.addAll(list) and after that if u change some list data it does not carry to another list

TensorFlow not found using pip

The only thing that worked for me was to use Ananconda and create a new conda env with conda create -n tensorflow python=3.5 then activate using activate tensorflow and finally conda install -c conda-forge tensorflow.

This works around every issue I had including ssl certs, proxy settings, and does not need admin access. It should be noted that this is not directly supported by the tensorflow team.

Source

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Split a List into smaller lists of N size

How about this one? The idea was to use only one loop. And, who knows, maybe you're using only IList implementations thorough your code and you don't want to cast to List.

private IEnumerable<IList<T>> SplitList<T>(IList<T> list, int totalChunks)
{
    IList<T> auxList = new List<T>();
    int totalItems = list.Count();

    if (totalChunks <= 0)
    {
        yield return auxList;
    }
    else 
    {
        for (int i = 0; i < totalItems; i++)
        {               
            auxList.Add(list[i]);           

            if ((i + 1) % totalChunks == 0)
            {
                yield return auxList;
                auxList = new List<T>();                
            }

            else if (i == totalItems - 1)
            {
                yield return auxList;
            }
        }
    }   
}

How to access Session variables and set them in javascript?

<?php
    session_start();
    $_SESSION['mydata']="some text";
?>

<script>
    var myfirstdata="<?php echo $_SESSION['mydata'];?>";
</script>

C++ String Concatenation operator<<

nametext is an std::string but these do not have the stream insertion operator (<<) like output streams do.

To concatenate strings you can use the append member function (or its equivalent, +=, which works in the exact same way) or the + operator, which creates a new string as a result of concatenating the previous two.

How to change the style of alert box?

I don't think you could change the style of browsers' default alert boxes.

You need to create your own or use a simple and customizable library like xdialog. Following is a example to customize the alert box. More demos can be found here.

_x000D_
_x000D_
function show_alert() {_x000D_
    xdialog.alert("Hello! I am an alert box!");_x000D_
}
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css"/>_x000D_
    <script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js"></script>_x000D_
    _x000D_
    <style>_x000D_
        .xd-content .xd-body .xd-body-inner {_x000D_
            max-height: unset;_x000D_
        }_x000D_
        .xd-content .xd-body p {_x000D_
            color: #f0f;_x000D_
            text-shadow: 0 0 5px rgba(0, 0, 0, 0.75);_x000D_
        }_x000D_
        .xd-content .xd-button.xd-ok {_x000D_
            background: #734caf;_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
<body>_x000D_
    <input type="button" onclick="show_alert()" value="Show alert box" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to do a FULL OUTER JOIN in MySQL?

Modified shA.t's query for more clarity:

-- t1 left join t2
SELECT t1.value, t2.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value   

    UNION ALL -- include duplicates

-- t1 right exclude join t2 (records found only in t2)
SELECT t1.value, t2.value
FROM t1 RIGHT JOIN t2 ON t1.value = t2.value
WHERE t1.value IS NULL 

android.content.res.Resources$NotFoundException: String resource ID #0x0

If we get the value as int and we set it to String, the error occurs. PFB my solution,

Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

If you have used CHECK CONSTRAINT on table for string field length

e.g: to check username length >= 8

use:

CHECK (CHAR_LENGTH(username)>=8)

instead of

CHECK (username>=8)

fix the check constraint if any have wrong datatype comparison

printing all contents of array in C#

I upvoted the extension method answer by Matthew Watson, but if you're migrating/visiting coming from Python, you may find such a method useful:

class Utils
{
    static void dump<T>(IEnumerable<T> list, string glue="\n")
    {
        Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
    }
}

-> this will print any collection using the separator provided. It's quite limited (nested collections?).

For a script (i.e. a C# console application which only contains Program.cs, and most things happen in Program.Main) - this may be just fine.

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

How to end C++ code

People are saying "call exit(return code)," but this is bad form. In small programs it is fine, but there are a number of issues with this:

  1. You will end up having multiple exit points from the program
  2. It makes code more convoluted (like using goto)
  3. It cannot release memory allocated at runtime

Really, the only time you should exit the problem is with this line in main.cpp:

return 0;

If you are using exit() to handle errors, you should learn about exceptions (and nesting exceptions), as a much more elegant and safe method.

How to listen for a WebView finishing loading a URL?

Use this it should help.`var currentUrl = "google.com" var partOfUrl = currentUrl.substring(0, currentUrl.length-2)

webView.setWebViewClient(object: WebViewClient() {

override fun onLoadResource(WebView view, String url) {
     //call loadUrl() method  here 
     // also check if url contains partOfUrl, if not load it differently.
     if(url.contains(partOfUrl, true)) {
         //it should work if you reach inside this if scope.
     } else if(!(currentUrl.startWith("w", true))) {
         webView.loadurl("www.$currentUrl")

     } else if(!(currentUrl.startWith("h", true))) {
         webView.loadurl("https://$currentUrl")

     } else { ...}


 }

override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
   // you can call again loadUrl from here too if there is any error.
}

//You should also override other override method for error such as onReceiveError to see how all these methods are called one after another and how they behave while debugging with break point. } `

Recursion or Iteration?

As far as I know, Perl does not optimize tail-recursive calls, but you can fake it.

sub f{
  my($l,$r) = @_;

  if( $l >= $r ){
    return $l;
  } else {

    # return f( $l+1, $r );

    @_ = ( $l+1, $r );
    goto &f;

  }
}

When first called it will allocate space on the stack. Then it will change its arguments, and restart the subroutine, without adding anything more to the stack. It will therefore pretend that it never called its self, changing it into an iterative process.

Note that there is no "my @_;" or "local @_;", if you did it would no longer work.

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

Repeat a task with a time delay?

Try following example it works !!!

Use [Handler] in onCreate() method which makes use of postDelayed() method that Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses that is 0 in given example. 1

Refer this code :

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
    //------------------
    //------------------
    android.os.Handler customHandler = new android.os.Handler();
            customHandler.postDelayed(updateTimerThread, 0);
}

private Runnable updateTimerThread = new Runnable()
{
        public void run()
        {
            //write here whaterver you want to repeat
            customHandler.postDelayed(this, 1000);
        }
};

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

Add number of days to a date

//Set time zone
date_default_timezone_set("asia/kolkata");
$pastdate='2016-07-20';
$addYear=1;
$addMonth=3;
$addWeek=2;
$addDays=5;
$newdate=date('Y-m-d', strtotime($pastdate.' +'.$addYear.' years +'.$addMonth. ' months +'.$addWeek.' weeks +'.$addDays.' days'));
echo $newdate;

Load arrayList data into JTable

Basic method for beginners like me.

public void loadDataToJtable(ArrayList<String> liste){
        
    rows = table.getRowCount();

    cols = table.getColumnCount();

    for (int i = 0; i < rows ; i++) {

            for ( int k  = 0; k < cols ; k++) {
            
            for (int h = 0; h < list1.size(); h++) {
                
                String b =  list1.get(h);
                b = table.getValueAt(i, k).toString();
                
            }
        }
    }
}

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

I wanted learn how to use vagrant with virtualbox, when I got the error message 'Raw-mode is unavailable courtesy of Hyper-V'. To fix this issue, I think I made all of the suggested changes above (thank you guys), and some more.

Let me summarize:

( cmd: optionalfeatures )
Turn off 'Hyper-V'
Turn off 'Containers'
Turn off 'Windows Subsystem for Linux'

Turn off 'Hyper-V' and 'Containers' Turn off 'Windows Subsystem for Linux'

cmd: bcdedit /set hypervisorlaunchtype off

bcdedit hypervisorlaunchtype off

( cmd: gpedit.msc )
Local Computer Policy -> Computer Configuration -> Administrative Templates -> System -> Device Guard ->
Disable 'Turn On Virtualization Based Security'

Disable Virtualization Based Security

Settings -> Update & Security -> Windows Security -> Device Security -> Core isolation details -> Memory integrity -> Off

enter image description here

Check which element has been clicked with jQuery

Another option can be to utilize the tagName property of the e.target. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV or an A tag, and I want to see if that class was clicked, and determine whether it was the DIV or the A that was clicked. I can do something like:

$('.example-class').click(function(e){
  if ((e.target.tagName.toLowerCase()) == 'a') {
    console.log('You clicked an A element.');
  } else { // DIV, we assume in this example
    console.log('You clicked a DIV element.');
  }
});

How to efficiently remove duplicates from an array without using Set

public class RemoveDuplicates {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int size;
        System.out.println("Enter an array size");
        Scanner sc=new Scanner(System.in);
        size = sc.nextInt();

        int arr[] = new int[size];

        System.out.println("Enter "+size+" numbers");
        for(int i=0;i<size;i++){
            arr[i]=sc.nextInt();
        }

        for(int i=0;i<size;i++){
            int count=0;
            for(int j=i+1;j<size;j++){
                if(arr[i]==arr[j]){

                    int shiftLeft = j;

                    for (int k = j+1; k < size; k++, shiftLeft++) {
                        arr[shiftLeft] = arr[k];
                    }
                    size--;
                    j--;
                }
            }
        }
        System.out.println("New Array");
        for(int i=0;i<size;i++)
        {
            System.out.println(arr[i]);
        }
    }

}

Sorting a Data Table

This worked for me:

dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();

How do I flush the cin buffer?

int i;
  cout << "Please enter an integer value: ";

  // cin >> i; leaves '\n' among possible other junk in the buffer. 
  // '\n' also happens to be the default delim character for getline() below.
  cin >> i; 
  if (cin.fail()) 
  {
    cout << "\ncin failed - substituting: i=1;\n\n";
    i = 1;
  }
  cin.clear(); cin.ignore(INT_MAX,'\n'); 

  cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";

  string myString;
  cout << "What's your full name? (spaces inclded) \n";
  getline (cin, myString);
  cout << "\nHello '" << myString << "'.\n\n\n";

How to keep a VMWare VM's clock in sync?

I'll answer for Windows guests. If you have VMware Tools installed, then the taskbar's notification area (near the clock) has an icon for VMware Tools. Double-click that and set your options.

If you don't have VMware Tools installed, you can still set the clock's option for internet time to sync with some NTP server. If your physical machine serves the NTP protocol to your guest machines then you can get that done with host-only networking. Otherwise you'll have to let your guests sync with a genuine NTP server out on the internet, for example time.windows.com.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

You probably want to use something like jQuery, which makes JS programming easier.

Something like:

$(document).ready(function(){
   // Your code here
});

Would seem to do what you are after.

Make footer stick to bottom of page using Twitter Bootstrap

As discussed in the comments you have based your code on this solution: https://stackoverflow.com/a/8825714/681807

One of the key parts of this solution is to add height: 100% to html, body so the #footer element has a base height to work from - this is missing from your code:

html,body{
    height: 100%
}

You will also find that you will run into problems with using bottom: -50px as this will push your content under the fold when there isn't much content. You will have to add margin-bottom: 50px to the last element before the #footer.

How do I use namespaces with TypeScript external modules?

OP I'm with you man. again too, there is nothing wrong with that answer with 300+ up votes, but my opinion is:

  1. what is wrong with putting classes into their cozy warm own files individually? I mean this will make things looks much better right? (or someone just like a 1000 line file for all the models)

  2. so then, if the first one will be achieved, we have to import import import... import just in each of the model files like man, srsly, a model file, a .d.ts file, why there are so many *s in there? it should just be simple, tidy, and that's it. Why I need imports there? why? C# got namespaces for a reason.

  3. And by then, you are literally using "filenames.ts" as identifiers. As identifiers... Come on its 2017 now and we still do that? Ima go back to Mars and sleep for another 1000 years.

So sadly, my answer is: nop, you cannot make the "namespace" thing functional if you do not using all those imports or using those filenames as identifiers (which I think is really silly). Another option is: put all of those dependencies into a box called filenameasidentifier.ts and use

export namespace(or module) boxInBox {} .

wrap them so they wont try to access other classes with same name when they are just simply trying to get a reference from the class sit right on top of them.

How to properly add 1 month from now to current date in moment.js

_x000D_
_x000D_
startdate = "20.03.2020";_x000D_
    var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');_x000D_
_x000D_
     alert(new_date)
_x000D_
_x000D_
_x000D_

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

How do I force detach Screen from another SSH session?

Short answer

  1. Reattach without ejecting others: screen -x
  2. Get list of displays: ^A *, select the one to disconnect, press d


Explained answer

Background: When I was looking for the solution with same problem description, I have always landed on this answer. I would like to provide more sensible solution. (For example: the other attached screen has a different size and a I cannot force resize it in my terminal.)

Note: PREFIX is usually ^A = ctrl+a

Note: the display may also be called:

  • "user front-end" (in at command manual in screen)
  • "client" (tmux vocabulary where this functionality is detach-client)
  • "terminal" (as we call the window in our user interface) /depending on

1. Reattach a session: screen -x

-x attach to a not detached screen session without detaching it

2. List displays of this session: PREFIX *

It is the default key binding for: PREFIX :displays. Performing it within the screen, identify the other display we want to disconnect (e.g. smaller size). (Your current display is displayed in brighter color/bold when not selected).

term-type   size         user interface           window       Perms
---------- ------- ---------- ----------------- ----------     -----
 screen     240x60         you@/dev/pts/2      nb  0(zsh)        rwx
 screen      78x40         you@/dev/pts/0      nb  0(zsh)        rwx

Using arrows ? ?, select the targeted display, press d If nothing happens, you tried to detach your own display and screen will not detach it. If it was another one, within a second or two, the entry will disappear.

Press ENTER to quit the listing.

Optionally: in order to make the content fit your screen, reflow: PREFIX F (uppercase F)

Excerpt from man page of screen:

displays

Shows a tabular listing of all currently connected user front-ends (displays). This is most useful for multiuser sessions. The following keys can be used in displays list:

  • mouseclick Move to the selected line. Available when "mousetrack" is set to on.
  • space Refresh the list
  • d Detach that display
  • D Power detach that display
  • C-g, enter, or escape Exit the list

How can I get a user's media from Instagram without authenticating as a user?

Well, as /?__a=1 stopped working by now, it's better to use curl and parse the instagram page as written at this answer: Generate access token Instagram API, without having to log in?

How do I convert Int/Decimal to float in C#?

It is just:

float f = (float)6;

How do I add a library path in cmake?

might fail working with link_directories, then add each static library like following:

target_link_libraries(foo /path_to_static_library/libbar.a)

Android Preventing Double Click On A Button

I fix this problem using two clases, one similar to @jinshiyi11 answer's and the anoter is based on explicit click, in this you can click a button only once time, if you want another click you have to indicate it explicitly.

/**
 * Listener que sólo permite hacer click una vez, para poder hacer click
 * posteriormente se necesita indicar explicitamente.
 *
 * @author iberck
 */
public abstract class OnExplicitClickListener implements View.OnClickListener {

    // you can perform a click only once time
    private boolean canClick = true;

    @Override
    public synchronized void onClick(View v) {
        if (canClick) {
            canClick = false;
            onOneClick(v);
        }
    }

    public abstract void onOneClick(View v);

    public synchronized void enableClick() {
        canClick = true;
    }

    public synchronized void disableClick() {
        canClick = false;
    }
}

Example of use:

OnExplicitClickListener clickListener = new OnExplicitClickListener() {
    public void onOneClick(View v) {
        Log.d("example", "explicit click");
        ...
        clickListener.enableClick();    
    }
}
button.setOnClickListener(clickListener);

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

Differences between time complexity and space complexity?

First of all, the space complexity of this loop is O(1) (the input is customarily not included when calculating how much storage is required by an algorithm).

So the question that I have is if its possible that an algorithm has different time complexity from space complexity?

Yes, it is. In general, the time and the space complexity of an algorithm are not related to each other.

Sometimes one can be increased at the expense of the other. This is called space-time tradeoff.

Before and After Suite execution hook in jUnit 4.x

Since maven-surefire-plugin does not run Suite class first but treats suite and test classes same, so we can configure plugin as below to enable only suite classes and disable all the tests. Suite will run all the tests.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <includes>
                    <include>**/*Suite.java</include>
                </includes>
                <excludes>
                    <exclude>**/*Test.java</exclude>
                    <exclude>**/*Tests.java</exclude>
                </excludes>
            </configuration>
        </plugin>

AngularJS HTTP post to PHP and undefined

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

Is there a difference between `continue` and `pass` in a for loop in python?

continue will jump back to the top of the loop. pass will continue processing.

if pass is at the end for the loop, the difference is negligible as the flow would just back to the top of the loop anyway.

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

jquery mobile background image

Override ui-page class in your css:

.ui-page {
    background: url("image.gif");
    background-repeat: repeat;
}

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

require_once :failed to open stream: no such file or directory

The error pretty much explains what the problem is: you are trying to include a file that is not there.

Try to use the full path to the file, using realpath(), and use dirname(__FILE__) to get your current directory:

require_once(realpath(dirname(__FILE__) . '/../includes/dbconn.inc'));

How to slice a Pandas Data Frame by position?

I can see at least three options:

1.

df[:10]

2. Using head

df.head(10)

For negative values of n, this function returns all rows except the last n rows, equivalent to df[:-n] [Source].

3. Using iloc

df.iloc[:10]

How to initialize an array in Java?

Try data = new int[] {10,20,30,40,50,60,71,80,90,91 };

How do I enumerate the properties of a JavaScript object?

Simple JavaScript code:

for(var propertyName in myObject) {
   // propertyName is what you want.
   // You can get the value like this: myObject[propertyName]
}

jQuery:

jQuery.each(obj, function(key, value) {
   // key is what you want.
   // The value is in: value
});

How to compare data between two table in different databases using Sql Server 2008?

select * 
from (
      select 'T1' T, *
      from DB1.dbo.Table
      except
      select 'T2' T, *
      from DB2.dbo.Table
     ) as T
union all
select * 
from (
      select 'T2' T, *
      from DB2.dbo.Table
      except
      select 'T1' T, *
      from DB1.dbo.Table
     ) as T
ORDER BY 2,3,4, ..., 1  -- make T1 and T2 to be close in output 2,3,4 are UNIQUE KEY SEGMENTS

Test code:

declare @T1 table (ID int)
declare @T2 table (ID int)

insert into @T1 values(1),(2)
insert into @T2 values(2),(3)

select * 
from (
      select *
      from @T1
      except
      select *
      from @T2
     ) as T
union all
select * 
from (
      select *
      from @T2
      except
      select *
      from @T1
     ) as T

Result:

ID
-----------
1
3

Note: It can take long time to compare big table, when developing "tuned" solution or refactorig, which will give same result as REFERERCE - it may be wise to chekc simple parameters first: like

select count(t.*) from (
   select count(*) c0, SUM(BINARY_CHECKSUM(*)%1000000) c1 FROM T_REF_TABLE 
   -- select 12345 c0, -214365454 c1 -- constant values FROM T_REF_TABLE 
   except 
   select count(*) , SUM(BINARY_CHECKSUM(*)%1000000) FROM T_WORK_COPY 
) t

When this is empty, you have probably things under controll, and may be you can modify when you fail you will see "constant values FROM T_REF" to isert to save even more time for next check!!!

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

How to make an executable JAR file?

A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main Class is in the jar file. Example code would be as follows.

public class JarExample {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // your logic here
            }
        });
    }
}

Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF). For example,

Manifest-Version: 1.0
Main-Class: JarExample

Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)

jar cfm jarexample.jar jexample.mf *.class

It will create executable jarexample.jar.

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

Anchor links in Angularjs?

You could try to use anchorScroll.

Example

So the controller would be:

app.controller('MainCtrl', function($scope, $location, $anchorScroll, $routeParams) {
  $scope.scrollTo = function(id) {
     $location.hash(id);
     $anchorScroll();
  }
});

And the view:

<a href="" ng-click="scrollTo('foo')">Scroll to #foo</a>

...and no secret for the anchor id:

<div id="foo">
  This is #foo
</div>

How can I replace non-printable Unicode characters in Java?

methods in blow for your goal

public static String removeNonAscii(String str)
{
    return str.replaceAll("[^\\x00-\\x7F]", "");
}

public static String removeNonPrintable(String str) // All Control Char
{
    return str.replaceAll("[\\p{C}]", "");
}

public static String removeSomeControlChar(String str) // Some Control Char
{
    return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
}

public static String removeFullControlChar(String str)
{
    return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
} 

How do I access nested HashMaps in Java?

import java.util.*;
public class MyFirstJava {
public static void main(String[] args)
{
  Animal dog = new Animal();
  dog.Info("Dog","Breezi","Lab","Chicken liver");
  dog.Getname();
  Animal dog2= new Animal();
  dog2.Info("Dog", "pumpkin", "POM", "Pedigree");
  dog2.Getname();
  HashMap<String,  HashMap<String, Object>> dogs = new HashMap<>();
  dogs.put("dog1", new HashMap<>() {{put("Name",dog.name); 
  put("Food",dog.food);put("Age",3);}});
  dogs.put("dog2", new HashMap<>() {{put("Name",dog2.name); 
  put("Food",dog2.food);put("Age",6);}});
  //dogs.get("dog1");
  System.out.print(dogs + "\n");
  System.out.print(dogs.get("dog1").get("Age"));

} }

How to convert a command-line argument to int?

Like that we can do....

int main(int argc, char *argv[]) {

    int a, b, c;
    *// Converting string type to integer type
    // using function "atoi( argument)"* 

    a = atoi(argv[1]);     
    b = atoi(argv[2]);
    c = atoi(argv[3]);

 }

move column in pandas dataframe

An alternative, more generic method;

from pandas import DataFrame


def move_columns(df: DataFrame, cols_to_move: list, new_index: int) -> DataFrame:
    """
    This method re-arranges the columns in a dataframe to place the desired columns at the desired index.
    ex Usage: df = move_columns(df, ['Rev'], 2)   
    :param df:
    :param cols_to_move: The names of the columns to move. They must be a list
    :param new_index: The 0-based location to place the columns.
    :return: Return a dataframe with the columns re-arranged
    """
    other = [c for c in df if c not in cols_to_move]
    start = other[0:new_index]
    end = other[new_index:]
    return df[start + cols_to_move + end]

Center align a column in twitter bootstrap

The question is correctly answered here Center a column using Twitter Bootstrap 3

For odd rows: i.e., col-md-7 or col-large-9 use this

Add col-centered to the column you want centered.

<div class="col-lg-11 col-centered">    

And add this to your stylesheet:

.col-centered{
float: none;
margin: 0 auto;
}

For even rows: i.e., col-md-6 or col-large-10 use this

Simply use bootstrap 3's offset col class. i.e.,

<div class="col-lg-10 col-lg-offset-1">

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

Similar to the previous answer: Just use the 'name' key with your regular add_index line:

def change
  add_index :studies, :user_id, name: 'my_index'
end

What does $(function() {} ); do?

This is a shortcut for $(document).ready(), which is executed when the browser has finished loading the page (meaning here, "when the DOM is available"). See http://www.learningjquery.com/2006/09/introducing-document-ready. If you are trying to call example() before the browser has finished loading the page, it may not work.

Sending Email in Android using JavaMail API without using the default/built-in app

I found a shorter alternative for others who need help. The code is:

package com.example.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailTLS {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username", "password");
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Source: Sending Email via JavaMail API

Hope this Helps! Good Luck!

How to include !important in jquery

If you need to have jquery use !important for more than one item, this is how you would do it.

e.g. set an img tags max-width and max-height to 500px each

$('img').css('cssText', "max-width: 500px !important;' + "max-height: 500px !important;');

Redraw datatables after using ajax to refresh the table content?

It looks as if you could use the API functions to

  • clear the table ( fnClearTable )
  • add new data to the table ( fnAddData)
  • redraw the table ( fnDraw )

http://datatables.net/api

UPDATE

I guess you're using the DOM Data Source (for server-side processing) to generate your table. I didn't really get that at first, so my previous answer won't work for that.

To get it to work without rewriting your server side code:

What you'll need to do is totally remove the old table (in the dom) and replace it with the ajax result content, then reinitialize the datatable:

// in your $.post callback:

function (data) {

    // remove the old table
    $("#ajaxresponse").children().remove();

    // replace with the new table
    $("#ajaxresponse").html(data);

    // reinitialize the datatable
    $('#rankings').dataTable( {
    "sDom":'t<"bottom"filp><"clear">',
    "bAutoWidth": false,
    "sPaginationType": "full_numbers",
        "aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

    } 
    );
}

How do I call a function twice or more times consecutively?

You could define a function that repeats the passed function N times.

def repeat_fun(times, f):
    for i in range(times): f()

If you want to make it even more flexible, you can even pass arguments to the function being repeated:

def repeat_fun(times, f, *args):
    for i in range(times): f(*args)

Usage:

>>> def do():
...   print 'Doing'
... 
>>> def say(s):
...   print s
... 
>>> repeat_fun(3, do)
Doing
Doing
Doing
>>> repeat_fun(4, say, 'Hello!')
Hello!
Hello!
Hello!
Hello!

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Cannot open local file - Chrome: Not allowed to load local resource

1) Open your terminal and type

npm install -g http-server

2) Go to the root folder that you want to serve you files and type:

http-server ./

3) Read the output of the terminal, something kinda http://localhost:8080 will appear.

Everything on there will be allowed to be got. Example:

background: url('http://localhost:8080/waw.png');

A JOIN With Additional Conditions Using Query Builder or Eloquent

There's a difference between the raw queries and standard selects (between the DB::raw and DB::select methods).

You can do what you want using a DB::select and simply dropping in the ? placeholder much like you do with prepared statements (it's actually what it's doing).

A small example:

$results = DB::select('SELECT * FROM user WHERE username=?', ['jason']);

The second parameter is an array of values that will be used to replace the placeholders in the query from left to right.

How to execute a file within the python interpreter?

For Python 3:

>>> exec(open("helloworld.py").read())

Make sure that you're in the correct directory before running the command.

To run a file from a different directory, you can use the below command:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

Converting List<String> to String[] in Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

How to get bean using application context in spring boot

Using SpringApplication.run(Class<?> primarySource, String... arg) worked for me. E.g.:

@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class, args);

    }
}

Calling C++ class methods via a function pointer

A function pointer to a class member is a problem that is really suited to using boost::function. Small example:

#include <boost/function.hpp>
#include <iostream>

class Dog 
{
public:
   Dog (int i) : tmp(i) {}
   void bark ()
   {
      std::cout << "woof: " << tmp << std::endl;
   }
private:
   int tmp;
};



int main()
{
   Dog* pDog1 = new Dog (1);
   Dog* pDog2 = new Dog (2);

   //BarkFunction pBark = &Dog::bark;
   boost::function<void (Dog*)> f1 = &Dog::bark;

   f1(pDog1);
   f1(pDog2);
}

How do I consume the JSON POST data in an Express application

Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:

        const res_data = JSON.parse(body);

Display PDF file inside my android application

Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
    startActivity(pdfIntent ); 
    }
catch (ActivityNotFoundException e) {
    Toast.makeText(EmptyBlindDocumentShow.this,
            "No Application available to viewPDF",
            Toast.LENGTH_SHORT).show();
    }  
}  

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

If you would like to purposely link your project A in Release against another project B in Debug, say to keep the overall performance benefits of your application while debugging, then you will likely hit this error. You can fix this by temporarily modifying the preprocessor flags of project B to disable iterator debugging (and make it match project A):

In Project B's "Debug" properties, Configuration Properties -> C/C++ -> Preprocessor, add the following to Preprocessor Definitions:

_HAS_ITERATOR_DEBUGGING=0;_ITERATOR_DEBUG_LEVEL=0;

Rebuild project B in Debug, then build project A in Release and it should link correctly.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

import java.lang.*;
import java.io.*;
public class rupee
{
public static void main(String[] args)throws  IOException
{

int len=0,revnum=0,i,dup=0,j=0,k=0;
int gvalue;
 String[] ones={"one","Two","Three","Four","Five","Six","Seven","Eight","Nine","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",""};
String[] twos={"Ten","Twenty","Thirty","Fourty","fifty","Sixty","Seventy","eighty","Ninety",""};
System.out.println("\n Enter value");
InputStreamReader b=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(b);
gvalue=Integer.parseInt(br.readLine());
if(gvalue==10)

   System.out.println("Ten");

else if(gvalue==100)

  System.out.println("Hundred");

else if(gvalue==1000)
  System.out.println("Thousand");

dup=gvalue;
for(i=0;dup>0;i++)
{
  revnum=revnum*10+dup%10;
  len++;
  dup=dup/10;
}
while(j<len)
{
 if(gvalue<10)
 {
  System.out.println(ones[gvalue-1]);
 }
else if(gvalue>10&&gvalue<=19)
 {
  System.out.println(ones[gvalue-2]);
  break;
 }
else if(gvalue>19&&gvalue<100)
 {
   k=gvalue/10;
   gvalue=gvalue%10;
   System.out.println(twos[k-1]);
 }
else if(gvalue>100&&gvalue<1000)
 {
   k=gvalue/100;
   gvalue=gvalue%100;
   System.out.println(ones[k-1] +"Hundred");
 }
else if(gvalue>=1000&&gvalue<9999)
 {
   k=gvalue/1000;
   gvalue=gvalue%1000;
   System.out.println(ones[k-1]+"Thousand");
}
else if(gvalue>=11000&&gvalue<=19000)
 {
  k=gvalue/1000;
  gvalue=gvalue%1000;
  System.out.println(twos[k-2]+"Thousand");
 }      
else if(gvalue>=12000&&gvalue<100000)
{
 k=gvalue/10000;
     gvalue=gvalue%10000;
 System.out.println(ones[gvalue-1]);
}
else
{
 System.out.println("");
    }
j++;
}
}
}

Maven compile: package does not exist

Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.

How do I change the figure size for a seaborn plot?

Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.

sns.catplot(data=df, x='xvar', y='yvar', 
    hue='hue_bar', height=8.27, aspect=11.7/8.27)

See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.

String literals and escape characters in postgresql

Cool.

I also found the documentation regarding the E:

http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS

PostgreSQL also accepts "escape" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \b is a backspace, \f is a form feed, \n is a newline, \r is a carriage return, \t is a tab. Also supported are \digits, where digits represents an octal byte value, and \xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\). Also, a single quote can be included in an escape string by writing \', in addition to the normal way of ''.

Automate scp file transfer using a shell script

Instead of hardcoding password in a shell script, use SSH keys, its easier and secure.

$ scp -i ~/.ssh/id_rsa *.derp [email protected]:/path/to/target/directory/

assuming your private key is at ~/.ssh/id_rsa and the files you want to send can be filtered with *.derp

To generate a public / private key pair :

$ ssh-keygen -t rsa

The above will generate 2 files, ~/.ssh/id_rsa (private key) and ~/.ssh/id_rsa.pub (public key)

To setup the SSH keys for usage (one time task) : Copy the contents of ~/.ssh/id_rsa.pub and paste in a new line of ~devops/.ssh/authorized_keys in myserver.org server. If ~devops/.ssh/authorized_keys doesn't exist, feel free to create it.

A lucid how-to guide is available here.

How to create range in Swift?

(1..<10)

returns...

Range = 1..<10

How do you install an APK file in the Android emulator?

06-11-2020

Drag and Drop didn't work for me on Windows 10 Pro.

  1. Put the APK on Google Drive

  2. Access that Google drive using Chrome browser on the Android Emulator

  3. Then install it from there.

Note: You need to enable unknown sources within the Emulator.

Hash function for a string

-- The way to go these days --

Use SipHash. For your own protection.

-- Old and Dangerous --

unsigned int RSHash(const std::string& str)
{
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(std::size_t i = 0; i < str.length(); i++)
    {
        hash = hash * a + str[i];
        a    = a * b;
    }

    return (hash & 0x7FFFFFFF);
 }

 unsigned int JSHash(const std::string& str)
 {
      unsigned int hash = 1315423911;

      for(std::size_t i = 0; i < str.length(); i++)
      {
          hash ^= ((hash << 5) + str[i] + (hash >> 2));
      }

      return (hash & 0x7FFFFFFF);
 }

Ask google for "general purpose hash function"

How to create a hex dump of file containing only the hex characters without spaces in bash?

It seems to depend on the details of the version of od. On OSX, use this:

od -t x1 -An file |tr -d '\n '

(That's print as type hex bytes, with no address. And whitespace deleted afterwards, of course.)

How to "add existing frameworks" in Xcode 4?

The frameworks directory is as follow in my computer: /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks

not the directory

/Developer/SDKs/MacOSXversion.sdk/System/Library/Frameworks

How to find what code is run by a button or element in Chrome using Developer Tools

Solution 1: Framework blackboxing

Works great, minimal setup and no third parties.

According to Chrome's documentation:

What happens when you blackbox a script?

Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.

Here's the updated workflow:
  1. Pop open Chrome Developer Tools (F12 or ?+?+i), go to settings (upper right, or F1). Find a tab on the left called "Blackboxing"

enter image description here

  1. This is where you put the RegEx pattern of the files you want Chrome to ignore while debugging. For example: jquery\..*\.js (glob pattern/human translation: jquery.*.js)
  2. If you want to skip files with multiple patterns you can add them using the pipe character, |, like so: jquery\..*\.js|include\.postload\.js (which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.
  3. Now continue to Solution 3 described down below.

Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/

You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:

enter image description here


Solution 2: Visual Event

enter image description here

It's an excellent tool to have:

Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:

  • Which elements have events attached to them
  • The type of events attached to an element
  • The code that will be run with the event is triggered
  • The source file and line number for where the attached function was defined (Webkit browsers and Opera only)


Solution 3: Debugging

You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.

In this instance, I want to know what exactly goes on when I click the button.

  1. Open Dev Tools -> Sources tab, and on the right find Event Listener Breakpoints:

    enter image description here

  2. Expand Mouse and select click

  3. Now click the element (execution should pause), and you are now debugging the code. You can go through all code pressing F11 (which is Step in). Or go back a few jumps in the stack. There can be a ton of jumps


Solution 4: Fishing keywords

With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:

enter image description here

and searching #envio or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.

Be aware sometimes there's not only an img but lots of elements stacked, and you may not know which one triggers the code.


If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.

How to config routeProvider and locationProvider in angularJS?

@Simple-Solution

I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run

python -m SimpleHTTPServer 8080

And that sets up the simple server on port 8080 letting you visit localhost:8080 on your browser to view the app in development.

Hope that helped!

Angular EXCEPTION: No provider for Http

If you have this error in your tests, you should create Fake Service for all services:

For example:

import { YourService1 } from '@services/your1.service';
import { YourService2 } from '@services/your2.service';

class FakeYour1Service {
 public getSomeData():any { return null; }
}

class FakeYour2Service {
  public getSomeData():any { return null; }
}

And in beforeEach:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      Your1Service,
      Your2Service,
      { provide: Your1Service, useClass: FakeYour1Service },
      { provide: Your2Service, useClass: FakeYour2Service }
    ]
  }).compileComponents();  // compile template and css
}));

Find the 2nd largest element in an array with minimum number of comparisons

function findSecondLargeNumber(arr){

    var fLargeNum = 0;
    var sLargeNum = 0;

    for(var i=0; i<arr.length; i++){
        if(fLargeNum < arr[i]){
            sLargeNum = fLargeNum;
            fLargeNum = arr[i];         
        }else if(sLargeNum < arr[i]){
            sLargeNum = arr[i];
        }
    }

    return sLargeNum;

}
var myArray = [799, -85, 8, -1, 6, 4, 3, -2, -15, 0, 207, 75, 785, 122, 17];

Ref: http://www.ajaybadgujar.com/finding-second-largest-number-from-array-in-javascript/

How to install Java 8 on Mac

Java8 is no longer available on homebrew, brew install java8 will not work.

Instead, use:

brew cask install adoptopenjdk/openjdk/adoptopenjdk8

See this commit for technical details.

Please note as well you may see issues around Cask adoptopenjdk8 exists in multiple taps. This is a known issue, currently being worked on, which you can see here:

https://github.com/AdoptOpenJDK/homebrew-openjdk/issues/106

For those who don't want to run through the details, here is a summary:

# To install JDK8
brew cask install adoptopenjdk/openjdk/adoptopenjdk8

# To be able to safely run 'brew cleanup'
brew untap adoptopenjdk/openjdk
brew untap caskroom/versions
brew cleanup

ToggleClass animate jQuery?

You can simply use CSS transitions, see this fiddle

.on {
color:#fff;
transition:all 1s;
}

.off{
color:#000;
transition:all 1s;
}

PL/pgSQL checking if a row exists

Simpler, shorter, faster: EXISTS.

IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
  -- do something
END IF;

The query planner can stop at the first row found - as opposed to count(), which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).

Improved with input from @a_horse_with_no_name in the comments below.

You could even use an empty SELECT list:

IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...

Since the SELECT list is not relevant to the outcome of EXISTS. Only the existence of at least one qualifying row matters.

Gradle does not find tools.jar

Found it. System property 'java.home' is not JAVA_HOME environment variable. JAVA_HOME points to the JDK, while java.home points to the JRE. See that page for more info.

Soo... My problem was that my startpoint was the jre folder (C:\jdk1.6.0_26\jre) and not the jdk folder (C:\jdk1.6.0_26) as I thought(tools.jar is on the C:\jdk1.6.0_26\lib folder ). The compile line in dependencies.gradle should be:

compile files("${System.properties['java.home']}/../lib/tools.jar")

What's the difference between ASCII and Unicode?

Beyond how UTF is a superset of ASCII, another good difference to know between ASCII and UTF is in terms of disk file encoding and data representation and storage in random memory. Programs know that given data should be understood as an ASCII or UTF string either by detecting special byte order mark codes at the start of the data, or by assuming from programmer intent that the data is text and then checking it for patterns that indicate it is in one text encoding or another.

Using the conventional prefix notation of 0x for hexadecimal data, basic good reference is that ASCII text starts with byte values 0x00 to 0x7F representing one of the possible ASCII character values. UTF text is normally indicated by starting with the bytes 0xEF 0xBB 0xBF for UTF8. For UTF16, start bytes 0xFE 0xFF, or 0xFF 0xFE are used, with the endian-ness order of the text bytes indicated by the order of the start bytes. The simple presence of byte values that are not in the ASCII range of possible byte values also indicates that data is probably UTF.

There are other byte order marks that use different codes to indicate data should be interpreted as text encoded in a certain encoding standard.

Using jquery to get element's position relative to viewport

Look into the Dimensions plugin, specifically scrollTop()/scrollLeft(). Information can be found at http://api.jquery.com/scrollTop.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.

Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.

Get absolute path to workspace directory in Jenkins Pipeline plugin

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}

How to escape % in String.Format?

To escape %, you will need to double it up: %%.

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".