Programs & Examples On #Automatic properties

What is the best way to give a C# auto-property an initial value?

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

Returning unique_ptr from functions

I think it's perfectly explained in item 25 of Scott Meyers' Effective Modern C++. Here's an excerpt:

The part of the Standard blessing the RVO goes on to say that if the conditions for the RVO are met, but compilers choose not to perform copy elision, the object being returned must be treated as an rvalue. In effect, the Standard requires that when the RVO is permitted, either copy elision takes place or std::move is implicitly applied to local objects being returned.

Here, RVO refers to return value optimization, and if the conditions for the RVO are met means returning the local object declared inside the function that you would expect to do the RVO, which is also nicely explained in item 25 of his book by referring to the standard (here the local object includes the temporary objects created by the return statement). The biggest take away from the excerpt is either copy elision takes place or std::move is implicitly applied to local objects being returned. Scott mentions in item 25 that std::move is implicitly applied when the compiler choose not to elide the copy and the programmer should not explicitly do so.

In your case, the code is clearly a candidate for RVO as it returns the local object p and the type of p is the same as the return type, which results in copy elision. And if the compiler chooses not to elide the copy, for whatever reason, std::move would've kicked in to line 1.

How can I use async/await at the top level?

Top-level await is a feature of the upcoming EcmaScript standard. Currently, you can start using it with TypeScript 3.8 (in RC version at this time).

How to Install TypeScript 3.8

You can start using TypeScript 3.8 by installing it from npm using the following command:

$ npm install typescript@rc

At this time, you need to add the rc tag to install the latest typescript 3.8 version.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

First you must test the query list size; here a example:

long count;
if (query.list().size() > 0)
    count=(long) criteria.list().get(0);   
else
    count=0;            
return count;

How to add property to a class dynamically?

It seems you could solve this problem much more simply with a namedtuple, since you know the entire list of fields ahead of time.

from collections import namedtuple

Foo = namedtuple('Foo', ['bar', 'quux'])

foo = Foo(bar=13, quux=74)
print foo.bar, foo.quux

foo2 = Foo()  # error

If you absolutely need to write your own setter, you'll have to do the metaprogramming at the class level; property() doesn't work on instances.

How to determine whether a year is a leap year?

If you don't want to import calendar and apply .isleap method you can try this:

def isleapyear(year):
    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        return True
    return False

Differences between Oracle JDK and OpenJDK

According to the oracle blog, Oracle JDK Releases for Java 11 and Later

Starting with Java 11, Oracle will provide JDK releases under the open source GNU General Public License v2, with the Classpath Exception (GPLv2+CPE), and under a commercial license for those using the Oracle JDK as part of an Oracle product or service, or who do not wish to use open source software. This combination of using an open source license and a commercial license replaces the historical “BCL” license, which had a combination of free and paid commercial terms.

Different builds will be provided for each license, but these builds are functionally identical aside from some cosmetic and packaging differences, described in detail below.

From the BCL to the GPL

The Binary Code License for Oracle Java SE technologies (“BCL”) has been the primary license for Oracle Java SE technologies for well over a decade. The BCL permits use without license fees under certain conditions. To simplify things going forward, Oracle started providing open source licensed OpenJDK builds as of Java 9, using the same license model as the Linux platform. If you are used to getting Oracle Java SE binaries for free, you can simply continue doing so with Oracle’s OpenJDK builds available at jdk.java.net. If you are used to getting Oracle Java SE binaries as part of a commercial product or service from Oracle, then you can continue to get Oracle JDK releases through My Oracle Support (MOS), and other locations.

Functionally identical and interchangeable...

Oracle’s BCL-licensed JDK historically contained “commercial features” that were not available in OpenJDK builds. As promised, however, over the past year Oracle has contributed these features to the OpenJDK Community, including:

From Java 11 forward, therefore, Oracle JDK builds and OpenJDK builds will be essentially identical.

...yet with some cosmetic and packaging differences

There do remain a small number of differences, some intentional and cosmetic, and some simply because more time to discuss with OpenJDK contributors is warranted.

  • Oracle JDK 11 emits a warning when using the -XX:+UnlockCommercialFeatures option, whereas in OpenJDK builds this option results in an error. This option was never part of OpenJDK and it would not make sense to add it now, since there are no commercial features in OpenJDK. This difference remains in order to make it easier for users of Oracle JDK 10 and earlier releases to migrate to Oracle JDK 11 and later.
  • Oracle JDK 11 can be configured to provide usage log data to the “Advanced Management Console” tool, which is a separate commercial Oracle product. We will work with other OpenJDK contributors to discuss how such usage data may be useful in OpenJDK in future releases, if at all. This difference remains primarily to provide a consistent experience to Oracle customers until such decisions are made.
  • The javac --release command behaves differently for the Java 9 and Java 10 targets, since in those releases the Oracle JDK contained some additional modules that were not part of corresponding OpenJDK releases:
    • javafx.base
    • javafx.controls
    • javafx.fxml
    • javafx.graphics
    • javafx.media
    • javafx.web
    • java.jnlp
    • jdk.jfr
    • jdk.management.cmm
    • jdk.management.jfr
    • jdk.management.resource
    • jdk.packager.services
    • jdk.snmp

This difference remains in order to provide a consistent experience for specific kinds of legacy use. These modules are either now available separately as part of OpenJFX, are now in both OpenJDK and the Oracle JDK because they were commercial features which Oracle contributed to OpenJDK (e.g., Flight Recorder), or were removed from Oracle JDK 11 (e.g., JNLP).

  • The output of the java --version and java -fullversion commands will distinguish Oracle JDK builds from OpenJDK builds, so that support teams can diagnose any issues that may exist. Specifically, running java --version with an Oracle JDK 11 build results in:

java 11 2018-09-25

Java(TM) SE Runtime Environment 18.9 (build 11+28)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)

And for an OpenJDK 11 build:

openjdk version "11" 2018-09-25

OpenJDK Runtime Environment 18.9 (build 11+28)

OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)

  • The Oracle JDK has always required third party cryptographic providers to be signed by a known certificate. The cryptography framework in OpenJDK has an open cryptographic interface, meaning it does not restrict which providers can be used. Oracle JDK 11 will continue to require a valid signature, and Oracle OpenJDK builds will continue to allow the use of either a valid signature or unsigned third party crypto provider.
  • Oracle JDK 11 will continue to include installers, branding and JRE packaging for an experience consistent with legacy desktop uses. Oracle OpenJDK builds are currently available as zip and tar.gz files, while alternative distribution formats are being considered.

How can I pass a parameter to a setTimeout() callback?

In modern browsers, the "setTimeout" receives a third parameter that is sent as parameter to the internal function at the end of the timer.

Example:

_x000D_
_x000D_
var hello = "Hello World";_x000D_
setTimeout(alert, 1000, hello);
_x000D_
_x000D_
_x000D_

More details:

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

Negate if condition in bash script

You can choose:

if [[ $? -ne 0 ]]; then       # -ne: not equal

if ! [[ $? -eq 0 ]]; then     # -eq: equal

if [[ ! $? -eq 0 ]]; then

! inverts the return of the following expression, respectively.

Nullable property to entity field, Entity Framework through Code First

The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.

Where does Console.WriteLine go in ASP.NET?

If you are using IIS Express and launch it via a command prompt, it will leave the DOS window open, and you will see Console.Write statements there.

So for example get a command window open and type:

"C:\Program Files (x86)\IIS Express\iisexpress" /path:C:\Projects\Website1 /port:1655

This assumes you have a website directory at C:\Projects\Website1. It will start IIS Express and serve the pages in your website directory. It will leave the command windows open, and you will see output information there. Let's say you had a file there, default.aspx, with this code in it:

<%@ Page Language="C#" %>
<html>
<body>
    <form id="form1" runat="server">
    Hello!

    <% for(int i = 0; i < 6; i++) %>
       <% { Console.WriteLine(i.ToString()); }%>

    </form>
</body>
</html>

Arrange your browser and command windows so you can see them both on the screen. Now type into your browser: http://localhost:1655/. You will see Hello! on the webpage, but in the command window you will see something like

Request started: "GET" http://localhost:1655/
0
1
2
3
4
5
Request ended: http://localhost:1655/default.aspx with HTTP status 200.0

I made it simple by having the code in a code block in the markup, but any console statements in your code-behind or anywhere else in your code will show here as well.

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

How to wrap text of HTML button with fixed width?

You can force it (browser permitting, I imagine) by inserting line breaks in the HTML source, like this:

<INPUT value="Line 1
Line 2">

Of course working out where to place the line breaks is not necessarily trivial...

If you can use an HTML <BUTTON> instead of an <INPUT>, such that the button label is the element's content rather than its value attribute, placing that content inside a <SPAN> with a width attribute that is a few pixels narrower than that of the button seems to do the trick (even in IE6 :-).

git pull while not in a git directory

You can write a script like this:

cd /X/Y
git pull

You can name it something like gitpull.
If you'd rather have it do arbitrary directories instead of /X/Y:

cd $1
git pull

Then you can call it with gitpull /X/Z
Lastly, you can try finding repositories. I have a ~/git folder which contains repositories, and you can use this to do a pull on all of them.

g=`find /X -name .git`
for repo in ${g[@]}
do
    cd ${repo}
    cd ..
    git pull
done

Remove leading zeros from a number in Javascript

We can use four methods for this conversion

  1. parseInt with radix 10
  2. Number Constructor
  3. Unary Plus Operator
  4. Using mathematical functions (subtraction)

_x000D_
_x000D_
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
_x000D_
_x000D_


Update(based on comments): Why doesn't this work on "large numbers"?

For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER).

_x000D_
_x000D_
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
_x000D_
_x000D_

Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods

_x000D_
_x000D_
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
_x000D_
_x000D_

All results will be incorrect.

That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means all operation performed with the assumption that the stringcan be converted to number type fails.

For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere.

The conversion code will be like this.

const numString = '099999999999999999999';
const number = BigInt(numString);

P.S: Why radix is important for parseInt?

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal)
  • If the input string begins with any other value, the radix is 10 (decimal)

Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.

For this reason, always specify a radix when using parseInt

How to change DataTable columns order

This is based off of "default locale"'s answer but it will remove invalid column names prior to setting ordinal. This is because if you accidentally send an invalid column name then it would fail and if you put a check to prevent it from failing then the index would be wrong since it would skip indices wherever an invalid column name was passed in.

public static class DataTableExtensions
{
    /// <summary>
    /// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
    /// </summary>
    /// <param name="table"></param>
    /// <param name="columnNames"></param>
    /// <remarks> http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order</remarks>
    public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
    {
        List<string> listColNames = columnNames.ToList();

        //Remove invalid column names.
        foreach (string colName in columnNames)
        {
            if (!dtbl.Columns.Contains(colName))
            {
                listColNames.Remove(colName);
            }
        }

        foreach (string colName in listColNames)
        {
            dtbl.Columns[colName].SetOrdinal(listColNames.IndexOf(colName));
        }
}

Get pixel's RGB using PIL

Not PIL, but imageio.imread might still be interesting:

import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So the pixel at position (x, y) is

color = tuple(im[y][x])
r, g, b = color

Outdated

scipy.misc.imread is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)

Linux - Install redis-cli only

In my case, I have to run some more steps to build it on RedHat or Centos.

# get system libraries
sudo yum install -y gcc wget

# get stable version and untar it
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable

# build dependencies too!
cd deps
make hiredis jemalloc linenoise lua geohash-int
cd ..

# compile it
make

# make it globally accesible
sudo cp src/redis-cli /usr/bin/

JSON and XML comparison

The XML (extensible Markup Language) is used often XHR because this is a standard broadcasting language, what can be used by any programming language, and supported both server and client side, so this is the most flexible solution. The XML can be separated for more parts so a specified group can develop the part of the program, without affecting the other parts. The XML format can also be determined by the XML DTD or XML Schema (XSL) and can be tested.

The JSON a data-exchange format which is getting more popular as the JavaScript applications possible format. Basically this is an object notation array. JSON has a very simple syntax so can be easily learned. And also the JavaScript support parsing JSON with the eval function. On the other hand, the eval function has got negatives. For example, the program can be very slow parsing JSON and because of security the eval can be very risky. This not mean that the JSON is not good, just we have to be more careful.

My suggestion is that you should use JSON for applications with light data-exchange, like games. Because you don't have to really care about the data-processing, this is very simple and fast.

The XML is best for the bigger websites, for example shopping sites or something like this. The XML can be more secure and clear. You can create basic data-struct and schema to easily test the correction and separate it into parts easily.

I suggest you use XML because of the speed and the security, but JSON for lightweight stuff.

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

In-memory size of a Python structure

Try memory profiler. memory profiler

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

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

You can get columns number from ResultSetMetaData:

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

int columnsNumber = rsmd.getColumnCount();

Remove unwanted parts from strings in a column

i'd use the pandas replace function, very simple and powerful as you can use regex. Below i'm using the regex \D to remove any non-digit characters but obviously you could get quite creative with regex.

data['result'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

If you are using rails, you can use #present?

require 'rails'

nil.present?  # ==> false (Works on nil)
''.present?    # ==> false (Works on strings)
'  '.present?  # ==> false (Works on blank strings)
[].present?    # ==> false(Works on arrays)
false.present? # ==> false (Works on boolean)

So, conversely to check for nil or zero length use !present?

!(nil.present?)  # ==> true
!(''.present?)    # ==> true
!('  '.present?)  # ==> true
!([].present?)    # ==> true
!(false.present?) # ==> true

Drop all tables command

I don't think you can drop all tables in one hit but you can do the following to get the commands:

select 'drop table ' || name || ';' from sqlite_master
    where type = 'table';

The output of this is a script that will drop the tables for you. For indexes, just replace table with index.

You can use other clauses in the where section to limit which tables or indexes are selected (such as "and name glob 'pax_*'" for those starting with "pax_").

You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.

If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see why it wouldn't work.

kill -3 to get java thread dump

Steps that you should follow if you want the thread dump of your StandAlone Java Process

Step 1: Get the Process ID for the shell script calling the java program

linux$ ps -aef | grep "runABCD"

user1  **8535**  4369   0   Mar 25 ?           0:00 /bin/csh /home/user1/runABCD.sh

user1 17796 17372   0 08:15:41 pts/49      0:00 grep runABCD

Step 2: Get the Process ID for the Child which was Invoked by the runABCD. Use the above PID to get the childs.

linux$ ps -aef | grep **8535**

user1  **8536**  8535   0   Mar 25 ?         126:38 /apps/java/jdk/sun4/SunOS5/1.6.0_16/bin/java -cp /home/user1/XYZServer

user1  8535  4369   0   Mar 25 ?           0:00 /bin/csh /home/user1/runABCD.sh

user1 17977 17372   0 08:15:49 pts/49      0:00 grep 8535

Step 3: Get the JSTACK for the particular process. Get the Process id of your XYSServer process. i.e. 8536

linux$ jstack **8536** > threadDump.log

How to check if a table contains an element in Lua?

I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think that more accurate is this syntax:

SELECT CONVERT(CHAR(10), GETDATE(), 103)

I add SELECT and GETDATE() for instant testing purposes :)

How to create a inner border for a box in html?

Take a look at this , we can simply do this with outline-offset property

Output image look like

enter image description here

_x000D_
_x000D_
.black_box {_x000D_
    width:500px;_x000D_
    height:200px;_x000D_
    background:#000;_x000D_
    float:left;_x000D_
    border:2px solid #000;_x000D_
    outline: 1px dashed #fff;_x000D_
    outline-offset: -10px;_x000D_
}
_x000D_
<div class="black_box"></div>
_x000D_
_x000D_
_x000D_

Setting Spring Profile variable

There are at least two ways to do that:

  1. defining context param in web.xml – that breaks "one package for all environments" statement. I don't recommend that

  2. defining system property -Dspring.profiles.active=your-active-profile

I believe that defining system property is a much better approach. So how to define system property for Tomcat? On the internet I could find a lot of advice like "modify catalina.sh" because you will not find any configuration file for doing stuff like that. Modifying catalina.sh is a dirty unmaintainable solution. There is a better way to do that.

Just create file setenv.sh in Tomcat's bin directory with content:

JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=dev"

and it will be loaded automatically during running catalina.sh start or run.

Here is a blog describing the above solution.

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

How do I quickly rename a MySQL database (change schema name)?

The simplest method is to use HeidiSQL software. It's free and open source. It runs on Windows and on any Linux with Wine (run Windows applications on Linux, BSD, Solaris and Mac OS X).

To download HeidiSQL, goto http://www.heidisql.com/download.php.

To download Wine, goto http://www.winehq.org/.

To rename a database in HeidiSQL, just right click on the database name and select 'Edit'. Then enter a new name and press 'OK'.

It is so simple.

regex with space and letters only?

Try this demo please: http://jsfiddle.net/sgpw2/

Thanks Jan for spaces \s rest there is some good detail in this link:

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI

Hope it fits your need :)

code

 $(function() {

    $("#field").bind("keyup", function(event) {
        var regex = /^[a-zA-Z\s]+$/;
        if (regex.test($("#field").val())) {
            $('.validation').html('valid');
        } else {
            $('.validation').html("FAIL regex");
        }
    });
});?

YouTube iframe API: how do I control an iframe player that's already in the HTML?

My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.

$(function() {
    callPlayer($('#iframe')[0], 'unMute');
});

function callPlayer(iframe, func, args) {
    if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
        iframe.contentWindow.postMessage( JSON.stringify({
            'event': 'command',
            'func': func,
            'args': args || []
        } ), '*');
    }
}

Exit from app when click button in android phonegap?

sorry i can't reply in comment. just FYI, these codes

if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
  navigator.device.exitApp();
}
else {
          window.close();
}

i confirm doesn't work. i use phonegap 6.0.5 and cordova 6.2.0

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

MySql Error: 1364 Field 'display_name' doesn't have default value

Also, I had this issue using Laravel, but fixed by changing my database schema to allow "null" inputs on a table where I plan to collect the information from separate forms:

public function up()
{

    Schema::create('trip_table', function (Blueprint $table) {
        $table->increments('trip_id')->unsigned();
        $table->time('est_start');
        $table->time('est_end');
        $table->time('act_start')->nullable();
        $table->time('act_end')->nullable();
        $table->date('Trip_Date');
        $table->integer('Starting_Miles')->nullable();
        $table->integer('Ending_Miles')->nullable();
        $table->string('Bus_id')->nullable();
        $table->string('Event');
        $table->string('Desc')->nullable();
        $table->string('Destination');
        $table->string('Departure_location');
        $table->text('Drivers_Comment')->nullable();
        $table->string('Requester')->nullable();
        $table->integer('driver_id')->nullable();
        $table->timestamps();
    });

}

The ->nullable(); Added to the end. This is using Laravel. Hope this helps someone, thanks!

Send JSON data from Javascript to PHP?

I've gotten lots of information here so I wanted to post a solution I discovered.

The problem: Getting JSON data from Javascript on the browser, to the server, and having PHP successfully parse it.

Environment: Javascript in a browser (Firefox) on Windows. LAMP server as remote server: PHP 5.3.2 on Ubuntu.

What works (version 1):
1) JSON is just text. Text in a certain format, but just a text string.

2) In Javascript, var str_json = JSON.stringify(myObject) gives me the JSON string.

3) I use the AJAX XMLHttpRequest object in Javascript to send data to the server:

request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]

4) On the server, PHP code to read the JSON string:

$str_json = file_get_contents('php://input');

This reads the raw POST data. $str_json now contains the exact JSON string from the browser.

What works (version 2):
1) If I want to use the "application/x-www-form-urlencoded" request header, I need to create a standard POST string of "x=y&a=b[etc]" so that when PHP gets it, it can put it in the $_POST associative array. So, in Javascript in the browser:

var str_json = "json_string=" + (JSON.stringify(myObject))

PHP will now be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest as in version 1 above.

Displaying the contents of $_POST['json_string'] will display the JSON string. Using json_decode() on the $_POST array element with the json string will correctly decode that data and put it in an array/object.

The pitfall I ran into:
Initially, I tried to send the JSON string with the header of application/x-www-form-urlencoded and then tried to immediately read it out of the $_POST array in PHP. The $_POST array was always empty. That's because it is expecting data of the form yval=xval&[rinse_and_repeat]. It found no such data, only the JSON string, and it simply threw it away. I examined the request headers, and the POST data was being sent correctly.

Similarly, if I use the application/json header, I again cannot access the sent data via the $_POST array. If you want to use the application/json content-type header, then you must access the raw POST data in PHP, via php://input, not with $_POST.

References:
1) How to access POST data in PHP: How to access POST data in PHP?
2) Details on the application/json type, with some sample objects which can be converted to JSON strings and sent to the server: http://www.ietf.org/rfc/rfc4627.txt

CSS Vertical align does not work with float

Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.

However, this is how you can vertically align YOUR 3 divs:

.wrap{
    width: 500px;
    overflow:hidden;    
    background: pink;
}

.left {
    width: 150px;       
    margin-right: 10px;
    background: yellow;  
    display:inline-block;
    vertical-align: middle; 
}

.left2 {
    width: 150px;    
    margin-right: 10px;
    background: aqua; 
    display:inline-block;
    vertical-align: middle; 
}

.right{
    width: 150px;
    background: orange;
    display:inline-block;
    vertical-align: middle; 
}

Not sure why you needed both fixed width, display: inline-block and floating.

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

How to check for file lock?

Here's a variation of DixonD's code that adds number of seconds to wait for file to unlock, and try again:

public bool IsFileLocked(string filePath, int secondsToWait)
{
    bool isLocked = true;
    int i = 0;

    while (isLocked &&  ((i < secondsToWait) || (secondsToWait == 0)))
    {
        try
        {
            using (File.Open(filePath, FileMode.Open)) { }
            return false;
        }
        catch (IOException e)
        {
            var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
            isLocked = errorCode == 32 || errorCode == 33;
            i++;

            if (secondsToWait !=0)
                new System.Threading.ManualResetEvent(false).WaitOne(1000);
        }
    }

    return isLocked;
}


if (!IsFileLocked(file, 10))
{
    ...
}
else
{
    throw new Exception(...);
}

jsonify a SQLAlchemy result set in Flask

I had the same need, to serialize into json. Take a look at this question. It shows how to discover columns programmatically. So, from that I created the code below. It works for me, and I'll be using it in my web app. Happy coding!


def to_json(inst, cls):
    """
    Jsonify the sql alchemy query result.
    """
    convert = dict()
    # add your coversions for things like datetime's 
    # and what-not that aren't serializable.
    d = dict()
    for c in cls.__table__.columns:
        v = getattr(inst, c.name)
        if c.type in convert.keys() and v is not None:
            try:
                d[c.name] = convert[c.type](v)
            except:
                d[c.name] = "Error:  Failed to covert using ", str(convert[c.type])
        elif v is None:
            d[c.name] = str()
        else:
            d[c.name] = v
    return json.dumps(d)

class Person(base):
    __tablename__ = 'person'
    id = Column(Integer, Sequence('person_id_seq'), primary_key=True)
    first_name = Column(Text)
    last_name = Column(Text)
    email = Column(Text)

    @property
    def json(self):
        return to_json(self, self.__class__)

How to read a file from jar in Java?

If you want to read that file from inside your application use:

InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");

The path starts with "/", but that is not the path in your file-system, but in your classpath. So if your file is at the classpath "org.xml" and is called myxml.xml your path looks like "/org/xml/myxml.xml".

The InputStream reads the content of your file. You can wrap it into an Reader, if you want.

I hope that helps.

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

How to fix Cannot find module 'typescript' in Angular 4?

For me just running the below command is not enough (though a valid first step):

npm install -g typescript

The following command is what you need (I think deleting node_modules works too, but the below command is quicker)

npm link typescript

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

Copying Code from Inspect Element in Google Chrome

Click on the line or element you want to copy. Copy to clipboard. Paste.

The only tricky thing is if you click on a line, you get everything that line includes if it was folded. For example if you click on a div, and copy, you get everything that the div includes.

You can also get only what you want by Right Clicking, and select 'Edit as HTML'. This will make that section essentially text, with none of the folding activated. You can then select, copy and paste the relevant bits.

React Native fetch() Network Request Failed

For us it was because we were uploading a file and the RN filePicker did not give the proper mime type. It just gave us 'image' as the type. We needed to change it to 'image/jpg' to get the fetch to work.

form.append(uploadFileName, {
  uri : localImage.full,
  type: 'image/jpeg',
  name: uploadFileName
 })

round a single column in pandas

Use the pandas.DataFrame.round() method like this:

df = df.round({'value1': 0})

Any columns not included will be left as is.

OpenCV get pixel channel value from Mat image

The below code works for me, for both accessing and changing a pixel value.

For accessing pixel's channel value :

for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            uchar col = intensity.val[k]; 
        }   
    }
}

For changing a pixel value of a channel :

uchar pixValue;
for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b &intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            // calculate pixValue
            intensity.val[k] = pixValue;
        }
     }
}

`

Source : Accessing pixel value

How to trigger click on page load?

$(function(){

    $(selector).click();

});

Efficient way to remove ALL whitespace from String?

Here is a simple linear alternative to the RegEx solution. I am not sure which is faster; you'd have to benchmark it.

static string RemoveWhitespace(string input)
{
    StringBuilder output = new StringBuilder(input.Length);

    for (int index = 0; index < input.Length; index++)
    {
        if (!Char.IsWhiteSpace(input, index))
        {
            output.Append(input[index]);
        }
    }
    return output.ToString();
}

How to return the current timestamp with Moment.js?

Here you are assigning an instance of momentjs to CurrentDate:

var CurrentDate = moment();

Here just a string, the result from default formatting of a momentjs instance:

var CurrentDate = moment().format();

And here the number of seconds since january of... well, unix timestamp:

var CurrentDate = moment().unix();

And here another string as ISO 8601 (What's the difference between ISO 8601 and RFC 3339 Date Formats?):

var CurrentDate = moment().toISOString();

And this can be done too:

var a = moment();
var b = moment(a.toISOString());

console.log(a.isSame(b)); // true

pass JSON to HTTP POST Request

you can pass the json object as the body(third argument) of the fetch request.

How to convert a byte array to its numeric value (Java)?

Complete java converter code for all primitive types to/from arrays http://www.daniweb.com/code/snippet216874.html

How to install MySQLdb package? (ImportError: No module named setuptools)

This was sort of tricky for me too, I did the following which worked pretty well.

  • Download the appropriate Python .egg for setuptools (ie, for Python 2.6, you can get it here. Grab the correct one from the PyPI site here.)
  • chmod the egg to be executable: chmod a+x [egg] (ie, for Python 2.6, chmod a+x setuptools-0.6c9-py2.6.egg)
  • Run ./[egg] (ie, for Python 2.6, ./setuptools-0.6c9-py2.6.egg)

Not sure if you'll need to use sudo if you're just installing it for you current user. You'd definitely need it to install it for all users.

Executing a shell script from a PHP script

I would have a directory somewhere called scripts under the WWW folder so that it's not reachable from the web but is reachable by PHP.

e.g. /var/www/scripts/testscript

Make sure the user/group for your testscript is the same as your webfiles. For instance if your client.php is owned by apache:apache, change the bash script to the same user/group using chown. You can find out what your client.php and web files are owned by doing ls -al.

Then run

<?php
      $message=shell_exec("/var/www/scripts/testscript 2>&1");
      print_r($message);
    ?>  

EDIT:

If you really want to run a file as root from a webserver you can try this binary wrapper below. Check out this solution for the same thing you want to do.

Execute root commands via PHP

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Try this with fixed length.

select right('000000'+'123',5)

select REPLICATE('0', 5 - LEN(123)) + '123'

How to step through Python code to help debug issues?

If you come from Java/C# background I guess your best bet would be to use Eclipse with Pydev. This gives you a fully functional IDE with debugger built in. I use it with django as well.

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

$watch an object

Try this:

function MyController($scope) {
    $scope.form = {
        name: 'my name',
        surname: 'surname'
    }

    function track(newValue, oldValue, scope) {
        console.log('changed');
    };

    $scope.$watch('form.name', track);
}

How to create a blank/empty column with SELECT query in oracle?

I guess you will get ORA-01741: illegal zero-length identifier if you use the following

SELECT "" AS Contact  FROM Customers;

And if you use the following 2 statements, you will be getting the same null value populated in the column.

SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;

Align div right in Bootstrap 3

The class pull-right is still there in Bootstrap 3 See the 'helper classes' here

pull-right is defined by

.pull-right {
  float: right !important;
}

without more info on styles and content, it's difficult to say.

It definitely pulls right in this JSBIN when the page is wider than 990px - which is when the col-md styling kicks in, Bootstrap 3 being mobile first and all.

Bootstrap 4

Note that for Bootstrap 4 .pull-right has been replaced with .float-right https://www.geeksforgeeks.org/pull-left-and-pull-right-classes-in-bootstrap-4/#:~:text=pull%2Dright%20classes%20have%20been,based%20on%20the%20Bootstrap%20Grid.

Is there a function to make a copy of a PHP array to another?

In PHP arrays are assigned by copy, while objects are assigned by reference. This means that:

$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);

Will yield:

array(0) {
}

Whereas:

$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);

Yields:

object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

You could get confused by intricacies such as ArrayObject, which is an object that acts exactly like an array. Being an object however, it has reference semantics.

Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.

Inline elements shifting when made bold on hover

One line in jquery:

$('ul.nav li a').each(function(){
    $(this).parent().width($(this).width() + 4);
});

edit: While this can bring about the solution, one should mention that it does not work in conjunction with the code in the original post. "display:inline" has to be replaced with floating-parameters for a width-setting to be effective and that horizontal menu to work as intended.

Converting Milliseconds to Minutes and Seconds?

You can try proceeding this way:

Pass ms value from

Long ms = watch.getTime();

to

getDisplayValue(ms)

Kotlin implementation:

fun getDisplayValue(ms: Long): String {
        val duration = Duration.ofMillis(ms)
        val minutes = duration.toMinutes()
        val seconds = duration.minusMinutes(minutes).seconds

        return "${minutes}min ${seconds}sec"
}

Java implementation:

public String getDisplayValue(Long ms) {
        Duration duration = Duration.ofMillis(ms);
        Long minutes = duration.toMinutes();
        Long seconds = duration.minusMinutes(minutes).getSeconds();

        return minutes + "min " + seconds "sec"
}

Adding up BigDecimals using Streams

You can sum up the values of a BigDecimal stream using a reusable Collector named summingUp:

BigDecimal sum = bigDecimalStream.collect(summingUp());

The Collector can be implemented like this:

public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
    return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}

Local storage in Angular 2

Local Storage Set Item

Syntax:

  localStorage.setItem(key,value);
  localStorage.getItem(key);

Example:

  localStorage.setItem("name","Muthu");
  if(localStorage){   //it checks browser support local storage or not
    let Name=localStorage.getItem("name");
    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

also you can use

    localStorage.setItem("name", JSON.stringify("Muthu"));

Session Storage Set Item

Syntax:

  sessionStorage.setItem(key,value);
  sessionStorage.getItem(key);

Example:

  sessionStorage.setItem("name","Muthu");

  if(sessionStorage){ //it checks browser support session storage/not
    let Name=sessionStorage.getItem("name");

    if(Name!=null){  //  it checks values here or not to the variable
       //do some stuff here...
    }
  }

also you can use

   sessionStorage.setItem("name", JSON.stringify("Muthu"));

Store and Retrieve data easily

How to make a query with group_concat in sql server

Please run the below query, it doesn't requires STUFF and GROUP BY in your case:

Select
      A.maskid
    , A.maskname
    , A.schoolid
    , B.schoolname
    , CAST((
          SELECT  T.maskdetail+','
          FROM dbo.maskdetails T
          WHERE A.maskid = T.maskid
          FOR XML PATH(''))as varchar(max)) as maskdetail 
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid

Is Python faster and lighter than C++?

Source size is not really a sensible thing to measure. For example, the following shell script:

cat foobar

is much shorter than either its Python or C++ equivalents.

Possible reason for NGINX 499 error codes

In my case I got 499 when the client's API closed the connection before it gets any response. Literally sent a POST and immediately close the connection. This is resolved by option:

proxy_ignore_client_abort on

Nginx doc

Sniffing/logging your own Android Bluetooth traffic

On Xiaomi Redmi Note 9s This configuration file can also be found /storage/emulated/0/MIUI/debug_log/common named as hci_snoop20210210214303.cfa hci_snoop20210211095126.cfa

With enabled 'Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log." '

I was used Total Commander for taking file from Internal storage

When is a language considered a scripting language?

A scripting language is a language that "scripts" other things to do stuff. The primary focus isn't primarily building your own apps so much as getting an existing app to act the way you want, e.g. JavaScript for browsers, VBA for MS Office.

How to Exit a Method without Exiting the Program?

The basic problem here is that you are mistaking System.Environment.Exit for return.

How to use the pass statement?

Suppose you are designing a new class with some methods that you don't want to implement, yet.

class MyClass(object):
    def meth_a(self):
        pass

    def meth_b(self):
        print "I'm meth_b"

If you were to leave out the pass, the code wouldn't run.

You would then get an:

IndentationError: expected an indented block

To summarize, the pass statement does nothing particular, but it can act as a placeholder, as demonstrated here.

Generating PDF files with JavaScript

Another interesting project is texlive.js.

It allows you to compile (La)TeX to PDF in the browser.

React - uncaught TypeError: Cannot read property 'setState' of undefined

You can also use:

<button onClick={()=>this.delta()}>+</button>

Or:

<button onClick={event=>this.delta(event)}>+</button>

If you are passing some params..

Dockerfile copy keep subdirectory structure

To merge a local directory into a directory within an image, do this. It will not delete files already present within the image. It will only add files that are present locally, overwriting the files in the image if a file of the same name already exists.

COPY ./files/. /files/

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

My issue was due to version conflict. I resolved this issue by excluding byte-buddy dependency from springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
</exclusions>
</dependency>

How to run TestNG from command line

I tried everything on this post but it turns out I was missing a jar file. Here's my solution:

Add guice-4.2.2.jar to your jar files if you are getting the following error. If you are using maven then add the following dependency.

<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.1.0</version>
</dependency>


Exception in thread "main" java.lang.NoClassDefFoundError: com/google/inject/Stage
        at org.testng.internal.Configuration.<init>(Configuration.java:33)
        at org.testng.TestNG.init(TestNG.java:216)
        at org.testng.TestNG.<init>(TestNG.java:200)
        at org.testng.TestNG.privateMain(TestNG.java:1312)
        at org.testng.TestNG.main(TestNG.java:1304)
Caused by: java.lang.ClassNotFoundException: com.google.inject.Stage
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        ... 5 more

Select option padding not working in chrome

Not padding but if your goal is to simply make it larger, you can increase the font-size. And using it with font-size-adjust reduces the font-size back to normal on select and not on options, so it ends up making the option larger.

Not sure if it works on all browsers, or will keep working in current.

Tested on Chrome 85 & Firefox 81.

screenshot (on Firefox)

_x000D_
_x000D_
select {
    font-size: 2em;
    font-size-adjust: 0.3;
}
_x000D_
<label>
  Select: <select>
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
          </select>
</label>
_x000D_
_x000D_
_x000D_

What is the preferred syntax for defining enums in JavaScript?

Here's what we all want:

function Enum(constantsList) {
    for (var i in constantsList) {
        this[constantsList[i]] = i;
    }
}

Now you can create your enums:

var YesNo = new Enum(['NO', 'YES']);
var Color = new Enum(['RED', 'GREEN', 'BLUE']);

By doing this, constants can be acessed in the usual way (YesNo.YES, Color.GREEN) and they get a sequential int value (NO = 0, YES = 1; RED = 0, GREEN = 1, BLUE = 2).

You can also add methods, by using Enum.prototype:

Enum.prototype.values = function() {
    return this.allValues;
    /* for the above to work, you'd need to do
            this.allValues = constantsList at the constructor */
};


Edit - small improvement - now with varargs: (unfortunately it doesn't work properly on IE :S... should stick with previous version then)

function Enum() {
    for (var i in arguments) {
        this[arguments[i]] = i;
    }
}

var YesNo = new Enum('NO', 'YES');
var Color = new Enum('RED', 'GREEN', 'BLUE');

Detect if a jQuery UI dialog box is open

If you want to check if the dialog's open on a particular element you can do this:

if ($('#elem').closest('.ui-dialog').is(':visible')) { 
  // do something
}

Or if you just want to check if the element itself is visible you can do:

if ($('#elem').is(':visible')) { 
  // do something
}

Or...

if ($('#elem:visible').length) { 
  // do something
}

How to do an update + join in PostgreSQL?

The UPDATE syntax is:

[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table [ [ AS ] alias ]
    SET { column = { expression | DEFAULT } |
          ( column [, ...] ) = ( { expression | DEFAULT } [, ...] ) } [, ...]
    [ FROM from_list ]
    [ WHERE condition | WHERE CURRENT OF cursor_name ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

In your case I think you want this:

UPDATE vehicles_vehicle AS v 
SET price = s.price_per_vehicle
FROM shipments_shipment AS s
WHERE v.shipment_id = s.id 

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

Sorry guys.. actually because of a csrf token was needed I was getting that issue. I have implemented spring security and csrf is enable. And through ajax call I need to pass the csrf token.

EnterKey to press button in VBA Userform

Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default property of the button to True (you can set this in the properties window, open by hitting F4)

That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel property of a button to True would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)


Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896

Check if space is in a string

Write if " " in word: instead of if " " in word == True:.

Explanation:

  • In Python, for example a < b < c is equivalent to (a < b) and (b < c).
  • The same holds for any chain of comparison operators, which include in!
  • Therefore ' ' in w == True is equivalent to (' ' in w) and (w == True) which is not what you want.

How to get attribute of element from Selenium?

You are probably looking for get_attribute(). An example is shown here as well

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

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

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

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

Could not load file or assembly ... The parameter is incorrect

I see lot of techies have posted about clearing temporary directories of ASP .Net run-time pertaining to each and every .Net framework hosted on your machine as in this answer. But I believe we should know the clear-cut logistics as to why we need to blindly clear all of temporary working directories of all .Net frameworks. According to me, it should not be the case.

My advice would be that you should try a pin pointed directory clearing approach to resolve this issue. How would you know which directory to clear?

  1. Go to IIS and right click on your website node in left navigation pane to open the context menu. In the context menu point to Manage Application -> Advanced Settings... to open the Advanced Settings window.
  2. Check the Application Pool your website is assigned to. In my case it is DefaultAppPool as shown below:

enter image description here

  1. Now go to Application Pools node in left navigation bar in the IIS. Now check that which .Net CLR Version is being run by your app pool. In my case it is v4.0 as shown below:

enter image description here

Since the CLR version being hosted by my app pool is v4.0, so I prcisely cleared only the temporary files in the folder pertaining to ASP .NET v4.0 only as below:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files

And that's it. My problem got resolved.

Lesson learnt: This is indicative of the fact that all the temporary files being used by your website aren't scattered across several directories but they are at once place being referred by your app pool. So you need to clear that specific folder only.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

change cursor to finger pointer

in css write

a.menu_links:hover{ cursor:pointer}

Install tkinter for Python

Use ntk for your desktop application, which work on top of tkinter to give you more functional and good looking ui in less codding.

install ntk by pip install ntk

proper Documentation in here: ntk.readthedocs.io

Happy codding.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

If other solution is not working like:

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

check for what are you returning from onCreateView of fragment is it single view or viewgroup? in my case I had viewpager on root of xml of fragment and I was returning viewpager, when i added viewgroup in layout i didnt updated that i have to return viewgroup now, not viewpager(view).

Java Try Catch Finally blocks without Catch

Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

How can I output a UTF-8 CSV in PHP that Excel will read properly?

As I investigated and I found that UTF-8 is not working well on MAC and Windows so I tried with Windows-1252 , it supports well on both of them but you must select type of encoding on ubuntu. Here is my code$valueToWrite = mb_convert_encoding($value, 'Windows-1252');

$response->headers->set('Content-Type', $mime . '; charset=Windows-1252');
    $response->headers->set('Pragma', 'public');
    $response->headers->set('Content-Endcoding','Windows-1252');
    $response->headers->set('Cache-Control', 'maxage=1');
    $response->headers->set('Content-Disposition', $dispositionHeader);
    echo "\xEF\xBB\xBF"; // UTF-8 BOM

Django: Get list of model fields?

So before I found this post, I successfully found this to work.

Model._meta.fields

It works equally as

Model._meta.get_fields()

I'm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.

for field in Model._meta.fields:
    print(field.name)

How to find the last day of the month from date?

t returns the number of days in the month of a given date (see the docs for date):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));

Getting execute permission to xp_cmdshell

For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.

  1. Enable the xp_cmdshell procedure

    Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*

  2. Create a login for the non-sysadmin user that has public access to the master database

    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*

  3. Grant EXEC permission on the xp_cmdshell stored procedure

    Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*

  4. Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

    Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*

It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.

Extract substring in Bash

If x is constant, the following parameter expansion performs substring extraction:

b=${a:12:5}

where 12 is the offset (zero-based) and 5 is the length

If the underscores around the digits are the only ones in the input, you can strip off the prefix and suffix (respectively) in two steps:

tmp=${a#*_}   # remove prefix ending in "_"
b=${tmp%_*}   # remove suffix starting with "_"

If there are other underscores, it's probably feasible anyway, albeit more tricky. If anyone knows how to perform both expansions in a single expression, I'd like to know too.

Both solutions presented are pure bash, with no process spawning involved, hence very fast.

Create a date time with month and day only, no year

How about creating a timer with the next date?

In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location.replace or location.href, etc.) to redirect to whatever URL you want. Of course, that depends on what HTML has already been sent down.

std::string to float or double

The Standard Library (C++11) offers the desired functionality with std::stod :

std::string  s  = "0.6"
std::wstring ws = "0.7"
double d  = std::stod(s);
double dw = std::stod(ws);

Generally for most other basic types, see <string>. There are some new features for C strings, too. See <stdlib.h>

How to programmatically move, copy and delete files and directories on SD?

Moving file using kotlin. App has to have permission to write a file in destination directory.

@Throws(FileNotFoundException::class, IOError::class)
private fun moveTo(source: File, dest: File, destDirectory: File? = null) {

    if (destDirectory?.exists() == false) {
        destDirectory.mkdir()
    }

    val fis = FileInputStream(source)
    val bufferLength = 1024
    val buffer = ByteArray(bufferLength)
    val fos = FileOutputStream(dest)
    val bos = BufferedOutputStream(fos, bufferLength)
    var read = fis.read(buffer, 0, read)
    while (read != -1) {
        bos.write(buffer, 0, read)
        read = fis.read(buffer) // if read value is -1, it escapes loop.
    }
    fis.close()
    bos.flush()
    bos.close()

    if (!source.delete()) {
        HLog.w(TAG, klass, "failed to delete ${source.name}")
    }
}

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

you have to add the missing local lang helper: for me the missing ones where de_LU de_LU.UTF-8 . Mongo 2.6.4 worked wihtout mongo 2.6.5 throw an error on this

Basic example for sharing text or image with UIActivityViewController in Swift

UIActivityViewController Example Project

Set up your storyboard with two buttons and hook them up to your view controller (see code below).

enter image description here

Add an image to your Assets.xcassets. I called mine "lion".

enter image description here

Code

import UIKit
class ViewController: UIViewController {

    // share text
    @IBAction func shareTextButton(_ sender: UIButton) {

        // text to share
        let text = "This is some text that I want to share."

        // set up activity view controller
        let textToShare = [ text ]
        let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)

    }

    // share image
    @IBAction func shareImageButton(_ sender: UIButton) {

        // image to share
        let image = UIImage(named: "Image")

        // set up activity view controller
        let imageToShare = [ image! ]
        let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)
    }

}

Result

Clicking "Share some text" gives result on the left and clicking "Share an image" gives the result on the right.

enter image description here

Notes

  • I retested this with iOS 11 and Swift 4. I had to run it a couple times in the simulator before it worked because it was timing out. This may be because my computer is slow.
  • If you wish to hide some of these choices, you can do that with excludedActivityTypes as shown in the code above.
  • Not including the popoverPresentationController?.sourceView line will cause your app to crash when run on an iPad.
  • This does not allow you to share text or images to other apps. You probably want UIDocumentInteractionController for that.

See also

Center image in div horizontally

A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:

.top_image img { margin:0 auto; }

More information and examples from W3C.

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

How do you clone a Git repository into a specific folder?

Here's how I would do it, but I have made an alias to do it for me.

$ cd ~Downloads/git; git clone https:git.foo/poo.git

There is probably a more elegant way of doing this, however I found this to be easiest for myself.

Here's the alias I created to speed things along. I made it for zsh, but it should work just fine for bash or any other shell like fish, xyzsh, fizsh, and so on.

Edit ~/.zshrc, /.bashrc, etc. with your favorite editor (mine is Leafpad, so I would write $ leafpad ~/.zshrc).

My personal preference, however, is to make a zsh plugin to keep track of all my aliases. You can create a personal plugin for oh-my-zsh by running these commands:

$ cd ~/.oh-my-zsh/
$ cd plugins/
$ mkdir your-aliases-folder-name; cd your-aliases-folder-name
     # In my case '~/.oh-my-zsh/plugins/ev-aliases/ev-aliases'
$ leafpad your-zsh-aliases.plugin.zsh
     # Again, in my case 'ev-aliases.plugin.zsh'

Afterwards, add these lines to your newly created blank alises.plugin file:

# Git aliases
alias gc="cd ~/Downloads/git; git clone "

(From here, replace your name with mine.)

Then, in order to get the aliases to work, they (along with zsh) have to be sourced-in (or whatever it's called). To do so, inside your custom plugin document add this:

## Ev's Aliases

#### Remember to re-source zsh after making any changes with these commands:

#### These commands should also work, assuming ev-aliases have already been sourced before:

allsource="source $ZSH/oh-my-zsh.sh ; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh; clear"
sourceall="source $ZSH/oh-my-zsh.sh ; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh"
#### 

####################################

# git aliases

alias gc="cd ~/Downloads/git; git clone "
# alias gc="git clone "
# alias gc="cd /your/git/folder/or/whatever; git clone "

####################################

Save your oh-my-zsh plugin, and run allsource. If that does not seem to work, simply run source $ZSH/oh-my-zsh.sh; source /home/ev/.oh-my-zsh/plugins/ev-aliases/ev-aliases.plugin.zsh. That will load the plugin source which will allow you to use allsource from now on.


I'm in the process of making a Git repository with all of my aliases. Please feel free to check them out here: Ev's dot-files. Please feel free to fork and improve upon them to suit your needs.

The type or namespace name 'DbContext' could not be found

I had the same problem..I have VS2010 express..

(Note: If you see this problem try checking references to EntityFramework.dll .. May be it is missing.)

The following resolved it for me.

I installed latest MVC 3 Tools Update
then I installed EntityFramework 4.1
or using NUGet ie. from with Visual Studio 2010 Express (Tools->Library Package Manager -> Add library Package reference -> Select Online -> EntityFramework)

Strangely that didnt work..So i had to manually add a reference to "EntityFramework.dll"
try doing a search for the dll ..may be here
"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\"

If you already have it..just add a '.net' reference.

Note: If you use NuGet ,it creates a folder "packages" along side your Solution directory. You will find the "EntityFramework.4.1.10331.0" folder inside it.Within "Libs" folder you will find "EntityFramework.dll" .
Add reference to it using Browse tab and select the above dll.

Snap for the same

Find the similarity metric between two strings

Note, difflib.SequenceMatcher only finds the longest contiguous matching subsequence, this is often not what is desired, for example:

>>> a1 = "Apple"
>>> a2 = "Appel"
>>> a1 *= 50
>>> a2 *= 50
>>> SequenceMatcher(None, a1, a2).ratio()
0.012  # very low
>>> SequenceMatcher(None, a1, a2).get_matching_blocks()
[Match(a=0, b=0, size=3), Match(a=250, b=250, size=0)]  # only the first block is recorded

Finding the similarity between two strings is closely related to the concept of pairwise sequence alignment in bioinformatics. There are many dedicated libraries for this including biopython. This example implements the Needleman Wunsch algorithm:

>>> from Bio.Align import PairwiseAligner
>>> aligner = PairwiseAligner()
>>> aligner.score(a1, a2)
200.0
>>> aligner.algorithm
'Needleman-Wunsch'

Using biopython or another bioinformatics package is more flexible than any part of the python standard library since many different scoring schemes and algorithms are available. Also, you can actually get the matching sequences to visualise what is happening:

>>> alignment = next(aligner.align(a1, a2))
>>> alignment.score
200.0
>>> print(alignment)
Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-
|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-
App-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-el

How to set up default schema name in JPA configuration?

I had to set the value in '' and ""

spring:
   jpa:
     properties:
       hibernate:
          default_schema: '"schema"'

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

Excel: last character/string match in a string

I'm a little late to the party, but maybe this could help. The link in the question had a similar formula, but mine uses the IF() statement to get rid of errors.

If you're not afraid of Ctrl+Shift+Enter, you can do pretty well with an array formula.

String (in cell A1): "one.two.three.four"

Formula:

{=MAX(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)))}  use Ctrl+Shift+Enter

Result: 14

First,

ROW($1:$99)

returns an array of integers from 1 to 99: {1,2,3,4,...,98,99}.

Next,

MID(A1,ROW($1:$99),1)

returns an array of 1-length strings found in the target string, then returns blank strings after the length of the target string is reached: {"o","n","e",".",..."u","r","","",""...}

Next,

IF(MID(I16,ROW($1:$99),1)=".",ROW($1:$99))

compares each item in the array to the string "." and returns either the index of the character in the string or FALSE: {FALSE,FALSE,FALSE,4,FALSE,FALSE,FALSE,8,FALSE,FALSE,FALSE,FALSE,FALSE,14,FALSE,FALSE.....}

Last,

=MAX(IF(MID(I16,ROW($1:$99),1)=".",ROW($1:$99)))

returns the maximum value of the array: 14

Advantages of this formula is that it is short, relatively easy to understand, and doesn't require any unique characters.

Disadvantages are the required use of Ctrl+Shift+Enter and the limitation on string length. This can be worked around with a variation shown below, but that variation uses the OFFSET() function which is a volatile (read: slow) function.

Not sure what the speed of this formula is vs. others.

Variations:

=MAX((MID(A1,ROW(OFFSET($A$1,,,LEN(A1))),1)=".")*ROW(OFFSET($A$1,,,LEN(A1)))) works the same way, but you don't have to worry about the length of the string

=SMALL(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)),2) determines the 2nd occurrence of the match

=LARGE(IF(MID(A1,ROW($1:$99),1)=".",ROW($1:$99)),2) determines the 2nd-to-last occurrence of the match

=MAX(IF(MID(I16,ROW($1:$99),2)=".t",ROW($1:$99))) matches a 2-character string **Make sure you change the last argument of the MID() function to the number of characters in the string you wish to match!

OS X: equivalent of Linux's wget

1) on your mac type

nano /usr/bin/wget

2) paste the following in

#!/bin/bash
curl -L $1 -o $2

3) close then make it executable

chmod 777 /usr/bin/wget

That's it.

How to convert JSON to CSV format and store in a variable

I wanted to riff off @Christian Landgren's answer above. I was confused why my CSV file only had 3 columns/headers. This was because the first element in my json only had 3 keys. So you need to be careful with the const header = Object.keys(json[0]) line. It's assuming that the first element in the array is representative. I had messy JSON that with some objects having more or less.

So I added an array.sort to this which will order the JSON by number of keys. So that way your CSV file will have the max number of columns.

This is also a function that you can use in your code. Just feed it JSON!

function convertJSONtocsv(json) {
    if (json.length === 0) {
        return;
    }

    json.sort(function(a,b){ 
       return Object.keys(b).length - Object.keys(a).length;
    });

    const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
    const header = Object.keys(json[0])
    let csv = json.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
    csv.unshift(header.join(','))
    csv = csv.join('\r\n')

    fs.writeFileSync('awesome.csv', csv)
}

Generate random number between two numbers in JavaScript

for big number.

var min_num = 900;
var max_num = 1000;
while(true){
    
    let num_random = Math.random()* max_num;
    console.log('input : '+num_random);
    if(num_random >= min_num){
        console.log(Math.floor(num_random));
       break; 
    } else {
        console.log(':::'+Math.floor(num_random));
    }
}

Show/hide image with JavaScript

HTML

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.display = "block";
}

CSS:

#theImage { display:none; }

HTML email with Javascript

I don't think that is possible in an email, nor should it be. There would be major security ramifications.

Style bottom Line in Android

Try next xml drawable code:

    <layer-list>
        <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
            <shape>
                <solid android:color="@android:color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="#fff" />
            </shape>
        </item>
    </layer-list>

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Showing all errors and warnings

Display errors could be turned off in the php.ini or your Apache configuration file.

You can turn it on in the script:

error_reporting(E_ALL);
ini_set('display_errors', '1');

You should see the same messages in the PHP error log.

Case objects vs Enumerations in Scala

Case objects already return their name for their toString methods, so passing it in separately is unnecessary. Here is a version similar to jho's (convenience methods omitted for brevity):

trait Enum[A] {
  trait Value { self: A => }
  val values: List[A]
}

sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
  case object EUR extends Currency
  case object GBP extends Currency
  val values = List(EUR, GBP)
}

Objects are lazy; by using vals instead we can drop the list but have to repeat the name:

trait Enum[A <: {def name: String}] {
  trait Value { self: A =>
    _values :+= this
  }
  private var _values = List.empty[A]
  def values = _values
}

sealed abstract class Currency(val name: String) extends Currency.Value
object Currency extends Enum[Currency] {
  val EUR = new Currency("EUR") {}
  val GBP = new Currency("GBP") {}
}

If you don't mind some cheating, you can pre-load your enumeration values using the reflection API or something like Google Reflections. Non-lazy case objects give you the cleanest syntax:

trait Enum[A] {
  trait Value { self: A =>
    _values :+= this
  }
  private var _values = List.empty[A]
  def values = _values
}

sealed trait Currency extends Currency.Value
object Currency extends Enum[Currency] {
  case object EUR extends Currency
  case object GBP extends Currency
}

Nice and clean, with all the advantages of case classes and Java enumerations. Personally, I define the enumeration values outside of the object to better match idiomatic Scala code:

object Currency extends Enum[Currency]
sealed trait Currency extends Currency.Value
case object EUR extends Currency
case object GBP extends Currency

How to export query result to csv in Oracle SQL Developer?

To take an export to your local system from sql developer.

Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv

    SPOOL "Path where you want to save the file"
    SELECT /*csv*/ * FROM TABLE_NAME;

VB.NET Connection string (Web.Config, App.Config)

I don't know if this still is an issue, but i prefere just to use the My.Settings in my code.

Visual Studio generates a simple class with functions for reading settings from the app.config file.

You can simply access it using My.Settings.ConnectionString.

    Using Context As New Data.Context.DataClasses()
        Context.Connection.ConnectionString = My.Settings.ConnectionString
    End Using

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);
    }

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1:

    cluster.name: mycluster
    node.name: "node1"
    node.master: true
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2:

    cluster.name: mycluster
    node.name: "node2"
    node.master: false
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

Git: How to return from 'detached HEAD' state

You may have made some new commits in the detached HEAD state. I believe if you do as other answers advise:

git checkout master
# or
git checkout -

then you may lose your commits!! Instead, you may want to do this:

# you are currently in detached HEAD state
git checkout -b commits-from-detached-head

and then merge commits-from-detached-head into whatever branch you want, so you don't lose the commits.

What does `m_` variable prefix mean?

This is typical programming practice for defining variables that are member variables. So when you're using them later, you don't need to see where they're defined to know their scope. This is also great if you already know the scope and you're using something like intelliSense, you can start with m_ and a list of all your member variables are shown. Part of Hungarian notation, see the part about scope in the examples here.

JMS Topic vs Queues

Queue is JMS managed object used for holding messages waiting for subscribers to consume. When all subscribers consumed the message , message will be removed from queue.

Topic is that all subscribers to a topic receive the same message when the message is published.

Find where java class is loaded from

Take a look at this similar question. Tool to discover same class..

I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap )

UILabel - auto-size label to fit text?

This is not as complicated as some of the other answers make it.

enter image description here

Pin the left and top edges

Just use auto layout to add constraints to pin the left and top sides of the label.

enter image description here

After that it will automatically resize.

Notes

  • Don't add constraints for the width and height. Labels have an intrinsic size based on their text content.
  • Thanks to this answer for help with this.
  • No need to set sizeToFit when using auto layout. My complete code for the example project is here:

    import UIKit
    class ViewController: UIViewController {
    
        @IBOutlet weak var myLabel: UILabel!
    
        @IBAction func changeTextButtonTapped(sender: UIButton) {
            myLabel.text = "my name is really long i want it to fit in this box"
        }
    }
    
  • If you want your label to line wrap then set the number of lines to 0 in IB and add myLabel.preferredMaxLayoutWidth = 150 // or whatever in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)

enter image description here

  • If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.

enter image description here

Checking if an Android application is running in the background

If you turn on developer settings "Don't keep actvities" - check only count of created activites is not enough. You must check also isSaveInstanceState. My custom method isApplicationRunning() check is android app is running:

Here my work code:

public class AppLifecycleService implements Application.ActivityLifecycleCallbacks {
    private int created;
    private boolean isSaveInstanceState;
    private static AppLifecycleService instance;

    private final static String TAG = AppLifecycleService.class.getName();

    public static AppLifecycleService getInstance() {
        if (instance == null) {
            instance = new AppLifecycleService();
        }
        return instance;
    }

    public static boolean isApplicationRunning() {
        boolean isApplicationRunning = true;
        if (getCountCreatedActvities() == 0 && !isSaveInstanceState()) {
            isApplicationRunning = false;
        }
        return isApplicationRunning;
    }

    public static boolean isSaveInstanceState() {
        return AppLifecycleService.getInstance().isSaveInstanceState;
    }

    public static int getCountCreatedActvities() {
        return AppLifecycleService.getInstance().created;
    }

    private AppLifecycleService() {
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        this.isSaveInstanceState = true;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        ++created;
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        --created;
    }

    @Override
    public void onActivityResumed(Activity activity) {   }

    @Override
    public void onActivityPaused(Activity activity) { }


    @Override
    public void onActivityStarted(Activity activity) { }

    @Override
    public void onActivityStopped(Activity activity) { }        

}

Delete all but the most recent X files in bash

The problems with the existing answers:

  • inability to handle filenames with embedded spaces or newlines.
    • in the case of solutions that invoke rm directly on an unquoted command substitution (rm `...`), there's an added risk of unintended globbing.
  • inability to distinguish between files and directories (i.e., if directories happened to be among the 5 most recently modified filesystem items, you'd effectively retain fewer than 5 files, and applying rm to directories will fail).

wnoise's answer addresses these issues, but the solution is GNU-specific (and quite complex).

Here's a pragmatic, POSIX-compliant solution that comes with only one caveat: it cannot handle filenames with embedded newlines - but I don't consider that a real-world concern for most people.

For the record, here's the explanation for why it's generally not a good idea to parse ls output: http://mywiki.wooledge.org/ParsingLs

ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {}

Note: This command operates in the current directory; to target a directory explicitly, use a subshell ((...)):
(cd /path/to && ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {})
The same applies analogously to the commands below.

The above is inefficient, because xargs has to invoke rm once for each filename.
Your platform's xargs may allow you to solve this problem:

If you have GNU xargs, use -d '\n', which makes xargs consider each input line a separate argument, yet passes as many arguments as will fit on a command line at once:

ls -tp | grep -v '/$' | tail -n +6 | xargs -d '\n' -r rm --

-r (--no-run-if-empty) ensures that rm is not invoked if there's no input.

If you have BSD xargs (including on macOS), you can use -0 to handle NUL-separated input, after first translating newlines to NUL (0x0) chars., which also passes (typically) all filenames at once (will also work with GNU xargs):

ls -tp | grep -v '/$' | tail -n +6 | tr '\n' '\0' | xargs -0 rm --

Explanation:

  • ls -tp prints the names of filesystem items sorted by how recently they were modified , in descending order (most recently modified items first) (-t), with directories printed with a trailing / to mark them as such (-p).

    • Note: It is the fact that ls -tp always outputs file / directory names only, not full paths, that necessitates the subshell approach mentioned above for targeting a directory other than the current one ((cd /path/to && ls -tp ...)).
  • grep -v '/$' then weeds out directories from the resulting listing, by omitting (-v) lines that have a trailing / (/$).

    • Caveat: Since a symlink that points to a directory is technically not itself a directory, such symlinks will not be excluded.
  • tail -n +6 skips the first 5 entries in the listing, in effect returning all but the 5 most recently modified files, if any.
    Note that in order to exclude N files, N+1 must be passed to tail -n +.

  • xargs -I {} rm -- {} (and its variations) then invokes on rm on all these files; if there are no matches at all, xargs won't do anything.

    • xargs -I {} rm -- {} defines placeholder {} that represents each input line as a whole, so rm is then invoked once for each input line, but with filenames with embedded spaces handled correctly.
    • -- in all cases ensures that any filenames that happen to start with - aren't mistaken for options by rm.

A variation on the original problem, in case the matching files need to be processed individually or collected in a shell array:

# One by one, in a shell loop (POSIX-compliant):
ls -tp | grep -v '/$' | tail -n +6 | while IFS= read -r f; do echo "$f"; done

# One by one, but using a Bash process substitution (<(...), 
# so that the variables inside the `while` loop remain in scope:
while IFS= read -r f; do echo "$f"; done < <(ls -tp | grep -v '/$' | tail -n +6)

# Collecting the matches in a Bash *array*:
IFS=$'\n' read -d '' -ra files  < <(ls -tp | grep -v '/$' | tail -n +6)
printf '%s\n' "${files[@]}" # print array elements

A hex viewer / editor plugin for Notepad++?

There is an old plugin called HEX Editor here.

According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.

How to install Jdk in centos

Here is something that might help. Use the root privileges. if you have .bin then simply add the execution permission to the bin file.

chmod a+x jdk*.bin

next step is to run the .bin file which is simply

./jdk*.bin in the location you want to install.

you are done.

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

As a general point when using a search engine to search for SQL codes make sure you put the sqlcode e.g. -302 in quote marks - like "-302" otherwise the search engine will exclude all search results including the text 302, since the - sign is used to exclude results.

Submit form on pressing Enter with AngularJS

If you only have one input you can use the form tag.

<form ng-submit="myFunc()" ...>

If you have more than one input, or don't want to use the form tag, or want to attach the enter-key functionality to a specific field, you can inline it to a specific input as follows:

<input ng-keyup="$event.keyCode == 13 && myFunc()" ...>

Returning JSON object as response in Spring Boot

you can also use a hashmap for this

@GetMapping
public HashMap<String, Object> get() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("results", somePOJO);
    return map;
}

Replace multiple characters in one replace call

Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).

// Test:
document.write(SafeHTML('<div>\n\
    x</div>'));

function SafeHTML(str)
    {
    const replacements = [
        {'&':'&amp;'},
        {'<':'&lt;'},
        {'>':'&gt;'},
        {'"':'&quot;'},
        {"'":'&apos;'},
        {'`':'&grave;'},
        {'\n':'<br>'},
        {' ':'&nbsp;'}
        ];
    return replaceManyStr(replacements,str);
    } // HTMLToSafeHTML

function replaceManyStr(replacements,str)
    {
    return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
    }

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

node.js require all files in a folder?

Using this function you can require a whole dir.

const GetAllModules = ( dirname ) => {
    if ( dirname ) {
        let dirItems = require( "fs" ).readdirSync( dirname );
        return dirItems.reduce( ( acc, value, index ) => {
            if ( PATH.extname( value ) == ".js" && value.toLowerCase() != "index.js" ) {
                let moduleName = value.replace( /.js/g, '' );
                acc[ moduleName ] = require( `${dirname}/${moduleName}` );
            }
            return acc;
        }, {} );
    }
}

// calling this function.

let dirModules = GetAllModules(__dirname);

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

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>

With this javascript:

var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

First you need to install cors by using below command :

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js)

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

With the new @SpringBootTest annotation, I took this answer and modified it to use profiles with a @SpringBootApplication configuration class. The @Profile annotation is necessary so that this class is only picked up during the specific integration tests that need this, as other test configurations do different component scanning.

Here is the configuration class:

@Profile("specific-profile")
@SpringBootApplication(scanBasePackages={"com.myco.package1", "com.myco.package2"})
public class SpecificTestConfig {

}

Then, the test class references this configuration class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpecificTestConfig.class })
@ActiveProfiles({"specific-profile"})
public class MyTest {

}

How to read a local text file?

Try creating two functions:

function getData(){       //this will read file and send information to other function
       var xmlhttp;

       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();               
       }           
       else {               
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
       }

       xmlhttp.onreadystatechange = function () {               
           if (xmlhttp.readyState == 4) {                   
             var lines = xmlhttp.responseText;    //*here we get all lines from text file*

             intoArray(lines);     *//here we call function with parameter "lines*"                   
           }               
       }

       xmlhttp.open("GET", "motsim1.txt", true);
       xmlhttp.send();    
}

function intoArray (lines) {
   // splitting all text data into array "\n" is splitting data from each new line
   //and saving each new line as each element*

   var lineArr = lines.split('\n'); 

   //just to check if it works output lineArr[index] as below
   document.write(lineArr[2]);         
   document.write(lineArr[3]);
}

Setting default values to null fields when mapping with Jackson

Only one proposed solution keeps the default-value when some-value:null was set explicitly (POJO readability is lost there and it's clumsy)

Here's how one can keep the default-value and never set it to null

@JsonProperty("some-value")
public String someValue = "default-value";

@JsonSetter("some-value")
public void setSomeValue(String s) {
    if (s != null) { 
        someValue = s; 
    }
}

Remove excess whitespace from within a string

If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . " And you expect the answer to be "this string have lots of space", you can use the following solution:

$strng = "this string                        have lots of                        space  .   ";

$strng = trim(preg_replace('/\s+/',' ', $strng));

echo $strng;

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Go: panic: runtime error: invalid memory address or nil pointer dereference

According to the docs for func (*Client) Do:

"An error is returned if caused by client policy (such as CheckRedirect), or if there was an HTTP protocol error. A non-2xx response doesn't cause an error.

When err is nil, resp always contains a non-nil resp.Body."

Then looking at this code:

res, err := client.Do(req)
defer res.Body.Close()

if err != nil {
    return nil, err
}

I'm guessing that err is not nil. You're accessing the .Close() method on res.Body before you check for the err.

The defer only defers the function call. The field and method are accessed immediately.


So instead, try checking the error immediately.

res, err := client.Do(req)

if err != nil {
    return nil, err
}
defer res.Body.Close()

What is the difference between join and merge in Pandas?

One of the difference is that merge is creating a new index, and join is keeping the left side index. It can have a big consequence on your later transformations if you wrongly assume that your index isn't changed with merge.

For example:

import pandas as pd

df1 = pd.DataFrame({'org_index': [101, 102, 103, 104],
                    'date': [201801, 201801, 201802, 201802],
                    'val': [1, 2, 3, 4]}, index=[101, 102, 103, 104])
df1

       date  org_index  val
101  201801        101    1
102  201801        102    2
103  201802        103    3
104  201802        104    4

-

df2 = pd.DataFrame({'date': [201801, 201802], 'dateval': ['A', 'B']}).set_index('date')
df2

       dateval
date          
201801       A
201802       B

-

df1.merge(df2, on='date')

     date  org_index  val dateval
0  201801        101    1       A
1  201801        102    2       A
2  201802        103    3       B
3  201802        104    4       B

-

df1.join(df2, on='date')
       date  org_index  val dateval
101  201801        101    1       A
102  201801        102    2       A
103  201802        103    3       B
104  201802        104    4       B

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

Long Press in JavaScript?

$(document).ready(function () {
    var longpress = false;

    $("button").on('click', function () {
        (longpress) ? alert("Long Press") : alert("Short Press");
    });

    var startTime, endTime;
    $("button").on('mousedown', function () {
        startTime = new Date().getTime();
    });

    $("button").on('mouseup', function () {
        endTime = new Date().getTime();
        longpress = (endTime - startTime < 500) ? false : true;
    });
});

DEMO

How to set the image from drawable dynamically in android?

Try this Dynamic code

String fnm = "cat"; //  this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));

In above code you will need Image-file-Name and Image-View object which both you are having.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Where can I get a list of Ansible pre-defined variables?

Some variables are not available on every host, e.g. ansible_domain and domain. If the situation needs to be debugged, I login to the server and issue:

user@server:~$ ansible -m setup localhost | grep domain
 [WARNING]: provided hosts list is empty, only localhost is available
    "ansible_domain": "prd.example.com",

Select subset of columns in data.table R

This seems an improvement:

> cols<-!(colnames(dt) %in% c("V1","V2","V3","V5"))
> new_dt<-subset(dt,,cols)
> cor(new_dt)
            V4          V6          V7          V8         V9         V10
V4   1.0000000  0.14141578 -0.44466832  0.23697216 -0.1020074  0.48171747
V6   0.1414158  1.00000000 -0.21356218 -0.08510977 -0.1884202 -0.22242274
V7  -0.4446683 -0.21356218  1.00000000 -0.02050846  0.3209454 -0.15021528
V8   0.2369722 -0.08510977 -0.02050846  1.00000000  0.4627034 -0.07020571
V9  -0.1020074 -0.18842023  0.32094540  0.46270335  1.0000000 -0.19224973
V10  0.4817175 -0.22242274 -0.15021528 -0.07020571 -0.1922497  1.00000000

This one is not quite as easy to grasp but might have use for situations there there were a need to specify columns by a numeric vector:

subset(dt, , !grepl(paste0("V", c(1:3,5),collapse="|"),colnames(dt) ))

What does the function then() mean in JavaScript?

Another example:

_x000D_
_x000D_
new Promise(function(ok) {
   ok( 
      /* myFunc1(param1, param2, ..) */
   )
}).then(function(){
     /* myFunc1 succeed */
     /* Launch something else */
     /* console.log(whateverparam1) */
     /* myFunc2(whateverparam1, otherparam, ..) */
}).then(function(){
     /* myFunc2 succeed */
     /* Launch something else */
     /* myFunc3(whatever38, ..) */
})
_x000D_
_x000D_
_x000D_

The same logic using arrow functions shorthand.

?? This can cause issues with multiple calls see comments!

The syntax of the first snippet using plain function is preferable here.

_x000D_
_x000D_
new Promise((ok) =>
   ok( 
      /* myFunc1(param1, param2, ..) */
)).then(() =>
     /* myFunc1 succeed */
     /* Launch something else */
     /* Only ONE call or statment can be made inside arrow functions */
     /* For example, using console.log here will break everything */
     /* myFunc2(whateverparam1, otherparam, ..) */
).then(() =>
     /* myFunc2 succeed */
     /* Launch something else */
     /* Only ONE call or statment can be made inside arrow functions */
     /* For example, using console.log here will break everything */
     /* myFunc3(whatever38, ..) */
)
_x000D_
_x000D_
_x000D_

Responding with a JSON object in Node.js (converting object/array to JSON string)

You have to use the JSON.stringify() function included with the V8 engine that node uses.

var objToJson = { ... };
response.write(JSON.stringify(objToJson));

Edit: As far as I know, IANA has officially registered a MIME type for JSON as application/json in RFC4627. It is also is listed in the Internet Media Type list here.

Run Excel Macro from Outside Excel Using VBScript From Command Line

If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:

Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here

oExcel.DisplayAlerts = False


For Each oFile In oFSO.GetFolder("C:\Location\").Files
    If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
        With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)



            oExcel.Run wb2.Name & "!modForm"


            For Each oSheet In .Worksheets



                oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6


            Next
            .Close False, , False
        End With
    End If



Next
oExcel.Quit
oShell.Popup "Conversion complete", 10

So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.

What does %>% mean in R

Use ?'%*%' to get the documentation.

%*% is matrix multiplication. For matrix multiplication, you need an m x n matrix times an n x p matrix.

Get current URL from IFRAME

I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:

    const iframeReference = document.getElementById("iframe_id");
    const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
    if (iframeUrl) {
        console.log("Voila: " + iframeUrl);
    } else {
        console.warn("iframe with id iframe_id not found");
    }

JS how to cache a variable

check out my js lib for caching: https://github.com/hoangnd25/cacheJS

My blog post: New way to cache your data with Javascript

Features:

  • Conveniently use array as key for saving cache
  • Support array and localStorage
  • Clear cache by context (clear all blog posts with authorId="abc")
  • No dependency

Basic usage:

Saving cache:

cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});

Retrieving cache:

cacheJS.get({blogId: 1,type: 'view'});

Flushing cache

cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});

cacheJS.removeByContext({author:'hoangnd'});

Switching provider

cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};

How do I check whether input string contains any spaces?

If you will use Regex, it already has a predefined character class "\S" for any non-whitespace character.

!str.matches("\\S+")

tells you if this is a string of at least one character where all characters are non-whitespace

How to call external url in jquery?

google the javascript same origin policy

in a nutshell, the url you are trying to use must have the same root and protocol. so http://yoursite.com cannot access https://yoursite.com or http://anothersite.com

is you absolutely MUST bypass this protection (which is at the browser level, as galimy pointed out), consider the ProxyPass module for your favorite web server.

Regex to split a CSV

Worked on this for a bit and came up with this solution:

(?:,|\n|^)("(?:(?:"")*[^"]*)*"|[^",\n]*|(?:\n|$))

Try it out here!

This solution handles "nice" CSV data like

"a","b",c,"d",e,f,,"g"

0: "a"
1: "b"
2: c
3: "d"
4: e
5: f
6:
7: "g"

and uglier things like

"""test"" one",test' two,"""test"" 'three'","""test 'four'"""

0: """test"" one"
1: test' two
2: """test"" 'three'"
3: """test 'four'"""

Here's an explanation of how it works:

(?:,|\n|^)      # all values must start at the beginning of the file,  
                #   the end of the previous line, or at a comma  
(               # single capture group for ease of use; CSV can be either...  
  "             # ...(A) a double quoted string, beginning with a double quote (")  
    (?:         #        character, containing any number (0+) of  
      (?:"")*   #          escaped double quotes (""), or  
      [^"]*     #          non-double quote characters  
    )*          #        in any order and any number of times  
  "             #        and ending with a double quote character  

  |             # ...or (B) a non-quoted value  

  [^",\n]*      # containing any number of characters which are not  
                # double quotes ("), commas (,), or newlines (\n)  

  |             # ...or (C) a single newline or end-of-file character,  
                #           used to capture empty values at the end of  
  (?:\n|$)      #           the file or at the ends of lines  
)

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

You don't need to downgrade you can:

Either disable undefined symbol diagnostics in the settings -- "intelephense.diagnostics.undefinedSymbols": false .

Or use an ide helper that adds stubs for laravel facades. See https://github.com/barryvdh/laravel-ide-helper

Storing and Retrieving ArrayList values from hashmap

The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:

map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);

According to Map.computeIfAbsent docs:

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null

The most idiomatic way to iterate a map of lists is using Map.forEach and Iterable.forEach:

map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));

Or, as shown in other answers, a traditional for loop:

for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
    String k = e.getKey();
    for (Integer v : e.getValue()) {
        /* use k and v here */
    }
}

API vs. Webservice

another example: google map api vs google direction api web service, while the former serves (delivers) javascript file to the site (which can then be used as an api to make new functions) , the later is a Rest web service delivering data (in json or xml format), which can be processed (but not used in an api sense).

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

For linux users: possible solution.

Build error due to "Failed to delete < any-file-or-folder >" will occur if there is by chance of only delete access provided to root user rather to normal-user.

Fix : type ll command to list file that cannot be deleted, if the file is given root access, change to normal user by :

sudo chown -R user-name:user-name filename

Later try for maven clean and build.

Setting a PHP $_SESSION['var'] using jQuery

in (backend.php) be sure to include include

session_start();

-Taylor http://www.hawkessolutions.com

Setting multiple attributes for an element at once with JavaScript

you can simply add a method (setAttributes, with "s" at the end) to "Element" prototype like:

Element.prototype.setAttributes = function(obj){
  for(var prop in obj) {
    this.setAttribute(prop, obj[prop])
  }
}

you can define it in one line:

Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }

and you can call it normally as you call the other methods. The attributes are given as an object:

elem.setAttributes({"src": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})

you can add an if statement to throw an error if the given argument is not an object.

How do I select child elements of any depth using XPath?

You're almost there. Simply use:

//form[@id='myform']//input[@type='submit']

The // shortcut can also be used inside an expression.

Python: Random numbers into a list

import random

a=[]
n=int(input("Enter number of elements:"))

for j in range(n):
       a.append(random.randint(1,20))

print('Randomised list is: ',a)

How does DHT in torrents work?

DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal

What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.

If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.

Integer.valueOf() vs. Integer.parseInt()

The difference between these two methods is:

  • parseXxx() returns the primitive type
  • valueOf() returns a wrapper object reference of the type.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Uncaught TypeError: Cannot read property 'value' of null

If in your HTML you have an input element with a name or id with a _ like e.g. first_name or more than one _ like e.g. student_first_name and you also have the Javascript code at the bottom of your Web Page and you are sure you are doing everything else right, then those dashes could be what is messing you up.

Having id or name for your input elements resembling the below

<input type="text" id="first_name" name="first_name">

or

<input type="text" id="student_first_name" name="student_first_name">

Then you try make a call like this below in your JavaScript code

var first_name = document.getElementById("first_name").value;

or

var student_first_name = document.getElementById("student_first_name").value;

You are certainly going to have an error like Uncaught TypeError: Cannot read property 'value' of null in Google Chrome and on Internet Explorer too. I did not get to test that with Firefox.

In my case I removed the dashes, in first_name and renamed it to firstname and from student_first_name to studentfirstname

At the end, I was able to resolve that error with my code now looking as follows for HTML and JavaScript.

HTML

<input type="text" id="firstname" name="firstname">

or

<input type="text" id="studentfirstname" name="studentfirstname">

Javascript

var firstname = document.getElementById("firstname").value;

or

var studentfirstname = document.getElementById("studentfirstname").value;

So if it is within your means to rename the HTML and JavaScript code with those dashes, it may help if that is what is ailing your piece of code. In my case that was what was bugging me.

Hope this helps someone stop pulling their hair like I was.

How to embed HTML into IPython output?

Expanding on @Harmon above, looks like you can combine the display and print statements together ... if you need. Or, maybe it's easier to just format your entire HTML as one string and then use display. Either way, nice feature.

display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))

Outputs something like this:


Hello, world!

Here's a link:

www.google.com

some more printed text ...

Paragraph text here ...


How to replace multiple substrings of a string?

In my case, I needed a simple replacing of unique keys with names, so I thought this up:

a = 'This is a test string.'
b = {'i': 'I', 's': 'S'}
for x,y in b.items():
    a = a.replace(x, y)
>>> a
'ThIS IS a teSt StrIng.'

Changing Font Size For UITableView Section Headers

Swift 2.0:

  1. Replace default section header with fully customisable UILabel.

Implement viewForHeaderInSection, like so:

  override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
    if sectionTitle == "" {
      return nil
    }

    let title: UILabel = UILabel()

    title.text = sectionTitle
    title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8)
    title.backgroundColor = UIColor.clearColor()
    title.font = UIFont.boldSystemFontOfSize(15)

    return title
  }
  1. Alter the default header (retains default).

Implement willDisplayHeaderView, like so:

  override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    if let view = view as? UITableViewHeaderFooterView {
      view.backgroundView?.backgroundColor = UIColor.blueColor()
      view.textLabel!.backgroundColor = UIColor.clearColor()
      view.textLabel!.textColor = UIColor.whiteColor()
      view.textLabel!.font = UIFont.boldSystemFontOfSize(15)
    }
  }

Remember: If you're using static cells, the first section header is padded higher than other section headers due to the top of the UITableView; to fix this:

Implement heightForHeaderInSection, like so:

  override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    return 30.0 // Or whatever height you want!
  }

PHP cURL custom headers

Here is one basic function:

/**
 * 
 * @param string $url
 * @param string|array $post_fields
 * @param array $headers
 * @return type
 */
function cUrlGetData($url, $post_fields = null, $headers = null) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($post_fields && !empty($post_fields)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    }
    if ($headers && !empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    return $data;
}

Usage example:

$url = "http://www.myurl.com";
$post_fields = 'postvars=val1&postvars2=val2';
$headers = ['Content-Type' => 'application/x-www-form-urlencoded', 'charset' => 'utf-8'];
$dat = cUrlGetData($url, $post_fields, $headers);

Java array assignment (multiple values)

On declaration you can do the following.

float[] values = {0.1f, 0.2f, 0.3f};

When the field is already defined, try this.

values = new float[] {0.1f, 0.2f, 0.3f};

Be aware that also the second version creates a new array. If values was the only reference to an already existing field, it becomes eligible for garbage collection.

Auto-Submit Form using JavaScript

You need to specify a frame, a target otherwise your script will vanish on first submit!

Change document.myForm with document.forms["myForm"]:

<form name="myForm" id="myForm" target="_myFrame" action="test.php" method="POST">
    <p>
        <input name="test" value="test" />
    </p>
    <p>
        <input type="submit" value="Submit" />
    </p>
</form>

<script type="text/javascript">
    window.onload=function(){
        var auto = setTimeout(function(){ autoRefresh(); }, 100);

        function submitform(){
          alert('test');
          document.forms["myForm"].submit();
        }

        function autoRefresh(){
           clearTimeout(auto);
           auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
        }
    }
</script>

Does Java have something like C#'s ref and out keywords?

Java passes parameters by value and doesn't have any mechanism to allow pass-by-reference. That means that whenever a parameter is passed, its value is copied into the stack frame handling the call.

The term value as I use it here needs a little clarification. In Java we have two kinds of variables - primitives and objects. A value of a primitive is the primitive itself, and the value of an object is its reference (and not the state of the object being referenced). Therefore, any change to the value inside the method will only change the copy of the value in the stack, and will not be seen by the caller. For example, there isn't any way to implement a real swap method, that receives two references and swaps them (not their content!).

Repeat a string in JavaScript a number of times

If you're not opposed to including a library in your project, lodash has a repeat function.

_.repeat('*', 3);
// ? '***

https://lodash.com/docs#repeat

How to use PHP OPCache?

I encountered this when setting up moodle. I added the following lines in the php.ini file.

zend_extension=C:\xampp\php\ext\php_opcache.dll

[opcache]
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 60

; Required for Moodle
opcache.use_cwd = 1
opcache.validate_timestamps = 1
opcache.save_comments = 1
opcache.enable_file_override = 0

; If something does not work in Moodle
;opcache.revalidate_path = 1 ; May fix problems with include paths
;opcache.mmap_base = 0x20000000 ; (Windows only) fix OPcache crashes with event id 487

; Experimental for Moodle 2.6 and later
;opcache.fast_shutdown = 1
;opcache.enable_cli = 1 ; Speeds up CLI cron
;opcache.load_comments = 0 ; May lower memory use, might not be compatible with add-ons and other apps

extension=C:\xampp\php\ext\php_intl.dll

[intl]
intl.default_locale = en_utf8
intl.error_level = E_WARNING

intl -> http://php.net/manual/en/book.intl.php

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can do something like this :

<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />

How to import and export components using React + ES6 + webpack?

There are two different ways of importing components in react and the recommended way is component way

  1. Library way(not recommended)
  2. Component way(recommended)

PFB detail explanation

Library way of importing

import { Button } from 'react-bootstrap';
import { FlatButton } from 'material-ui';

This is nice and handy but it does not only bundles Button and FlatButton (and their dependencies) but the whole libraries.

Component way of importing

One way to alleviate it is to try to only import or require what is needed, lets say the component way. Using the same example:

import Button from 'react-bootstrap/lib/Button';
import FlatButton from 'material-ui/lib/flat-button';

This will only bundle Button, FlatButton and their respective dependencies. But not the whole library. So I would try to get rid of all your library imports and use the component way instead.

If you are not using lot of components then it should reduce considerably the size of your bundled file.