Programs & Examples On #User environment

Laravel - Pass more than one variable to view

Came across a similar problem, but if you do not necessarily want to return a view with view file, you can do this:

return $view->with(compact('myVar1', 'myVar2', ..... , 'myLastVar'));

illegal character in path

try

"C:/Program Files (x86)/test software/myapp/demo.exe"

PHP output showing little black diamonds with a question mark

Just add these lines before headers.

Accurate format of .doc/docx files will be retrieved:

 if(ini_get('zlib.output_compression'))

   ini_set('zlib.output_compression', 'Off');
 ob_clean();

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

Why is a div with "display: table-cell;" not affected by margin?

You can use inner divs to set the margin.

<div style="display: table-cell;">
   <div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
  <div style="margin:5px;background-color: green;">1</div>
</div>

JS Fiddle

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

Change variable name in for loop using R

You could use assign, but using assign (or get) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.

  • with a list:

    A <- lapply (1 : 10, function (x) d + rnorm (3))
    
  • with a matrix:

    A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
    

Function to Calculate a CRC16 Checksum

Here follows a working code to calculate crc16 CCITT. I tested it and the results matched with those provided by http://www.lammertbies.nl/comm/info/crc-calculation.html.

unsigned short crc16(const unsigned char* data_p, unsigned char length){
    unsigned char x;
    unsigned short crc = 0xFFFF;

    while (length--){
        x = crc >> 8 ^ *data_p++;
        x ^= x>>4;
        crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
    }
    return crc;
}

What is the difference between match_parent and fill_parent?

Functionally no difference, Google just changed the name from fill_parent to match_parent, from API level 8 (Android 2.2). FILL_PARENT is still available for compatibility reason.

LayoutParams.FILL_PARENT and LayoutParams.MATCH_PARENT both have value -1. Not sure what tempted google to change from Fill Parent to Match Parent :)

Since most of the phones are >= Android 2.2 .. you should use Match Parent for future compatibility... not sure when they will discontinue the older Fill Parent constant!

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

pip install mysql-python fails with EnvironmentError: mysql_config not found

Sequence to be followed.

pip install mysqlclient
sudo apt-get install python3-dev libmysqlclient-dev
pip install configparser 
sudo cp /usr/lib/python3.6/configparser.py /usr/lib/python3.6/ConfigParser.py 

Then try to install the MYSQL-python again. That Worked for me

HTML anchor link - href and onclick both?

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

This error came to me when I configured (wrong) 3 Gb memory where there was none. IntelliJ does shows the real error message (Could not reserve enough space for object heap) in the Output frame. I was confused, and attracted by the message in the Event Log, which is to be ignored in this case.

Curl command line for consuming webServices?

Posting a string:

curl -d "String to post" "http://www.example.com/target"

Posting the contents of a file:

curl -d @soap.xml "http://www.example.com/target"

How to get the screen width and height in iOS?

Careful, [UIScreen mainScreen] contains status bar as well, if you want to retrieve the frame for your application (excluding status bar) you should use

+ (CGFloat) window_height   {
    return [UIScreen mainScreen].applicationFrame.size.height;
}

+ (CGFloat) window_width   {
    return [UIScreen mainScreen].applicationFrame.size.width;
}

How to convert buffered image to image and vice-versa?

BufferedImage is a subclass of Image. You don't need to do any conversion.

How to check python anaconda version installed on Windows 10 PC?

The folder containing your Anaconda installation contains a subfolder called conda-meta with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json.

My file is called anaconda-5.0.1-py27hdb50712_1.json, and at the bottom is more info about the version:

"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe", 
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" }, 
"name": "anaconda", 
"platform": "win", 
"subdir": "win-64", 
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2", 
"version": "5.0.1"

(Slightly edited for brevity.)

The output from conda -V is the conda version.

set up device for development (???????????? no permissions)

Try instead of GROUP="plugdev" use the main group of your user.

Running the new Intel emulator for Android

Here there are two issues we have to concentrate on:

  1. HAX device failed to open,

    For this problem, you have to run the HAX device setup file from the HAX addon folder. Follow Speed Up Android Emulator to know clearly how.

  2. If you created the AVD through AVD manager then you can change the RAM size in AVD Manager and device edit option.

If you created the AVD through command line, then you should start the AVD from command line will work,

emulator -memory 512 -avd gtv_avd

How to print without newline or space?

You will notice that all the above answers are correct. But I wanted to make a shortcut to always writing the " end='' " parameter in the end.

You could define a function like

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

It would accept all the number of parameters. Even it will accept all the other parameters like file, flush ,etc and with the same name.

HTML CSS Button Positioning

[type=submit]{
    margin-left: 121px;
    margin-top: 19px;
    width: 84px;
    height: 40px;   
    font-size:14px;
    font-weight:700;
}

what does mysql_real_escape_string() really do?

The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are

\x00, \n, \r, \, ', " and \x1a.

This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.

Determine the size of an InputStream

I just wanted to add, Apache Commons IO has stream support utilities to perform the copy. (Btw, what do you mean by placing the file into an inputstream? Can you show us your code?)

Edit:

Okay, what do you want to do with the contents of the item? There is an item.get() which returns the entire thing in a byte array.

Edit2

item.getSize() will return the uploaded file size.

How to check the version of scipy

In [95]: import scipy

In [96]: scipy.__version__
Out[96]: '0.12.0'

In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version

In [105]: scipy.version.full_version
Out[105]: '0.12.0'

In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'

In [107]: scipy.version.release
Out[107]: True

In [108]: scipy.version.short_version
Out[108]: '0.12.0'

In [109]: scipy.version.version
Out[109]: '0.12.0'

See SciPy doveloper documentation for reference.

Change Row background color based on cell value DataTable

Since datatables v1.10.18, you should specify the column key instead of index, it should be like this:

rowCallback: function(row, data, index){
            if(data["column_key"] == "ValueHere"){
                $('td', row).css('background-color', 'blue');
            }
        }

Set markers for individual points on a line in Matplotlib

Specify the keyword args linestyle and/or marker in your call to plot.

For example, using a dashed line and blue circle markers:

plt.plot(range(10), linestyle='--', marker='o', color='b')

A shortcut call for the same thing:

plt.plot(range(10), '--bo')

example1

Here is a list of the possible line and marker styles:

================    ===============================
character           description
================    ===============================
   -                solid line style
   --               dashed line style
   -.               dash-dot line style
   :                dotted line style
   .                point marker
   ,                pixel marker
   o                circle marker
   v                triangle_down marker
   ^                triangle_up marker
   <                triangle_left marker
   >                triangle_right marker
   1                tri_down marker
   2                tri_up marker
   3                tri_left marker
   4                tri_right marker
   s                square marker
   p                pentagon marker
   *                star marker
   h                hexagon1 marker
   H                hexagon2 marker
   +                plus marker
   x                x marker
   D                diamond marker
   d                thin_diamond marker
   |                vline marker
   _                hline marker
================    ===============================

edit: with an example of marking an arbitrary subset of points, as requested in the comments:

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(-np.pi, np.pi, 30)
ys = np.sin(xs)
markers_on = [12, 17, 18, 19]
plt.plot(xs, ys, '-gD', markevery=markers_on)
plt.show()

example2

This last example using the markevery kwarg is possible in since 1.4+, due to the merge of this feature branch. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the edit history for more details.

How to stop the task scheduled in java.util.Timer class

Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

SQL how to increase or decrease one for a int column in one command

to answer the second:

make the column unique and catch the exception if it's set to the same value.

SELECT * FROM in MySQLi

I was looking for a nice and complete example of how to bind multiple query parameters dynamically to any SELECT, INSERT, UPDATE and DELETE query. Alec mentions in his answer a way of how to bind result, for me the get_result() after execute() function for SELECT queries works just fine, and am able to retrieve all the selected results into an array of associative arrays.

Anyway, I ended up creating a function where I am able to dynamically bind any amount of parameters to a parametrized query ( using call_user_func_array function) and obtain a result of the query execution. Below is the function with its documentation (please read before it before using - especially the $paremetersTypes - Type specification chars parameter is important to understand)

     /**
     * Prepares and executes a parametrized QUERY (SELECT, INSERT, UPDATE, DELETE)
     *
     * @param[in] $dbConnection mysqli database connection to be used for query execution
     * @param[in] $dbQuery parametrized query to be bind parameters for and then execute
     * @param[in] $isDMQ boolean value, should be set to TRUE for (DELETE, INSERT, UPDATE - Data manipulaiton queries), FALSE for SELECT queries
     * @param[in] $paremetersTypes String representation for input parametrs' types as per http://php.net/manual/en/mysqli-stmt.bind-param.php
     * @param[in] $errorOut A variable to be passed by reference where a string representation of an error will be present if a FAUILURE occurs
     * @param[in] $arrayOfParemetersToBind Parameters to be bind to the parametrized query, parameters need to be specified in an array in the correct order 
     * @return array of feched records associative arrays for SELECT query on SUCCESS, TRUE for INSERT, UPDATE, DELETE queries on SUCCESS, on FAIL sets the error and returns NULL 
     */
    function ExecuteMySQLParametrizedQuery($dbConnection, $dbQuery, $isDMQ, $paremetersTypes, &$errorOut, $arrayOfParemetersToBind)
    {
        $stmt = $dbConnection->prepare($dbQuery);

        $outValue = NULL;

        if ($stmt === FALSE)
            $errorOut = 'Failed to prepare statement for query: ' . $dbQuery;
        else if ( call_user_func_array(array($stmt, "bind_param"), array_merge(array($paremetersTypes), $arrayOfParemetersToBind)) === FALSE)
            $errorOut = 'Failed to bind required parameters to query: ' . $dbQuery . '  , parameters :' . json_encode($arrayOfParemetersToBind);
        else if (!$stmt->execute())
            $errorOut = "Failed to execute query [$dbQuery] , erorr:" . $stmt->error;
        else
        {
            if ($isDMQ)
               $outValue = TRUE;
            else
            {
                $result = $stmt->get_result();

                if ($result === FALSE) 
                     $errorOut = 'Failed to obtain result from statement for query ' . $dbQuery;
                else
                    $outValue = $result->fetch_all(MYSQLI_ASSOC);
            }
        }

        $stmt->close();

        return $outValue;
    }

usage:

    $param1 = "128989";
    $param2 = "some passcode";


    $insertQuery = "INSERT INTO Cards (Serial, UserPin) VALUES (?, ?)";
    $rowsInserted = ExecuteMySQLParametrizedQuery($dbConnection, $insertQuery, TRUE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference

    if ($rowsInserted === NULL)
        echo 'error ' . $errorOut;
    else
        echo "successfully inserted row";


    $selectQuery = "SELECT CardID FROM Cards WHERE Serial like ? AND UserPin like ?";
    $arrayOfCardIDs = ExecuteMySQLParametrizedQuery($dbConnection, $selectQuery, FALSE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference

    if ($arrayOfCardIDs === NULL) 
        echo 'error ' . $errorOut;
    else
    {
        echo 'obtained result array of ' . count($arrayOfCardIDs) . 'selected rows';

        if (count($arrayOfCardIDs) > 0) 
            echo 'obtained card id = ' . $arrayOfCardIDs[0]['CardID'];
    }

git pull error "The requested URL returned error: 503 while accessing"

Had the same error while using SourceTree connected to BitBucket repository.

When navigating to repository url on bitbucket.org the warning message appeared:

This repository is in read-only mode. You caught us doing some quick maintenance.

After around 2 hours repository was accessible again.

You can check status and uptime of bitbucket here: http://status.bitbucket.org/

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

With arrays, why is it the case that a[5] == 5[a]?

Nice question/answers.

Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.

Consider the following declarations:

int a[10];
int* p = a;

In a.out, the symbol a is at an address that's the beginning of the array, and symbol p is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.

Webpack not excluding node_modules

This worked for me:

exclude: [/bower_components/, /node_modules/]

module.loaders

A array of automatically applied loaders.

Each item can have these properties:

test: A condition that must be met

exclude: A condition that must not be met

include: A condition that must be met

loader: A string of "!" separated loaders

loaders: A array of loaders as string

A condition can be a RegExp, an absolute path start, or an array of one of these combined with "and".

See http://webpack.github.io/docs/configuration.html#module-loaders

Base64 encoding in SQL Server 2005 T-SQL

Here is the code for the functions that will do the work

-- To Base64 string
CREATE FUNCTION [dbo].[fn_str_TO_BASE64]
(
    @STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    RETURN (
        SELECT
            CAST(N'' AS XML).value(
                  'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
                , 'NVARCHAR(MAX)'
            )   Base64Encoding
        FROM (
            SELECT CAST(@STRING AS VARBINARY(MAX)) AS bin
        ) AS bin_sql_server_temp
    )
END
GO

-- From Base64 string
CREATE FUNCTION [dbo].[fn_str_FROM_BASE64]
(
    @BASE64_STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    RETURN (
        SELECT 
            CAST(
                CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@BASE64_STRING"))', 'VARBINARY(MAX)') 
            AS NVARCHAR(MAX)
            )   UTF8Encoding
    )
END

Example of usage:

DECLARE @CHAR NVARCHAR(256) = N'e.g., ???? ????? or ? ??????'
SELECT [dbo].[fn_str_FROM_BASE64]([dbo].[fn_str_TO_BASE64](@CHAR)) as converted

enter image description here

How to send a POST request from node.js Express?

you can try like this:

var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
               , url: <your URL>, body: <req_body in json> }
               , function(error, response, body){
   console.log(body); 
}); 

Contains case insensitive

You can try this

_x000D_
_x000D_
str = "Wow its so COOL"_x000D_
searchStr = "CoOl"_x000D_
_x000D_
console.log(str.toLowerCase().includes(searchStr.toLowerCase()))
_x000D_
_x000D_
_x000D_

Minimum 6 characters regex expression

This match 6 or more any chars but newline:

/^.{6,}$/

File Explorer in Android Studio

This works on Android Studio 1.x:

  • Tools --> Android --> Android Device Monitor (this open the ADM)
  • Window --> Show View
  • Search for File Explorer then press the OK Button
  • The File Explorer Tab is now open on the View

java.util.zip.ZipException: error in opening zip file

Make sure your jar file is not corrupted. If it's corrupted or not able to unzip, this error will occur.

Abstract variables in Java?

I think your confusion is with C# properties vs. fields/variables. In C# you cannot define abstract fields, even in an abstract class. You can, however, define abstract properties as these are effectively methods (e.g. compiled to get_TAG() and set_TAG(...)).

As some have reminded, you should never have public fields/variables in your classes, even in C#. Several answers have hinted at what I would recommend, but have not made it clear. You should translate your idea into Java as a JavaBean property, using getTAG(). Then your sub-classes will have to implement this (I also have written a project with table classes that do this).

So you can have an abstract class defined like this...

public abstract class AbstractTable {

    public abstract String getTag();
    public abstract void init();

    ...
}

Then, in any concrete subclasses you would need to define a static final variable (constant) and return that from the getTag(), something like this:

public class SalesTable extends AbstractTable {

    private static final String TABLE_NAME = "Sales";

    public String getTag() {
        return TABLE_NAME;
    }

    public void init() {
        ...
        String tableName = getTag();
        ...
    }

}

EDIT:

You cannot override inherited fields (in either C# or Java). Nor can you override static members, whether they are fields or methods. So this also is the best solution for that. I changed my init method example above to show how this would be used - again, think of the getXXX method as a property.

Java: How to stop thread?

We don't stop or kill a thread rather we do Thread.currentThread().isInterrupted().

public class Task1 implements Runnable {
    public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                       ................
                       ................
                       ................
                       ................
           }
    }
}

in main we will do like this:

Thread t1 = new Thread(new Task1());
t1.start();
t1.interrupt();

javascript compare strings without being case sensitive

Another method using a regular expression (this is more correct than Zachary's answer):

var string1 = 'someText',
    string2 = 'SometexT',
    regex = new RegExp('^' + string1 + '$', 'i');

if (regex.test(string2)) {
    return true;
}

RegExp.test() will return true or false.

Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.

It might just be easier to use the string.toLowerCase() method.

So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.

There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial: http://weblogtoolscollection.com/regex/regex.php

This appears to be a good tool to test regular expressions: http://gskinner.com/RegExr/

How do I instantiate a Queue object in java?

Queue is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this isn't what you want to do for a collection. Instead, choose an existing implementation. For example:

Queue<Integer> q = new LinkedList<Integer>();

or

Queue<Integer> q = new ArrayDeque<Integer>();

Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.

batch file - counting number of files in folder and storing in a variable

Change into the directory and;

attrib.exe /s ./*.* |find /c /v ""

EDIT

I presumed that would be simple to discover. use

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "batchfile.bat";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

I run this and the variable output was holding this

D:\VSS\USSD V3.0\WTU.USSD\USSDConsole\bin\Debug>attrib.exe /s ./*.*   | find /c /v "" 13

where 13 is the file count. It should solve the issue

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

How can I change the current URL?

If you just want to update the relative path you can also do

window.location.pathname = '/relative-link'

"http://domain.com" -> "http://domain.com/relative-link"

Output PowerShell variables to a text file

The simple solution is to avoid creating an array before piping to Out-File. Rule #1 of PowerShell is that the comma is a special delimiter, and the default behavior is to create an array. Concatenation is done like this.

$computer + "," + $Speed + "," + $Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

This creates an array of three items.

$computer,$Speed,$Regcheck
FYKJ
100
YES

vs. concatenation of three items separated by commas.

$computer + "," + $Speed + "," + $Regcheck
FYKJ,100,YES

Reloading/refreshing Kendo Grid

I never do refresh.

$('#GridName').data('kendoGrid').dataSource.read();

alone works for me all the time.

What is "export default" in JavaScript?

There are two different types of export, named and default. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above. Source: MDN

Named Export

export class NamedExport1 { }

export class NamedExport2 { }

// Import class
import { NamedExport1 } from 'path-to-file'
import { NamedExport2 } from 'path-to-file'

// OR you can import all at once
import * as namedExports from 'path-to-file'

Default Export

export default class DefaultExport1 { }

// Import class
import DefaultExport1 from 'path-to-file' // No curly braces - {}

// You can use a different name for the default import

import Foo from 'path-to-file' // This will assign any default export to Foo.

Determine when a ViewPager changes pages

Use the ViewPager.onPageChangeListener:

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    public void onPageSelected(int position) {
        // Check if this is the page you want.
    }
});

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. My solution was to make all vectors numeric.

How to send an HTTP request with a header parameter?

With your own Code and a Slight Change withou jQuery,

function testingAPI(){ 
    var key = "8a1c6a354c884c658ff29a8636fd7c18"; 
    var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
    console.log(httpGet(url,key)); 
}


function httpGet(url,key){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

Thank You

How can I read a text file from the SD card in Android?

Beware: some phones have 2 sdcards , an internal fixed one and a removable card. You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? ) When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" . Suppose I want to open a text-file "MyBooks.txt" I would use something as :

   String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
   File file = new File(fname);...etc...

Allow docker container to connect to a local/host postgres database

In Ubuntu:

First You have to check that is the Docker Database port is Available in your system by following command -

sudo iptables -L -n

Sample OUTPUT:

Chain DOCKER (1 references)
target     prot opt source               destination         
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.2           tcp dpt:3306
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:80
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.3           tcp dpt:22

Here 3306 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

Now, You can easily access the Docker Database from your local system by following configuration

  host: 172.17.0.2 
  adapter: mysql
  database: DATABASE_NAME
  port: 3307
  username: DATABASE_USER
  password: DATABASE_PASSWORD
  encoding: utf8

In CentOS:

First You have to check that is the Docker Database port is Available in your firewall by following command -

sudo firewall-cmd --list-all

Sample OUTPUT:

  target: default
  icmp-block-inversion: no
  interfaces: eno79841677
  sources: 
  services: dhcpv6-client ssh
  **ports: 3307/tcp**
  protocols: 
  masquerade: no
  forward-ports: 
  sourceports: 
  icmp-blocks: 
  rich rules:

Here 3307 is used as Docker Database Port on 172.17.0.2 IP, If this port is not available Run the following command -

sudo firewall-cmd --zone=public --add-port=3307/tcp

In server, You can add the port permanently

sudo firewall-cmd --permanent --add-port=3307/tcp
sudo firewall-cmd --reload

Now, You can easily access the Docker Database from your local system by the above configuration.

What is the difference between typeof and instanceof and when should one be used vs. the other?

instanceof will not work for primitives eg "foo" instanceof String will return false whereas typeof "foo" == "string" will return true.

On the other hand typeof will probably not do what you want when it comes to custom objects (or classes, whatever you want to call them). For example:

function Dog() {}
var obj = new Dog;
typeof obj == 'Dog' // false, typeof obj is actually "object"
obj instanceof Dog  // true, what we want in this case

It just so happens that functions are both 'function' primitives and instances of 'Function', which is a bit of an oddity given that it doesn't work like that for other primitive types eg.

(typeof function(){} == 'function') == (function(){} instanceof Function)

but

(typeof 'foo' == 'string') != ('foo' instanceof String)

How do I address unchecked cast warnings?

If I have to use an API that doesn't support Generics.. I try and isolate those calls in wrapper routines with as few lines as possible. I then use the SuppressWarnings annotation and also add the type-safety casts at the same time.

This is just a personal preference to keep things as neat as possible.

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

How to declare std::unique_ptr and what is the use of it?

From cppreference, one of the std::unique_ptr constructors is

explicit unique_ptr( pointer p ) noexcept;

So to create a new std::unique_ptr is to pass a pointer to its constructor.

unique_ptr<int> uptr (new int(3));

Or it is the same as

int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);

The different is you don't have to clean up after using it. If you don't use std::unique_ptr (smart pointer), you will have to delete it like this

delete int_ptr;

when you no longer need it or it will cause a memory leak.

How to create timer events using C++ 11?

If you are on Windows, you can use the CreateThreadpoolTimer function to schedule a callback without needing to worry about thread management and without blocking the current thread.

template<typename T>
static void __stdcall timer_fired(PTP_CALLBACK_INSTANCE, PVOID context, PTP_TIMER timer)
{
    CloseThreadpoolTimer(timer);
    std::unique_ptr<T> callable(reinterpret_cast<T*>(context));
    (*callable)();
}

template <typename T>
void call_after(T callable, long long delayInMs)
{
    auto state = std::make_unique<T>(std::move(callable));
    auto timer = CreateThreadpoolTimer(timer_fired<T>, state.get(), nullptr);
    if (!timer)
    {
        throw std::runtime_error("Timer");
    }

    ULARGE_INTEGER due;
    due.QuadPart = static_cast<ULONGLONG>(-(delayInMs * 10000LL));

    FILETIME ft;
    ft.dwHighDateTime = due.HighPart;
    ft.dwLowDateTime = due.LowPart;

    SetThreadpoolTimer(timer, &ft, 0 /*msPeriod*/, 0 /*msWindowLength*/);
    state.release();
}

int main()
{
    auto callback = []
    {
        std::cout << "in callback\n";
    };

    call_after(callback, 1000);
    std::cin.get();
}

What is an uber jar?

A self-contained, executable Java archive. In the case of WildFly Swarm uberjars, it is a single .jar file containing your application, the portions of WildFly required to support it, an internal Maven repository of dependencies, plus a shim to bootstrap it all. see this

How do I check to see if a value is an integer in MySQL?

The best i could think of a variable is a int Is a combination with MySQL's functions CAST() and LENGTH().
This method will work on strings, integers, doubles/floats datatypes.

SELECT (LENGTH(CAST(<data> AS UNSIGNED))) = (LENGTH(<data>)) AS is_int

see demo http://sqlfiddle.com/#!9/ff40cd/44

it will fail if the column has a single character value. if column has a value 'A' then Cast('A' as UNSIGNED) will evaluate to 0 and LENGTH(0) will be 1. so LENGTH(Cast('A' as UNSIGNED))=LENGTH(0) will evaluate to 1=1 => 1

True Waqas Malik totally fogotten to test that case. the patch is.

SELECT <data>, (LENGTH(CAST(<data> AS UNSIGNED))) = CASE WHEN CAST(<data> AS UNSIGNED) = 0 THEN CAST(<data> AS UNSIGNED) ELSE (LENGTH(<data>)) END AS is_int;

Results

**Query #1**

    SELECT 1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1 AS UNSIGNED) = 0 THEN CAST(1 AS UNSIGNED) ELSE (LENGTH(1)) END AS is_int;

| 1   | is_int |
| --- | ------ |
| 1   | 1      |

---
**Query #2**

    SELECT 1.1, (LENGTH(CAST(1 AS UNSIGNED))) = CASE WHEN CAST(1.1 AS UNSIGNED) = 0 THEN CAST(1.1 AS UNSIGNED) ELSE (LENGTH(1.1)) END AS is_int;

| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0      |

---
**Query #3**

    SELECT "1", (LENGTH(CAST("1" AS UNSIGNED))) = CASE WHEN CAST("1" AS UNSIGNED) = 0 THEN CAST("1" AS UNSIGNED) ELSE (LENGTH("1")) END AS is_int;

| 1   | is_int |
| --- | ------ |
| 1   | 1      |

---
**Query #4**

    SELECT "1.1", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1.1" AS UNSIGNED) = 0 THEN CAST("1.1" AS UNSIGNED) ELSE (LENGTH("1.1")) END AS is_int;

| 1.1 | is_int |
| --- | ------ |
| 1.1 | 0      |

---
**Query #5**

    SELECT "1a", (LENGTH(CAST("1.1" AS UNSIGNED))) = CASE WHEN CAST("1a" AS UNSIGNED) = 0 THEN CAST("1a" AS UNSIGNED) ELSE (LENGTH("1a")) END AS is_int;

| 1a  | is_int |
| --- | ------ |
| 1a  | 0      |

---
**Query #6**

    SELECT "1.1a", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("1.1a" AS UNSIGNED) = 0 THEN CAST("1.1a" AS UNSIGNED) ELSE (LENGTH("1.1a")) END AS is_int;

| 1.1a | is_int |
| ---- | ------ |
| 1.1a | 0      |

---
**Query #7**

    SELECT "a1", (LENGTH(CAST("1.1a" AS UNSIGNED))) = CASE WHEN CAST("a1" AS UNSIGNED) = 0 THEN CAST("a1" AS UNSIGNED) ELSE (LENGTH("a1")) END AS is_int;

| a1  | is_int |
| --- | ------ |
| a1  | 0      |

---
**Query #8**

    SELECT "a1.1", (LENGTH(CAST("a1.1" AS UNSIGNED))) = CASE WHEN CAST("a1.1" AS UNSIGNED) = 0 THEN CAST("a1.1" AS UNSIGNED) ELSE (LENGTH("a1.1")) END AS is_int;

| a1.1 | is_int |
| ---- | ------ |
| a1.1 | 0      |

---
**Query #9**

    SELECT "a", (LENGTH(CAST("a" AS UNSIGNED))) = CASE WHEN CAST("a" AS UNSIGNED) = 0 THEN CAST("a" AS UNSIGNED) ELSE (LENGTH("a")) END AS is_int;

| a   | is_int |
| --- | ------ |
| a   | 0      |

see demo

Ignoring directories in Git repositories on Windows

I assume the problem is that your working tree is like:

a-cache/foo
a-cache/index.html
b-cache/bar
b-cache/foo
b-cache/index.html
.gitignore

... with the .gitignore you describe. This will give you git status output like:

$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#    .gitignore
#    a-cache/
#    b-cache/

... if the index.html files have not yet been added to the repository. (Git sees that there are unignored files in the cache directories, but it only reports the directories.) To fix this, make sure that you have added and committed the index.html files:

git add *cache/index.html
git commit -m "Adding index.html files to the cache directories"

... and your git status will then look like:

$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#    .gitignore
nothing added to commit but untracked files present (use "git add" to track)

(Obviously you do want to commit .gitignore as well. I was just being lazy with this test case.)

Passing properties by reference in C#

Properties cannot be passed by reference. Here are a few ways you can work around this limitation.

1. Return Value

string GetString(string input, string output)
{
    if (!string.IsNullOrEmpty(input))
    {
        return input;
    }
    return output;
}

void Main()
{
    var person = new Person();
    person.Name = GetString("test", person.Name);
    Debug.Assert(person.Name == "test");
}

2. Delegate

void GetString(string input, Action<string> setOutput)
{
    if (!string.IsNullOrEmpty(input))
    {
        setOutput(input);
    }
}

void Main()
{
    var person = new Person();
    GetString("test", value => person.Name = value);
    Debug.Assert(person.Name == "test");
}

3. LINQ Expression

void GetString<T>(string input, T target, Expression<Func<T, string>> outExpr)
{
    if (!string.IsNullOrEmpty(input))
    {
        var expr = (MemberExpression) outExpr.Body;
        var prop = (PropertyInfo) expr.Member;
        prop.SetValue(target, input, null);
    }
}

void Main()
{
    var person = new Person();
    GetString("test", person, x => x.Name);
    Debug.Assert(person.Name == "test");
}

4. Reflection

void GetString(string input, object target, string propertyName)
{
    if (!string.IsNullOrEmpty(input))
    {
        var prop = target.GetType().GetProperty(propertyName);
        prop.SetValue(target, input);
    }
}

void Main()
{
    var person = new Person();
    GetString("test", person, nameof(Person.Name));
    Debug.Assert(person.Name == "test");
}

base64 encode in MySQL

If you need this for < 5.6, I tripped across this UDF which seems to work fine:

https://github.com/y-ken/mysql-udf-base64

how to convert image to byte array in java?

java.io.FileInputStream is what you're looking for :-)

Is it possible to set ENV variables for rails development environment in my code?

The way I am trying to do this in my question actually works!

# environment/development.rb

ENV['admin_password'] = "secret" 

I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

I am picking my own answer because I feel this is a better place to put and set the ENV variables

Parse DateTime string in JavaScript

ASP.NET developers have the choice of this handy built-in (MS JS must be included in page):

var date = Date.parseLocale('20-Mar-2012', 'dd-MMM-yyyy');

http://msdn.microsoft.com/en-us/library/bb397521%28v=vs.100%29.aspx

What is the best regular expression to check if a string is a valid URL?

I've been working on an in-depth article discussing URI validation using regular expressions. It is based on RFC3986.

Regular Expression URI Validation

Although the article is not yet complete, I have come up with a PHP function which does a pretty good job of validating HTTP and FTP URLs. Here is the current version:

// function url_valid($url) { Rev:20110423_2000
//
// Return associative array of valid URI components, or FALSE if $url is not
// RFC-3986 compliant. If the passed URL begins with: "www." or "ftp.", then
// "http://" or "ftp://" is prepended and the corrected full-url is stored in
// the return array with a key name "url". This value should be used by the caller.
//
// Return value: FALSE if $url is not valid, otherwise array of URI components:
// e.g.
// Given: "http://www.jmrware.com:80/articles?height=10&width=75#fragone"
// Array(
//    [scheme] => http
//    [authority] => www.jmrware.com:80
//    [userinfo] =>
//    [host] => www.jmrware.com
//    [IP_literal] =>
//    [IPV6address] =>
//    [ls32] =>
//    [IPvFuture] =>
//    [IPv4address] =>
//    [regname] => www.jmrware.com
//    [port] => 80
//    [path_abempty] => /articles
//    [query] => height=10&width=75
//    [fragment] => fragone
//    [url] => http://www.jmrware.com:80/articles?height=10&width=75#fragone
// )
function url_valid($url) {
    if (strpos($url, 'www.') === 0) $url = 'http://'. $url;
    if (strpos($url, 'ftp.') === 0) $url = 'ftp://'. $url;
    if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
        ^
        (?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
        (?P<authority>
          (?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
          (?P<host>
            (?P<IP_literal>
              \[
              (?:
                (?P<IPV6address>
                  (?:                                                (?:[0-9A-Fa-f]{1,4}:){6}
                  |                                                ::(?:[0-9A-Fa-f]{1,4}:){5}
                  | (?:                          [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?::   [0-9A-Fa-f]{1,4}:
                  | (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::
                  )
                  (?P<ls32>[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}
                  | (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
                       (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
                  )
                |   (?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?::   [0-9A-Fa-f]{1,4}
                |   (?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::
                )
              | (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
              )
              \]
            )
          | (?P<IPv4address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
                               (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
          | (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
          )
          (?::(?P<port>[0-9]*))?
        )
        (?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
        (?:\?(?P<query>       (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
        (?:\#(?P<fragment>    (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
        $
        /mx', $url, $m)) return FALSE;
    switch ($m['scheme']) {
    case 'https':
    case 'http':
        if ($m['userinfo']) return FALSE; // HTTP scheme does not allow userinfo.
        break;
    case 'ftps':
    case 'ftp':
        break;
    default:
        return FALSE;   // Unrecognized URI scheme. Default to FALSE.
    }
    // Validate host name conforms to DNS "dot-separated-parts".
    if ($m['regname']) { // If host regname specified, check for DNS conformance.
        if (!preg_match('/# HTTP DNS host name.
            ^                      # Anchor to beginning of string.
            (?!.{256})             # Overall host length is less than 256 chars.
            (?:                    # Group dot separated host part alternatives.
              [A-Za-z0-9]\.        # Either a single alphanum followed by dot
            |                      # or... part has more than one char (63 chars max).
              [A-Za-z0-9]          # Part first char is alphanum (no dash).
              [A-Za-z0-9\-]{0,61}  # Internal chars are alphanum plus dash.
              [A-Za-z0-9]          # Part last char is alphanum (no dash).
              \.                   # Each part followed by literal dot.
            )*                     # Zero or more parts before top level domain.
            (?:                    # Explicitly specify top level domains.
              com|edu|gov|int|mil|net|org|biz|
              info|name|pro|aero|coop|museum|
              asia|cat|jobs|mobi|tel|travel|
              [A-Za-z]{2})         # Country codes are exactly two alpha chars.
              \.?                  # Top level domain can end in a dot.
            $                      # Anchor to end of string.
            /ix', $m['host'])) return FALSE;
    }
    $m['url'] = $url;
    for ($i = 0; isset($m[$i]); ++$i) unset($m[$i]);
    return $m; // return TRUE == array of useful named $matches plus the valid $url.
}

This function utilizes two regexes; one to match a subset of valid generic URIs (absolute ones having a non-empty host), and a second to validate the DNS "dot-separated-parts" host name. Although this function currently validates only HTTP and FTP schemes, it is structured such that it can be easily extended to handle other schemes.

How to update column with null value

In the above answers, many ways and repetitions have been suggested for the same. I kept looking for an answer as mentioned is the question but couldn't find here.

Another way to put the above question "update a column with a null value" could be "UPDATE ALL THE ROWS IN THE COLUMN TO NULL"

In such a situation following works

update table_name
set field_name = NULL
where field_name is not NULL;

is as well is not works in mysql

Is it possible to cast a Stream in Java 8?

Along the lines of ggovan's answer, I do this as follows:

/**
 * Provides various high-order functions.
 */
public final class F {
    /**
     * When the returned {@code Function} is passed as an argument to
     * {@link Stream#flatMap}, the result is a stream of instances of
     * {@code cls}.
     */
    public static <E> Function<Object, Stream<E>> instancesOf(Class<E> cls) {
        return o -> cls.isInstance(o)
                ? Stream.of(cls.cast(o))
                : Stream.empty();
    }
}

Using this helper function:

Stream.of(objects).flatMap(F.instancesOf(Client.class))
        .map(Client::getId)
        .forEach(System.out::println);

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

An alternative is:

System.out.println(opt.map(o -> "Found")
                      .orElse("Not found"));

I don't think it improves readability though.

Or as Marko suggested, use a ternary operator:

System.out.println(opt.isPresent() ? "Found" : "Not found");

Run JavaScript when an element loses focus

How about onblur event :

<input type="text" name="name" value="value" onblur="alert(1);"/>

Converting integer to binary in python

.. or if you're not sure it should always be 8 digits, you can pass it as a parameter:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'

How to convert a time string to seconds?

A little more pythonic way I think would be:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

Output is 263Sec.

I would be interested to see if anyone could simplify it further.

python exception message capturing

You can use logger.exception("msg") for logging exception with traceback:

try:
    #your code
except Exception as e:
    logger.exception('Failed: ' + str(e))

Node.js: How to read a stream into a buffer?

You can easily do this using node-fetch if you are pulling from http(s) URIs.

From the readme:

fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
    .then(res => res.buffer())
    .then(buffer => console.log)

Fix footer to bottom of page

Your footer element won't inherently be fixed to the bottom of your viewport unless you style it that way.
So if you happen to have a page that doesn't have enough content to push it all the way down it'll end up somewhere in the middle of the viewport; looking very awkward and not sure what to do with itself, like my first day of high school.

Positioning the element by declaring the fixed rule is great if you always want your footer visible regardless of initial page height - but then remember to set a bottom margin so that it doesn't overlay the last bit of content on that page. This becomes tricky if your footer has a dynamic height; which is often the case with responsive sites since it's in the nature of elements to stack.

You'll find a similar problem with absolute positioning. And although it does take the element in question out of the natural flow of the document, it still won't fix it to the bottom of the screen should you find yourself with a page that has little to no content to flesh it out.

Consider achieving this by:

  1. Declaring a height value for the <body> & <html> tags
  2. Declaring a minimum-height value to the nested wrapper element, usually the element which wraps all your descendant elements contained within the body structure (this wouldn't include your footer element)

Code Pen Example

_x000D_
_x000D_
$("#addBodyContent").on("click", function() {_x000D_
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".flex-col:first-of-type");_x000D_
});_x000D_
_x000D_
$("#resetBodyContent").on("click", function() {_x000D_
  $(".flex-col p").remove();_x000D_
});_x000D_
_x000D_
$("#addFooterContent").on("click", function() {_x000D_
  $("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo("footer");_x000D_
});_x000D_
_x000D_
$("#resetFooterContent").on("click", function() {_x000D_
  $("footer p").remove();_x000D_
});
_x000D_
html, body {_x000D_
    height: 91%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
    width: 100%;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
    display: block;_x000D_
    min-height: 100%;_x000D_
}_x000D_
_x000D_
footer {_x000D_
    background: black;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
    display: flex;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.flex-col {_x000D_
    flex: 1 1;_x000D_
    background: #ccc;_x000D_
    margin: 0px 10px;_x000D_
    box-sizing: border-box;_x000D_
    padding: 20px;_x000D_
}_x000D_
_x000D_
.flex-btn-wrapper {_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    flex-direction: row;_x000D_
}_x000D_
_x000D_
.btn {_x000D_
    box-sizing: border-box;_x000D_
    padding: 10px;_x000D_
    transition: .7s;_x000D_
    margin: 10px 10px;_x000D_
    min-width: 200px;_x000D_
}_x000D_
_x000D_
.btn:hover {_x000D_
    background: transparent;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
.dark {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    border: 3px solid black;_x000D_
}_x000D_
_x000D_
.light {_x000D_
    background: white;_x000D_
    border: 3px solid white;_x000D_
}_x000D_
_x000D_
.light:hover {_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.dark:hover {_x000D_
    color: black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrapper">_x000D_
    <div class="flex-btn-wrapper">_x000D_
        <button id="addBodyContent" class="dark btn">Add Content</button>_x000D_
        <button id="resetBodyContent" class="dark btn">Reset Content</button>_x000D_
    </div>_x000D_
    <div class="flex">_x000D_
    <div class="flex-col">_x000D_
      lorem ipsum dolor..._x000D_
    </div>_x000D_
    <div class="flex-col">_x000D_
      lorem ipsum dolor..._x000D_
    </div>_x000D_
    </div>_x000D_
    </div>_x000D_
<footer>_x000D_
    <div class="flex-btn-wrapper">_x000D_
        <button id="addFooterContent" class="light btn">Add Content</button>_x000D_
        <button id="resetFooterContent" class="light btn">Reset Content</button>_x000D_
    </div>_x000D_
    lorem ipsum dolor..._x000D_
</footer>
_x000D_
_x000D_
_x000D_

Flask Python Buttons

In case anyone was still looking and came across this SO post like I did.

<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">

def contact():
    if "open" in request.form:
        pass
    elif "close" in request.form:
        pass
    return render_template('contact.html')

Simple, concise, and it works. Don't even need to instantiate a form object.

How to do vlookup and fill down (like in Excel) in R?

I think you can also use match():

largetable$HouseTypeNo <- with(lookup,
                     HouseTypeNo[match(largetable$HouseType,
                                       HouseType)])

This still works if I scramble the order of lookup.

What is the "-->" operator in C/C++?

-- is the decrement operator and > is the greater-than operator.

The two operators are applied as a single one like -->.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only need to specify xs.

OK, the answer is easy, but read on:

col-lg- stands for column large = 1200px
col-md- stands for column medium = 992px
col-xs- stands for column extra small = 768px

The pixel numbers are the breakpoints, so for example col-xs is targeting the element when the window is smaller than 768px(likely mobile devices)...

I also created the image below to show how the grid system works, in this examples I use them with 3, like col-lg-6 to show you how the grid system work in the page, look at how lg, md and xs are responsive to the window size:

Bootstrap grid system, col-*-6

Add space between <li> elements

You can use the margin property:

li.menu-item {
   margin:0 0 10px 0;   
}

Demo: http://jsfiddle.net/UAXyd/

python pandas: apply a function with arguments to a series

Steps:

  1. Create a dataframe
  2. Create a function
  3. Use the named arguments of the function in the apply statement.

Example

x=pd.DataFrame([1,2,3,4])  

def add(i1, i2):  
    return i1+i2

x.apply(add,i2=9)

The outcome of this example is that each number in the dataframe will be added to the number 9.

    0
0  10
1  11
2  12
3  13

Explanation:

The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".

How to calculate percentage when old value is ZERO

There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:

  1. Any time you have to show a rate of increase from zero, output the infinity symbol (8). That's Alt + 236 on your number pad, in case you're wondering. You could also use negative infinity (-8) for a negative growth rate from zero.
  2. Output a statement such as "[Increase/Decrease] From Zero" or something along those lines.

Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.

As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

iOS - Calling App Delegate method from ViewController

NSObject <UIApplicationDelegate> * universalAppDelegate = 
    ( NSObject <UIApplicationDelegate> * ) [ [ UIApplication sharedApplication ] delegate ];

It avoid having to include your AppDelegate.h everywhere. It's a simple cast that goes a long way, allowing to develop independent Controller and reuse them elsewhere without to worry about class name and so on...

Enjoy

"git checkout <commit id>" is changing branch to "no branch"

If you are branch master and you do a git checkout <SHA>

I'm fairly certain that this causes git to load that commit in a detached state, changing you out of the current branch.

If you want to make changes you can and then you can do a git checkout -b <mynewbranch> to create a new branch based off that commit and any changes you have made.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

One thing json cannot do is dict indexed with numerals. The following snippet

import json
dictionary = dict({0:0, 1:5, 2:10})
serialized = json.dumps(dictionary)
unpacked   = json.loads(serialized)
print(unpacked[0])

will throw

KeyError: 0

Because keys are converted to strings. cPickle preserves the numeric type and the unpacked dict can be used right away.

php - push array into array - key issue

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}


array_push == $res_arr_values[] = $row;

example 

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
?>

Resource u'tokenizers/punkt/english.pickle' not found

I faced same issue. After downloading everything, still 'punkt' error was there. I searched package on my windows machine at C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers and I can see 'punkt.zip' present there. I realized that somehow the zip has not been extracted into C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers\punk. Once I extracted the zip, it worked like music.

How can I get Git to follow symlinks?

I used to add files beyond symlinks for quite some time now. This used to work just fine, without making any special arrangements. Since I updated to Git 1.6.1, this does not work any more.

You may be able to switch to Git 1.6.0 to make this work. I hope that a future version of Git will have a flag to git-add allowing it to follow symlinks again.

For each row return the column name of the largest value

A simple for loop can also be handy:

> df<-data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
> df
  V1 V2 V3
1  2  7  9
2  8  3  6
3  1  5  4
> df2<-data.frame()
> for (i in 1:nrow(df)){
+   df2[i,1]<-colnames(df[which.max(df[i,])])
+ }
> df2
  V1
1 V3
2 V1
3 V2

How do I set a textbox's text to bold at run time?

You could use Extension method to switch between Regular Style and Bold Style as below:

static class Helper
    {
        public static void SwtichToBoldRegular(this TextBox c)
        {
            if (c.Font.Style!= FontStyle.Bold)
                c.Font = new Font(c.Font, FontStyle.Bold);
            else
                c.Font = new Font(c.Font, FontStyle.Regular);
        }
    }

And usage:

textBox1.SwtichToBoldRegular();

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

JavaScript alert box with timer

tooltips can be used as alerts. These can be timed to appear and disappear.

CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.

Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.

Extracting .jar file with command line

In Ubuntu:

unzip file.jar -d dir_name_where_extracting

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

In my case, there was no string on which i was calling appendChild, the object i was passing on appendChild argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0]) instead of divel.appendChild(childel) and it worked. Hope it help someone.

What, exactly, is needed for "margin: 0 auto;" to work?

It will also work with display:table - a useful display property in this case because it doesn't require a width to be set. (I know this post is 5 years old, but it's still relevant to passers-by ;)

Replace Div with another Div

You can use .replaceWith()

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $(".region").click(function(e) {_x000D_
    e.preventDefault();_x000D_
    var content = $(this).html();_x000D_
    $('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
  <div class="region"><a href="link1">region1</a></div>_x000D_
  <div class="region"><a href="link2">region2</a></div>_x000D_
  <div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

require(vendor/autoload.php): failed to open stream

I had this path in my machine:

C:/xampp5.0/htdocs/project-recordando-symfony/project-recordando-symfony

Then I ran composer install or/and composer update and it returned this error:

ErrorException ZipArchive::extractTo...

That error is because your path is too much long, I changed to:

C:/xampp5.0/htdocs/p-symfony/*

and worked!

JavaScript by reference vs. by value

  1. Primitive type variable like string,number are always pass as pass by value.
  2. Array and Object is passed as pass by reference or pass by value based on these two condition.

    • if you are changing value of that Object or array with new Object or Array then it is pass by Value.

      object1 = {item: "car"}; array1=[1,2,3];

    here you are assigning new object or array to old one.you are not changing the value of property of old object.so it is pass by value.

    • if you are changing a property value of an object or array then it is pass by Reference.

      object1.item= "car"; array1[0]=9;

    here you are changing a property value of old object.you are not assigning new object or array to old one.so it is pass by reference.

Code

    function passVar(object1, object2, number1) {

        object1.key1= "laptop";
        object2 = {
            key2: "computer"
        };
        number1 = number1 + 1;
    }

    var object1 = {
        key1: "car"
    };
    var object2 = {
        key2: "bike"
    };
    var number1 = 10;

    passVar(object1, object2, number1);
    console.log(object1.key1);
    console.log(object2.key2);
    console.log(number1);

Output: -
    laptop
    bike
    10

Manifest Merger failed with multiple errors in Android Studio

Happened with me twice when I refractor (Rename with SHIFT + F6) the name of a field in our files and it asks you to change it everywhere and we without paying attention change the name everywhere. For example, if you have a variable name "id" in your Java class and you rename it with SHIFT + F6. If you don't pay attention to the next dialog which will ask you wherever else it is going to change the id and you tick check all it will change all the id in your layout files from the new value.

Why is my xlabel cut off in my matplotlib plot?

plt.autoscale() worked for me.

Multiple -and -or in PowerShell Where-Object statement

By wrapping your comparisons in {} in your first example you are creating ScriptBlocks; so the PowerShell interpreter views it as Where-Object { <ScriptBlock> -and <ScriptBlock> }. Since the -and operator operates on boolean values, PowerShell casts the ScriptBlocks to boolean values. In PowerShell anything that is not empty, zero or null is true. The statement then looks like Where-Object { $true -and $true } which is always true.

Instead of using {}, use parentheses ().

Also you want to use -eq instead of -match since match uses regex and will be true if the pattern is found anywhere in the string (try: 'xlsx' -match 'xls').

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public | 
        Where-Object {($_.extension -eq ".xls" -or $_.extension -eq ".xlk") -and ($_.creationtime -ge "06/01/2014")}
}

A better option is to filter the extensions at the Get-ChildItem command.

Invoke-Command -computername SERVERNAME { 
    Get-ChildItem -path E:\dfsroots\datastore2\public\* -Include *.xls, *.xlk | 
        Where-Object {$_.creationtime -ge "06/01/2014"}
}

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

I solved my problem in AngularJS as follows:

var configPopOver = {
        animation: 500,
        container: 'body',
        placement: function (context, source) {
                    var elBounding = source.getBoundingClientRect();
                    var pageWidth = angular.element('body')[0].clientWidth
                    var pageHeith = angular.element('body')[0].clientHeith

                    if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "left";
                    }

                    if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "right";
                    }

                    if (elBounding.top < 110){
                        return "bottom";
                    }

                    return "top";
                },
        html: true
    };

This function do the position of Bootstrap popover float to the best position, based on element position.

Incrementing a date in JavaScript

var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

How to display a JSON representation and not [Object Object] on the screen

this.http.get<any>('http://192.168.1.15:4000/GetPriority')
  .subscribe(response => 
  {
  this.records=JSON.stringify(response) // impoprtant
  console.log("records"+this.records)
  });

How can I flush GPU memory using CUDA (physical reset is unavailable)

One can also use nvtop, which gives an interface very similar to htop, but showing your GPU(s) usage instead, with a nice graph. You can also kill processes directly from here.

Here is a link to its Github : https://github.com/Syllo/nvtop

NVTOP interface

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

So far, the accepted answer has worked best for me. However, my concern has always been that there is a likely scenario where I might refactor the notebooks directory into subdirectories, requiring to change the module_path in every notebook. I decided to add a python file within each notebook directory to import the required modules.

Thus, having the following project structure:

project
|__notebooks
   |__explore
      |__ notebook1.ipynb
      |__ notebook2.ipynb
      |__ project_path.py
   |__ explain
       |__notebook1.ipynb
       |__project_path.py
|__lib
   |__ __init__.py
   |__ module.py

I added the file project_path.py in each notebook subdirectory (notebooks/explore and notebooks/explain). This file contains the code for relative imports (from @metakermit):

import sys
import os

module_path = os.path.abspath(os.path.join(os.pardir, os.pardir))
if module_path not in sys.path:
    sys.path.append(module_path)

This way, I just need to do relative imports within the project_path.py file, and not in the notebooks. The notebooks files would then just need to import project_path before importing lib. For example in 0.0-notebook.ipynb:

import project_path
import lib

The caveat here is that reversing the imports would not work. THIS DOES NOT WORK:

import lib
import project_path

Thus care must be taken during imports.

Invalid application of sizeof to incomplete type with a struct

Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

Where does linux store my syslog?

Default log location (rhel) are

General messages:

/var/log/messages

Authentication messages:

/var/log/secure

Mail events:

/var/log/maillog

Check your /etc/syslog.conf or /etc/syslog-ng.conf (it depends on which of syslog facility you have installed)

Example:

$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none         /var/log/messages

# The authpriv file has restricted access.
authpriv.*                             /var/log/secure

# Log all the mail messages in one place.
mail.*                                 /var/log/maillog

#For a start, use this simplified approach.
*.*                                     /var/log/messages

I get exception when using Thread.sleep(x) or wait()

Thread.sleep() is simple for the beginners and may be appropriate for unit tests and proofs of concept.

But please DO NOT use sleep() for production code. Eventually sleep() may bite you badly.

Best practice for multithreaded/multicore java applications to use the "thread wait" concept. Wait releases all the locks and monitors held by the thread, which allows other threads to acquire those monitors and proceed while your thread is sleeping peacefully.

Code below demonstrates that technique:

import java.util.concurrent.TimeUnit;
public class DelaySample {
    public static void main(String[] args) {
       DelayUtil d = new DelayUtil();
       System.out.println("started:"+ new Date());
       d.delay(500);
       System.out.println("half second after:"+ new Date());
       d.delay(1, TimeUnit.MINUTES); 
       System.out.println("1 minute after:"+ new Date());
    }
}

DelayUtil implementation:

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DelayUtil {
    /** 
    *  Delays the current thread execution. 
    *  The thread loses ownership of any monitors. 
    *  Quits immediately if the thread is interrupted
    *  
    * @param durationInMillis the time duration in milliseconds
    */
   public void delay(final long durationInMillis) {
      delay(durationInMillis, TimeUnit.MILLISECONDS);
   }

   /** 
    * @param duration the time duration in the given {@code sourceUnit}
    * @param unit
    */
    public void delay(final long duration, final TimeUnit unit) {
        long currentTime = System.currentTimeMillis();
        long deadline = currentTime+unit.toMillis(duration);
        ReentrantLock lock = new ReentrantLock();
        Condition waitCondition = lock.newCondition();

        while ((deadline-currentTime)>0) {
            try {
                lock.lockInterruptibly();    
                waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
            currentTime = System.currentTimeMillis();
        }
    }
}

About .bash_profile, .bashrc, and where should alias be written in?

The reason you separate the login and non-login shell is because the .bashrc file is reloaded every time you start a new copy of Bash. The .profile file is loaded only when you either log in or use the appropriate flag to tell Bash to act as a login shell.

Personally,

  • I put my PATH setup into a .profile file (because I sometimes use other shells);
  • I put my Bash aliases and functions into my .bashrc file;
  • I put this

    #!/bin/bash
    #
    # CRM .bash_profile Time-stamp: "2008-12-07 19:42"
    #
    # echo "Loading ${HOME}/.bash_profile"
    source ~/.profile # get my PATH setup
    source ~/.bashrc  # get my Bash aliases
    

    in my .bash_profile file.

Oh, and the reason you need to type bash again to get the new alias is that Bash loads your .bashrc file when it starts but it doesn't reload it unless you tell it to. You can reload the .bashrc file (and not need a second shell) by typing

source ~/.bashrc

which loads the .bashrc file as if you had typed the commands directly to Bash.

How to grab substring before a specified character jQuery or JavaScript

var streetaddress= addy.substr(0, addy.indexOf(',')); 

While it's not the best place for definitive information on what each method does (mozilla developer network is better for that) w3schools.com is good for introducing you to syntax.

Webpack.config how to just copy the index.html to the dist folder

To extend @hobbeshunter's answer if you want to take only index.html you can also use CopyPlugin, The main motivation to use this method over using other packages is because it's a nightmare to add many packages for every single type and config it etc. The easiest way is to use CopyPlugin for everything:

npm install copy-webpack-plugin --save-dev

Then

const CopyPlugin = require('copy-webpack-plugin');

module.exports = {
  plugins: [
    new CopyPlugin([
      { from: 'static', to: 'static' },
      { from: 'index.html', to: 'index.html', toType: 'file'},
    ]),
  ],
};

As you can see it copy the whole static folder along with all of it's content into dist folder. No css or file or any other plugins needed.

While this method doesn't suit for everything, it would get the job done simply & quickly.

How to set downloading file name in ASP.NET Web API

You need to add the content-disposition header to the response:

 response.StatusCode = HttpStatusCode.OK;
 response.Content = new StreamContent(result);
 response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
 return response;

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Why Would I Ever Need to Use C# Nested Classes

Maybe this is a good example of when to use nested classes?

// ORIGINAL
class ImageCacheSettings { }
class ImageCacheEntry { }
class ImageCache
{
    ImageCacheSettings mSettings;
    List<ImageCacheEntry> mEntries;
}

And:

// REFACTORED
class ImageCache
{
    Settings mSettings;
    List<Entry> mEntries;

    class Settings {}
    class Entry {}
}

PS: I've not taken into account which access modifiers should be applied (private, protected, public, internal)

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Above answers are excellent. You can look at the following full code example so that you could exactly know how to use

_x000D_
_x000D_
   var app = angular.module('hyperCrudApp', []);_x000D_
_x000D_
   app.controller('usersCtrl', function($scope, $http) {_x000D_
     $http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {_x000D_
        console.log(response.data)_x000D_
_x000D_
         $scope.users = response.data;_x000D_
          $scope.setKey = function (userId){_x000D_
              alert(userId)_x000D_
              if(localStorage){_x000D_
                localStorage.setItem("userId", userId)_x000D_
              } else {_x000D_
                alert("No support of localStorage")_x000D_
                return_x000D_
              }_x000D_
          }//function closed  _x000D_
     });_x000D_
   });
_x000D_
      #header{_x000D_
       color: green;_x000D_
       font-weight: bold;_x000D_
      }
_x000D_
  <!DOCTYPE html>_x000D_
  <html>_x000D_
  <head>_x000D_
    <title>HyperCrud</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
    <!-- NAVBAR STARTS -->_x000D_
      <nav class="navbar navbar-default navbar-fixed-top">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">HyperCrud</a>_x000D_
          </div>_x000D_
          <div id="navbar" class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="/">Home</a></li>_x000D_
              <li><a href="/about/">About</a></li>_x000D_
              <li><a href="/contact/">Contact</a></li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="/qAlarm/details/">qAlarm &raquo;</a></li>_x000D_
                  <li><a href="/YtEdit/details/">YtEdit &raquo;</a></li>_x000D_
                  <li><a href="/GWeather/details/">GWeather &raquo;</a></li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li><a href="/WadStore/details/">WadStore &raquo;</a></li>_x000D_
                  <li><a href="/chatsAll/details/">chatsAll</a></li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="/login/">Login</a></li>_x000D_
              <li><a href="/register/">Register</a></li>_x000D_
              <li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
      <!--NAVBAR ENDS-->_x000D_
  <br>_x000D_
  <br>_x000D_
_x000D_
  <div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">_x000D_
    <div class="row">_x000D_
     <div class="col-sm-12 col-md-12">_x000D_
      <center>_x000D_
        <h1 id="header"> Users </h1>_x000D_
      </center>_x000D_
     </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="row" >_x000D_
        <!--ITERATING USERS LIST-->_x000D_
      <div class="col-sm-6 col-md-4" ng-repeat="user in users">_x000D_
        <div class="thumbnail">_x000D_
          <center>_x000D_
           <img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">_x000D_
           <hr>_x000D_
          </center>_x000D_
          <div class="caption">_x000D_
           <center>_x000D_
             <h3>{{user.name}}</h3>_x000D_
             <p>{{user.email}}</p>_x000D_
             <p>+91 {{user.phone}}</p>_x000D_
             <p>{{user.address.city}}</p>_x000D_
            </center>_x000D_
          </div>_x000D_
            <div class="caption">_x000D_
                <a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>_x000D_
                <a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>_x000D_
            </div>_x000D_
        </div>_x000D_
      </div>_x000D_
_x000D_
        <div class="col-sm-6 col-md-4">_x000D_
          <div class="thumbnail">_x000D_
            <a href="/regiser/">_x000D_
             <img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
    </div>_x000D_
      <!--ROW ENDS-->_x000D_
  </div>_x000D_
_x000D_
_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

Shell script - remove first and last quote (") from a variable

I know this is a very old question, but here is another sed variation, which may be useful to someone. Unlike some of the others, it only replaces double quotes at the start or end...

echo "$opt" | sed -r 's/^"|"$//g'

Animate element to auto height with jQuery

IMO this is the cleanest and easiest solution:

$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );

Explanation: The DOM already knows from its initial rendering what size the expanded div will have when set to auto height. This property is stored in the DOM node as scrollHeight. We just have to fetch the DOM Element from the jQuery Element by calling get(0) and then we can access the property.

Adding a callback function to set the height to auto allows for greater responsiveness once the animation is complete (credit chris-williams):

$('#first').animate({
    height: $('#first').get(0).scrollHeight
}, 1000, function(){
    $(this).height('auto');
});

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

How to set the height and the width of a textfield in Java?

     f.setLayout(null);

add the above lines ( f is a JFrame or a Container where you have added the JTestField )

But try to learn 'LayoutManager' in java ; refer to other answers for the links of the tutorials .Or try This http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

String.Replace(char, char) method in C#

What about creating an Extension Method like this....

 public static string ReplaceTHAT(this string s)
 {
    return s.Replace("\n\r", "");
 }

And then when you want to replace that wherever you want you can do this.

s.ReplaceTHAT();

Best Regards!

How to stop event propagation with inline onclick attribute?

Use separate handler, say:

function myOnClickHandler(th){
//say let t=$(th)
}

and in html do this:

<...onclick="myOnClickHandler(this); event.stopPropagation();"...>

Or even :

function myOnClickHandler(e){
  e.stopPropagation();
}

for:

<...onclick="myOnClickHandler(event)"...>

Make an HTTP request with android

Look at this awesome new library which is available via gradle :)

build.gradle: compile 'com.apptakk.http_request:http-request:0.1.2'

Usage:

new HttpRequestTask(
    new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
    new HttpRequest.Handler() {
      @Override
      public void response(HttpResponse response) {
        if (response.code == 200) {
          Log.d(this.getClass().toString(), "Request successful!");
        } else {
          Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
        }
      }
    }).execute();

https://github.com/erf/http-request

Transform only one axis to log10 scale with ggplot2

I think I got it at last by doing some manual transformations with the data before visualization:

d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)

And work out a formatter to later compute 'back' the logarithmic data:

formatBack <- function(x) 10^x 
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ') 

And draw the plot with given formatter:

m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')

alt text

Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.

Anyway, thanks to @DWin for motivation!

What does it mean when Statement.executeUpdate() returns -1?

I haven't seen this anywhere, either, but my instinct would be that this means that the IF prevented the whole statement from executing.

Try to run the statement with a database where the IF passes.

Also check if there are any triggers involved which might change the result.

[EDIT] When the standard says that this function should never return -1, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.

If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF returns false and one where it returns true).

If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.

List attributes of an object

vars(obj) returns the attributes of an object.

psql: server closed the connection unexepectedly

If you are using Docker make sure you are not using the same port in another service, in my case i was mistakenly using the same port for both PostgreSQL and Redis.

Multiline strings in VB.NET

You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with

 Dim a = My.Resources.Whatever_you_chose

Does bootstrap have builtin padding and margin classes?

Bootstrap 5 has changed the ml,mr,pl,pr classes, which no longer work if you're upgrading from a lower version. The l and r have now been replaced with s(...which is confusing) and e(east?) respectively.

From bootstrap website:

Where property is one of:

  • m - for classes that set margin
  • p - for classes that set padding

Where sides is one of:

  • t - for classes that set margin-top or padding-top
  • b - for classes that set margin-bottom or padding-bottom
  • s - for classes that set margin-left or padding-left in LTR, margin-right or padding-right in RTL
  • e - for classes that set margin-right or padding-right in LTR, margin-left or padding-left in RTL
  • x - for classes that set both *-left and *-right
  • y - for classes that set both *-top and *-bottom blank - for classes that set a margin or padding on all 4 sides of the element Where size is one of:

0 - for classes that eliminate the margin or padding by setting it to 0 1 - (by default) for classes that set the margin or padding to $spacer * .25 2 - (by default) for classes that set the margin or padding to $spacer * .5 3 - (by default) for classes that set the margin or padding to $spacer 4 - (by default) for classes that set the margin or padding to $spacer * 1.5 5 - (by default) for classes that set the margin or padding to $spacer * 3 auto - for classes that set the margin to auto (You can add more sizes by adding entries to the $spacers Sass map variable.)

How to utilize date add function in Google spreadsheet?

You can just add the number to the cell with the date.

so if A1: 12/3/2012 and A2: =A1+7 then A2 would display 12/10/2012

Remove an entire column from a data.frame in R

The posted answers are very good when working with data.frames. However, these tasks can be pretty inefficient from a memory perspective. With large data, removing a column can take an unusually long amount of time and/or fail due to out of memory errors. Package data.table helps address this problem with the := operator:

library(data.table)
> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
     b c
[1,] 1 1

I should put together a bigger example to show the differences. I'll update this answer at some point with that.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

Watching variables in SSIS during debug

I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

Count number of rows per group and add result to original data frame

You can use ave:

df$count <- ave(df$num, df[,c("name","type")], FUN=length)

How should I log while using multiprocessing in Python?

Yet another alternative might be the various non-file-based logging handlers in the logging package:

  • SocketHandler
  • DatagramHandler
  • SyslogHandler

(and others)

This way, you could easily have a logging daemon somewhere that you could write to safely and would handle the results correctly. (E.g., a simple socket server that just unpickles the message and emits it to its own rotating file handler.)

The SyslogHandler would take care of this for you, too. Of course, you could use your own instance of syslog, not the system one.

Get the first element of an array

Use array_keys() to access the keys of your associative array as a numerical indexed array, which is then again can be used as key for the array.

When the solution is arr[0]:

(Note, that since the array with the keys is 0-based index, the 1st element is index 0)

You can use a variable and then subtract one, to get your logic, that 1 => 'apple'.

$i = 1;
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[$i-1]];

Output:

apple

Well, for simplicity- just use:

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[0]];

Output:

apple

By the first method not just the first element, but can treat an associative array like an indexed array.

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

How do I set adaptive multiline UILabel text?

This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.

No sizeToFit, preferredMaxLayoutWidth used

Below is how it will work.

enter image description here

Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:

enter image description here

Set the Label properties as below image:

enter image description here

Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton

enter image description here

Now set the priority of the trailing constraint of UILabel as 749

enter image description here

Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748

enter image description here

Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]


@IBAction func updateLabelText(sender: UIButton) {
    if count > 3 {
        count = 0
    }
    textLabel.text = items[count]
    count = count + 1
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //self.textLabel.sizeToFit()
    //self.textLabel.preferredMaxLayoutWidth = 500
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.

Android - running a method periodically using postDelayed() call

Why don't you create service and put logic in onCreate(). In this case even if you press back button service will keep on executing. and once you enter into application it will not call onCreate() again. Rather it will call onStart()

How to insert a string which contains an "&"

I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.

Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.

SET DEFINE OFF will stop sqlplus interpreting & this way.

But what if you need to use sqlplus variables and literal & characters?

  • You need SET DEFINE ON to make variables work
  • And SET ESCAPE ON to escape uses of &.

e.g.

set define on
set escape on

define myvar=/forth

select 'back\\ \& &myvar' as swing from dual;

Produces:

old   1: select 'back\\ \& &myvar' from dual
new   1: select 'back\ & /forth' from dual

SWING
--------------
back\ & /forth

If you want to use a different escape character:

set define on
set escape '#'

define myvar=/forth

select 'back\ #& &myvar' as swing from dual;

When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:

set escape off
set escape '#'

How can I show three columns per row?

This may be what you are looking for:

http://jsfiddle.net/L4L67/

_x000D_
_x000D_
body>div {_x000D_
  background: #aaa;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
  flex-grow: 1;_x000D_
  width: 33%;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
  background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
  background: #49b;_x000D_
}
_x000D_
<div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I measure the similarity between two images?

Well, not to answer your question directly, but I have seen this happen. Microsoft recently launched a tool called PhotoSynth which does something very similar to determine overlapping areas in a large number of pictures (which could be of different aspect ratios).

I wonder if they have any available libraries or code snippets on their blog.

Spring cron expression for every after 30 minutes

According to the Quartz-Scheduler Tutorial It should be value="0 0/30 * * * ?"

The field order of the cronExpression is

1.Seconds

2.Minutes

3.Hours

4.Day-of-Month

5.Month

6.Day-of-Week

7.Year (optional field)

Ensure you have at least 6 parameters or you will get an error (year is optional)

What is the difference between And and AndAlso in VB.NET?

If Bool1 And Bool2 Then

Evaluates both Bool1 and Bool2

If Bool1 AndAlso Bool2 Then

Evaluates Bool2 if and only if Bool1 is true.

MassAssignmentException in Laravel

Read this section of Laravel doc : http://laravel.com/docs/eloquent#mass-assignment

Laravel provides by default a protection against mass assignment security issues. That's why you have to manually define which fields could be "mass assigned" :

class User extends Model
{
    protected $fillable = ['username', 'email', 'password'];
}

Warning : be careful when you allow the mass assignment of critical fields like password or role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

Disabling of EditText in Android

Use this to disable user input

android:focusable="false"

android:editable="false" This method is deprecated one.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

What is the significance of load factor in HashMap?

I would pick a table size of n * 1.5 or n + (n >> 1), this would give a load factor of .66666~ without division, which is slow on most systems, especially on portable systems where there is no division in the hardware.

Switch on Enum in Java

You actually can switch on enums, but you can't switch on Strings until Java 7. You might consider using polymorphic method dispatch with Java enums rather than an explicit switch. Note that enums are objects in Java, not just symbols for ints like they are in C/C++. You can have a method on an enum type, then instead of writing a switch, just call the method - one line of code: done!

enum MyEnum {
    SOME_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("first enum constant behavior!");
        }
    },
    ANOTHER_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("second enum constant behavior!");
        }
    }; // note the semi-colon after the final constant, not just a comma!
    public abstract void method(); // could also be in an interface that MyEnum implements
}

void aMethodSomewhere(final MyEnum e) {
    doSomeStuff();
    e.method(); // here is where the switch would be, now it's one line of code!
    doSomeOtherStuff();
}

Code-first vs Model/Database-first

Quoting the relevant parts from http://www.itworld.com/development/405005/3-reasons-use-code-first-design-entity-framework

3 reasons to use code first design with Entity Framework

1) Less cruft, less bloat

Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code. You’re implored never to touch these generated files lest you break something, or your changes get overwritten on the next generation. The context and initializer are jammed together in this mess as well. When you need to add functionality to your generated models, like a calculated read only property, you need to extend the model class. This ends up being a requirement for almost every model and you end up with an extension for everything.

With code first your hand coded models become your database. The exact files that you’re building are what generate the database design. There are no additional files and there is no need to create a class extension when you want to add properties or whatever else that the database doesn't need to know about. You can just add them into the same class as long as you follow the proper syntax. Heck, you can even generate a Model.edmx file to visualize your code if you want.

2) Greater Control

When you go DB first, you’re at the mercy of what gets generated for your models for use in your application. Occasionally the naming convention is undesirable. Sometimes the relationships and associations aren't quite what you want. Other times non transient relationships with lazy loading wreak havoc on your API responses.

While there is almost always a solution for model generation problems you might run into, going code first gives you complete and fine grained control from the get go. You can control every aspect of both your code models and your database design from the comfort of your business object. You can precisely specify relationships, constraints, and associations. You can simultaneously set property character limits and database column sizes. You can specify which related collections are to be eager loaded, or not be serialized at all. In short, you are responsible for more stuff but you’re in full control of your app design.

3)Database Version Control

This is a big one. Versioning databases is hard, but with code first and code first migrations, it’s much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database. You’re responsible for controlling your context initialization which can help you do things like seed fixed business data. You’re also responsible for creating code first migrations.

When you first enable migrations, a configuration class and an initial migration are generated. The initial migration is your current schema or your baseline v1.0. From that point on you will add migrations which are timestamped and labeled with a descriptor to help with ordering of versions. When you call add-migration from the package manager, a new migration file will be generated containing everything that has changed in your code model automatically in both an UP() and DOWN() function. The UP function applies the changes to the database, the DOWN function removes those same changes in the event you want to rollback. What’s more, you can edit these migration files to add additional changes such as new views, indexes, stored procedures, and whatever else. They will become a true versioning system for your database schema.

How to display an activity indicator with text on iOS 8 with Swift?

Xcode 9.0 • Swift 4.0


import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var filterButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!
    let destinationUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        .appendingPathComponent("filteredImage.png")
    let imagePicker = UIImagePickerController()
    let messageFrame = UIView()
    var activityIndicator = UIActivityIndicatorView()
    var strLabel = UILabel()
    let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    func activityIndicator(_ title: String) {
        strLabel.removeFromSuperview()
        activityIndicator.removeFromSuperview()
        effectView.removeFromSuperview()
        strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
        strLabel.text = title
        strLabel.font = .systemFont(ofSize: 14, weight: .medium)
        strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
        effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
        effectView.layer.cornerRadius = 15
        effectView.layer.masksToBounds = true
        activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
        activityIndicator.startAnimating()
        effectView.contentView.addSubview(activityIndicator)
        effectView.contentView.addSubview(strLabel)
        view.addSubview(effectView)
    }
    func saveImage() {
        do {
            try imageView.image?.data?.write(to: destinationUrl, options: .atomic)
            print("file saved")
        } catch {
            print(error)
        }
    }        
    func applyFilterToImage() {
        imageView.image = imageView.image?.applying(contrast: 1.5)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a8/VST_images_the_Lagoon_Nebula.jpg"), let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
        view.backgroundColor = UIColor(white: 0, alpha: 1)
        imageView.image = image
    }
    @IBAction func startSavingImage(_ sender: AnyObject) {
        saveButton.isEnabled = false
        filterButton.isEnabled = false
        activityIndicator("Saving Image")
        DispatchQueue.main.async {
            self.saveImage()
            DispatchQueue.main.async {
                self.effectView.removeFromSuperview()
                self.saveButton.isEnabled = true
                self.filterButton.isEnabled = true
            }
        }
    }
    @IBAction func filterAction(_ sender: AnyObject) {
        filterButton.isEnabled = false
        saveButton.isEnabled = false
        activityIndicator("Applying Filter")
        DispatchQueue.main.async {
            self.applyFilterToImage()
            DispatchQueue.main.async {
                self.effectView.removeFromSuperview()
                self.filterButton.isEnabled = true
                self.saveButton.isEnabled = true
            }
        }
    }
    @IBAction func cameraAction(_ sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            present(imagePicker, animated: true)
        }
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
        dismiss(animated: true, completion: nil)
        imageView.image = image
    }
}

extension Data {
    var image: UIImage? { return UIImage(data: self) }
}

extension UIImage {
    var data: Data? { return UIImagePNGRepresentation(self) }
    func applying(contrast value: NSNumber) -> UIImage? {
        guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: value]) else { return nil }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }
        UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

Get timezone from users browser using moment(timezone).js

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

How to remove duplicate values from a multi-dimensional array in PHP

I've given this problem a lot of thought and have determined that the optimal solution should follow two rules.

  1. For scalability, modify the array in place; no copying to a new array
  2. For performance, each comparison should be made only once

With that in mind and given all of PHP's quirks, below is the solution I came up with. Unlike some of the other answers, it has the ability to remove elements based on whatever key(s) you want. The input array is expected to be numeric keys.

$count_array = count($input);
for ($i = 0; $i < $count_array; $i++) {
    if (isset($input[$i])) {
        for ($j = $i+1; $j < $count_array; $j++) {
            if (isset($input[$j])) {
                //this is where you do your comparison for dupes
                if ($input[$i]['checksum'] == $input[$j]['checksum']) {
                    unset($input[$j]);
                }
            }
        }
    }
}

The only drawback is that the keys are not in order when the iteration completes. This isn't a problem if you're subsequently using only foreach loops, but if you need to use a for loop, you can put $input = array_values($input); after the above to renumber the keys.

Best way to determine user's locale within browser

There's a difference between the user's preferred languages and the system/browser locale.

A user can configure preferred languages in the browser, and these will be used for navigator.language(s), and used when requesting resources from a server, to request content according to a list of language priorities.

However, the browser locale will decide how to render number, date, time and currency. This setting is likely the highest ranking language, but there is no guarantee. On Mac and Linux, the locale is decided by the system regardless of the user language preferences. On Windows is can be elected among the languages in the preferred list on Chrome.

By using Intl (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), developers can override/set the locale to use to render these things, but there are elements that cannot be overridden, such as the <input type="date"> format.

To properly extract this language, the only way I've found is:

(new Intl.NumberFormat()).resolvedOptions().locale

(Intl.NumberFormat().resolvedOptions().locale also seems to work)

This will create a new NumberFormat instance for the default locale and then reading back the locale of those resolved options.

Predicate in Java

A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:

public interface Predicate<ARGTYPE>
{
    public boolean evaluate(ARGTYPE arg);
}

And then you might have an implementation such as:

public class Tautology<E> implements Predicate<E>
{
     public boolean evaluate(E arg){
         return true;
     }
}

To get a better conceptual understanding, you might want to read about first-order logic.

Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.

Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true to a function instead of defining a named Tautology subclass like the above.

PHP: date function to get month of the current date

To compare with an int do this:

<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
    echo "They are the same";
}
?>

How do I get a decimal value when using the division operator in Python?

You cant get a decimal value by dividing one integer with another, you'll allways get an integer that way (result truncated to integer). You need at least one value to be a decimal number.

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

How do I copy items from list to list without foreach?

Easy to map different set of list by linq without for loop

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

How to add a margin to a table row <tr>

Here's a neat way I did it:

table tr {
    border-bottom: 4px solid;
}

That will add 4px of vertical spacing between each row. And if you wanted to not get that border on the last child:

table tr:last-child {
    border-bottom: 0;
}

Reminder that CSS3 pseudo-selectors will only work in IE 8 and below with selectivizr.

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

Pip - Fatal error in launcher: Unable to create process using '"'

For me it was an error in my path. You should directly call the script using the directory where it is stored.

C:\Users\YourUserName\AppData\Local\Programs\Python\Python36\Scripts\pip install requests

And for running python scripts you can do this:

C:\Users\Avanish\AppData\Local\Programs\Python\Python36\python -m pip install requests

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

//convert UTF-8 file without BOM to UTF-16LE for excel on mac
$fileUtf8String = file_get_contents("file.ext");
file_put_contents("file.ext", "\xFF\xFE" . mb_convert_encoding($fileUtf8String, "UTF-16LE", "UTF-8"));

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

You can try "SelectedIndexChanged", it will trigger the event even if the same item is selected.

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

while EOF in JAVA?

The problem is that you're reading nextLine() on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:

File:

Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something

On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah, printed to the System.

The process will repeat with Sincerely, being consumed and Capnstank printing out.

Finally the while will consume the "PS" line while the String line = fileReader.nextLine() retreives an exception from the file because there's nothing further to read.

To resolve the issue:

String line = fileReader.nextLine();

while (line != null) {
  System.out.println(line);
  line = fileReader.nextLine();
}

How do I change the default application icon in Java?

Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.

com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );

That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.

Ant error when trying to build file, can't find tools.jar?

I found that even though my path is set to JDK, the ant wants the tools.jar from jre folder. So just copy paste the tools.jar folder from JDK to jre.

Get form data in ReactJS

I use like this using React Component state:

<input type="text" name='value' value={this.state.value} onChange={(e) => this.handleChange(e)} />

handleChange(e){
   this.setState({[e.target.name]: e.target.value})
}`

Manually map column names with class properties

for all of you who use Dapper 1.12, Here's what you need to do to get this done:

  • Add a new column attribute class:

      [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property]
    
      public class ColumnAttribute : Attribute
      {
    
        public string Name { get; set; }
    
        public ColumnAttribute(string name)
        {
          this.Name = name;
        }
      }
    

  • Search for this line:

    map = new DefaultTypeMap(type);
    

    and comment it out.

  • Write this instead:

            map = new CustomPropertyTypeMap(type, (t, columnName) =>
            {
              PropertyInfo pi = t.GetProperties().FirstOrDefault(prop =>
                                prop.GetCustomAttributes(false)
                                    .OfType<ColumnAttribute>()
                                    .Any(attr => attr.Name == columnName));
    
              return pi != null ? pi : t.GetProperties().FirstOrDefault(prop => prop.Name == columnName);
            });
    

  • Why "no projects found to import"?

    if you are building a maven project through a command console, make sure the following is at the end of the command:

    eclipse:eclipse -Dwtpversion=2.0
    

    Why does checking a variable against multiple values with `OR` only check the first value?

    If you want case-insensitive comparison, use lower or upper:

    if name.lower() == "jesse":
    

    "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

    Read carefully the warning message :

    The POM for org.raml:jaxrs-code-generator:jar:2.0.0 is missing, no dependency information available

    The problem is not the jar, but the pom.xml that is missing.
    The pom.xml lists the required dependencies for this jar that Maven will pull during the build and overall the packaging of your application. So, you may really need it.

    Note that this problem may of course occur for other Maven dependencies and the ideas to solve that is always the same.

    The Mule website documents very well that in addition to some information related to.


    How to solve ?

    1) Quick workaround : looking for in the internet the pom.xml of the artifact

    Googling the artifact id, the group id and its version gives generally interesting results : maven repository links to download it.
    In the case of the org.raml:jaxrs-code-generator:jar:2.0.0 dependency, you can download the pom.xml from the Maven mule repository :

    https://repository.mulesoft.org/nexus/content/repositories/releases/org/raml/jaxrs-code-generator/2.0.0/

    2) Clean workaround for a single Maven project : adding the repository declaration in your pom.

    In your case, add the Maven mule repositories :

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        ...
        <repositories>
            <repository>
                <id>mulesoft-releases</id>
                <name>MuleSoft Repository</name>
                <url>http://repository.mulesoft.org/releases/</url>
                <layout>default</layout>
            </repository>
            <repository>
                <id>mulesoft-snapshots</id>
                <name>MuleSoft Snapshot Repository</name>
                <url>http://repository.mulesoft.org/snapshots/</url>
                <layout>default</layout>
            </repository>
        </repositories>
        ...
    </project>
    

    3) Clean workaround for any Maven projects : add the repository declaration in your settings.xml

     <profile> 
       <repositories>
        ...
        <repository>
          <id>mulesoft-releases</id>
          <name>MuleSoft Repository</name>
          <url>http://repository.mulesoft.org/releases/</url>
          <layout>default</layout>
        </repository>
        <repository>
          <id>mulesoft-snapshots</id>
          <name>MuleSoft Snapshot Repository</name>
          <url>http://repository.mulesoft.org/snapshots/</url>
          <layout>default</layout>
        </repository>
         ...
      </repositories>     
    </profile>
    

    Note that in some rare cases, the pom.xml declaring the dependencies is nowhere. So, you have to identify yourself whether the artifact requires dependencies.

    How do I join two SQLite tables in my Android application?

    In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this

    SELECT * FROM expense INNER JOIN refuel
    ON exp_id = expense_id
    WHERE refuel_id = 1
    

    via raw query like this -

    String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
            + " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
            + " WHERE " + RefuelTable.ID + " = " +  id;
    Cursor c = db.rawQuery(
            rawQuery,
            null
    );
    

    because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -

    SELECT *
    FROM expense, refuel
    WHERE exp_id = expense_id AND refuel_id = 1
    

    and hence be able to take advanatage of the SQLiteDatabase.query() helper method

    Cursor c = db.query(
            RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
            Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
            RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " +  id,
            null,
            null,
            null,
            null
    );
    

    For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery

    Initialise numpy array of unknown length

    Since y is an iterable I really do not see why the calls to append:

    a = np.array(list(y))
    

    will do and it's much faster:

    import timeit
    
    print timeit.timeit('list(s)', 's=set(x for x in xrange(1000))')
    # 23.952975494633154
    
    print timeit.timeit("""li=[]
    for x in s: li.append(x)""", 's=set(x for x in xrange(1000))')
    # 189.3826994248866
    

    Five equal columns in twitter bootstrap

    Just create a new class and define its behaviour per each each media query as needed

    @media(min-width: 768px){
      .col-1-5{
        width: 20%;
        float: left;
        position: relative;
        min-height: 1px;
        padding-right: 5px;
        padding-left: 5px;
      }
    }
    
    <div class="container-fluid">
      <div class="row">
        <div class="col-1-5">col 1</div>
        <div class="col-1-5">col 2</div>
        <div class="col-1-5">col 3</div>
        <div class="col-1-5">col 4</div>
        <div class="col-1-5">col 5</div>
      </div>
    </div>
    

    here is a working demo https://codepen.io/giorgosk/pen/BRVorW

    Difference between clean, gradlew clean

    1. ./gradlew clean

      Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

    2. ./gradlew clean assembleDebug

      Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

    3. ./gradlew clean :assembleDebug

      Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

    4. Android Studio --> Build --> Clean

      Is essentially the same as ./gradlew clean. See here.

    For more info, I suggest taking the time to read through the Android docs, especially this one.

    How do you UrlEncode without using System.Web?

    Here's an example of sending a POST request that properly encodes parameters using application/x-www-form-urlencoded content type:

    using (var client = new WebClient())
    {
        var values = new NameValueCollection
        {
            { "param1", "value1" },
            { "param2", "value2" },
        };
        var result = client.UploadValues("http://foo.com", values);
    }
    

    How exactly does __attribute__((constructor)) work?

    1. It runs when a shared library is loaded, typically during program startup.
    2. That's how all GCC attributes are; presumably to distinguish them from function calls.
    3. GCC-specific syntax.
    4. Yes, this works in C and C++.
    5. No, the function does not need to be static.
    6. The destructor runs when the shared library is unloaded, typically at program exit.

    So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

    Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

    How do I block comment in Jupyter notebook?

    Select the lines you want to comment out. Then press:

    Ctrl + #

    How to run docker-compose up -d at system start up?

    If your docker.service enabled on system startup

    $ sudo systemctl enable docker
    

    and your services in your docker-compose.yml has

    restart: always
    

    all of the services run when you reboot your system if you run below command only once

    docker-compose up -d
    

    "multiple target patterns" Makefile error

    I just want to add, if you get this error because you are using Cygwin make and auto-generated files, you can fix it with the following sed,

    sed -e 's@\\\([^ ]\)@/\1@g' -e 's@[cC]:@/cygdrive/c@' -i filename.d
    

    You may need to add more characters than just space to the escape list in the first substitution but you get the idea. The concept here is that /cygdrive/c is an alias for c: that cygwin's make will recognize.

    And may as well throw in

    -e 's@^ \+@\t@'
    

    just in case you did start with spaces on accident (although I /think/ this will usually be a "missing separator" error).

    WRONGTYPE Operation against a key holding the wrong kind of value php

    I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

    $redis->set('persons', $persons)
    

    Later I decided to change to "hSet" method, and I tried it this way

    foreach($persons as $person){
        $redis->hSet('persons', $person->id, $person);
    }
    

    Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

    del persons
    

    It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

    Convert .pfx to .cer

    If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:

    Get-PfxCertificate -FilePath InputBundle.pfx | 
    Export-Certificate -FilePath OutputCert.der -Type CERT
    

    Newline added for clarity, but you can of course have this all on a single line.

    If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem

    If you need to export to a different format than DER encoded, you can change the -Type parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed:

    -Type <CertType>
        Specifies the type of output file for the certificate export as follows. 
         -- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates. 
         -- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate. 
         -- P7B: A PKCS#7 file format which can contain one or more certificates.
    

    Line Break in XML formatting?

    Use \n for a line break and \t if you want to insert a tab.

    You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text.

    Other formatting options are shown in this article on the Android Developers' site:
    https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling