Programs & Examples On #Bitstream

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

How do I run a batch script from within a batch script?

You can use

call script.bat

or just

script.bat

what is the use of xsi:schemaLocation?

According to the spec for locating Schemas

there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy

(thanks for being unambiguous, spec!)

and

in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.

So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation attribute), depending on your "community." If you specify a specific schemaLocation, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation or noNamespaceSchemaLocation attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).

Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd" typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd (so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.

How to run SQL in shell script

Code

PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"

OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
           select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";

Explanation:

PL_CONNECT_STRING carry database username, password and it service name

sqlplus is used to connect the Database with PL_CONNECT_STRING details

END-OF-SQL tag contain the query which you want to execute

echo is used to print the output of the query

NOTE: You can give multiple Query inside the END-OF-SQL tag, so its useful for batch execution as well

Add hover text without javascript like we hover on a user's reputation

This can also be done in CSS, for more customisability:

_x000D_
_x000D_
.hoverable {
  position: relative;
}

.hoverable>.hoverable__tooltip {
  display: none;
}

.hoverable:hover>.hoverable__tooltip {
  display: inline;
  position: absolute;
  top: 1em;
  left: 1em;
  background: #888;
  border: 1px solid black;
}
_x000D_
<div class="hoverable">
  <span class="hoverable__main">Main text</span>
  <span class="hoverable__tooltip">Hover text</span>
</div>
_x000D_
_x000D_
_x000D_

(Obviously, styling can be improved)

How to use comparison operators like >, =, < on BigDecimal

Use the compareTo method of BigDecimal :

public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.

Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

how to set background image in submit button?

i do it like this cover button and the middle image that

<button><img src="foldername/imagename" width="30px" height= "30px"></button>

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

PowerShell : retrieve JSON object by field value

$json = @"
{
"Stuffs": 
    [
        {
            "Name": "Darts",
            "Type": "Fun Stuff"
        },

        {
            "Name": "Clean Toilet",
            "Type": "Boring Stuff"
        }
    ]
}
"@

$x = $json | ConvertFrom-Json

$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts

can you add HTTPS functionality to a python flask web server?

For a quick n' dirty self-signed cert, you can also use flask run --cert adhoc or set the FLASK_RUN_CERT env var.

$ export FLASK_APP="app.py"
$ export FLASK_ENV=development
$ export FLASK_RUN_CERT=adhoc

$ flask run
 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 329-665-000

The adhoc option isn't well documented (for good reason, never do this in production), but it's mentioned in the cli.py source code.

There's a thorough explanation of this by Miguel Grinberg at Running Your Flask Application Over HTTPS.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

While installation of Tortoise SVN.

Just change the command line svn tool setting.

Step 1: Click on command line client tools

enter image description here

Step 2: Select first option (Will be installed on local hard drive)

enter image description here

Thats it. Happy Journey.

[N.B: Images are copied from others solution]

Checking for duplicate strings in JavaScript array

This is the simplest solution I guess :

function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

List all indexes on ElasticSearch server?

I use the _stats/indexes endpoint to get a json blob of data and then filter with jq.

curl 'localhost:9200/_stats/indexes' | jq '.indices | keys | .[]'

"admin"
"blazeds"
"cgi-bin"
"contacts_v1"
"flex2gateway"
"formmail"
"formmail.pl"
"gw"
...

If you don't want quotes, add a -r flag to jq.

Yes, the endpoint is indexes and the data key is indices, so they couldn't make up their minds either :)

I needed this to clean up these garbage indices created by an internal security scan (nessus).

PS. I highly recommend getting familiar with jq if you're going to interact with ES from the command line.

Can't access Tomcat using IP address

Firewalls are often the problem in these situations. Personally, the Mcafee enterprise firewall was causing this issue even for requests within the network.

Disable your firewalls or add a rule for tomcat and see if this helps.

Sum columns with null values in oracle

select type, craft, sum(nvl(regular,0) + nvl(overtime,0)) as total_hours
from hours_t
group by type, craft
order by type, craft

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

As @fijaaron says,

  1. GRANT ALL does not imply GRANT FILE
  2. GRANT FILE only works with *.*

So do

GRANT FILE ON *.* TO user;

How to sort ArrayList<Long> in decreasing order?

Java 8

well doing this in java 8 is so much fun and easier

Collections.sort(variants,(a,b)->a.compareTo(b));
Collections.reverse(variants);

Lambda expressions rock here!!!

in case you needed a more than one line logic for comparing a and b you could write it like this

Collections.sort(variants,(a,b)->{
    int result = a.compareTo(b);
    return result;
});

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

Reverse a string without using reversed() or [::-1]?

reduce(lambda x, y : y + x, "hello world")

Pass variables by reference in JavaScript

Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.

The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...

function action(){
  /* Process this.arg, modification allowed */
}

action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();

You can also promise stuff up to enjoy the well-known chain: Here is the whole thing, with promise-like structure

function action(){
  /* Process this.arg, modification allowed */
  this.arg = ["a", "b"];
}

action.setArg = function(){this.arg = arguments; return this;}

action.setArg(["empty-array"], "some string", 0x100, "last argument")()

Or better yet...

action.setArg(["empty-array"],"some string",0x100,"last argument").call()

How to cancel a local git commit

Just use git reset without the --hard flag:

git reset HEAD~1

PS: On Unix based systems you can use HEAD^ which is equal to HEAD~1. On Windows HEAD^ will not work because ^ signals a line continuation. So your command prompt will just ask you More?.

JQuery Validate input file type

Simply use the .rules('add') method immediately after creating the element...

var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");

    // declare the rule on this newly created input field        
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});
  • You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

  • You'll still need to declare rules for your static elements using .validate(). Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

  • You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

  • You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add'). For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".

Working DEMO: http://jsfiddle.net/8dAU8/5/

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Firstly you can find duplicate rows and find count of rows is used how many times and order it by number like this;

_x000D_
_x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

after that create a table and insert result to it.

_x000D_
_x000D_
create table CopyTable _x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
  CASE q.NID_x000D_
  WHEN @curCode THEN_x000D_
   @curRow := @curRow + 1_x000D_
  ELSE_x000D_
   @curRow := 1_x000D_
  AND @curCode := q.NID_x000D_
  END_x000D_
 ) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
  SELECT_x000D_
   @curRow := 1,_x000D_
   @curCode := ''_x000D_
 ) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
    SELECT NID_x000D_
    FROM UserInfo_x000D_
    GROUP BY NID_x000D_
    HAVING COUNT(*) > 1_x000D_
) 
_x000D_
_x000D_
_x000D_

Finally, delete dublicate rows.No is start 0. Except fist number of each group delete all dublicate rows.

_x000D_
_x000D_
delete from  CopyTable where No!= 0;
_x000D_
_x000D_
_x000D_

What is the reason for having '//' in Python?

To complement these other answers, the // operator also offers significant (3x) performance benefits over /, presuming you want integer division.

$ python -m timeit '20.5 // 2'
100,000,000 loops, best of 3: 14.9 nsec per loop

$ python -m timeit '20.5 / 2'
 10,000,000 loops, best of 3: 48.4 nsec per loop

$ python -m timeit '20 / 2'
 10,000,000 loops, best of 3: 43.0 nsec per loop

$ python -m timeit '20 // 2'
100,000,000 loops, best of 3: 14.4 nsec per loop

python .replace() regex

For this particular case, if using re module is overkill, how about using split (or rsplit) method as

se='</html>'
z.write(article.split(se)[0]+se)

For example,

#!/usr/bin/python

article='''<html>Larala
Ponta Monta 
</html>Kurimon
Waff Moff
'''
z=open('out.txt','w')

se='</html>'
z.write(article.split(se)[0]+se)

outputs out.txt as

<html>Larala
Ponta Monta 
</html>

Parse XLSX with Node and create json

**podria ser algo asi en react y electron**

 xslToJson = workbook => {
        //var data = [];
        var sheet_name_list = workbook.SheetNames[0];
        return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
            raw: false,
            dateNF: "DD-MMM-YYYY",
            header:1,
            defval: ""
        });
    };

    handleFile = (file /*:File*/) => {
        /* Boilerplate to set up FileReader */
        const reader = new FileReader();
        const rABS = !!reader.readAsBinaryString;

        reader.onload = e => {
            /* Parse data */
            const bstr = e.target.result;
            const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
            /* Get first worksheet */
            let arr = this.xslToJson(wb);

            console.log("arr ", arr)
            var dataNueva = []

            arr.forEach(data => {
                console.log("data renaes ", data)
            })
            // this.setState({ DataEESSsend: dataNueva })
            console.log("dataNueva ", dataNueva)

        };


        if (rABS) reader.readAsBinaryString(file);
        else reader.readAsArrayBuffer(file);
    };

    handleChange = e => {
        const files = e.target.files;
        if (files && files[0]) {
            this.handleFile(files[0]);
        }
    };

How to initialize private static members in C++?

You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...

class Foo
   {
   public:
     int GetMyStatic() const
     {
       return *MyStatic();
     }

   private:
     static int* MyStatic()
     {
       static int mStatic = 0;
       return &mStatic;
     }
   }

The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.

Fast way of finding lines in one file that are not in another?

Using of fgrep or adding -F option to grep could help. But for faster calculations you could use Awk.

You could try one of these Awk methods:

http://www.linuxquestions.org/questions/programming-9/grep-for-huge-files-826030/#post4066219

How can I check the size of a file in a Windows batch script?

I prefer to use a DOS function. Feels cleaner to me.

SET SIZELIMIT=1000
CALL :FileSize %1 FileSize
IF %FileSize% GTR %SIZELIMIT% Echo Large file

GOTO :EOF

:FileSize
SET %~2=%~z1

GOTO :EOF

How do I hide an element on a click event anywhere outside of the element?

$('html').click(function() {
//Hide the menus if it is visible
});

$('#menu_container').click(function(event){
    event.stopPropagation();
});

but you need to keep in mind these things as well. http://css-tricks.com/dangers-stopping-event-propagation/

How to include External CSS and JS file in Laravel 5

Laravel 5.5 comes with mix , the replacement for Elixir, the external css(sass) can be extracted to resources/assets/css(sass) and import to app.css(scss) or give the correct path to your node_module folder that contains the library and can be used as

<link rel="stylesheet" href="{{ mix('css/app.css') }}" >

The same can be done for Javascript too .

How to retrieve field names from temporary table (SQL Server 2008)

Anthony

try the below one. it will give ur expected output

select c.name as Fields from 
tempdb.sys.columns c
    inner join tempdb.sys.tables t
 ON c.object_id = t.object_id
where t.name like '#MyTempTable%'

How to use a dot "." to access members of dictionary?

Use SimpleNamespace:

>>> from types import SimpleNamespace   
>>> d = dict(x=[1, 2], y=['a', 'b'])
>>> ns = SimpleNamespace(**d)
>>> ns.x
[1, 2]
>>> ns
namespace(x=[1, 2], y=['a', 'b'])

deleting rows in numpy array

Here's a one liner (yes, it is similar to user333700's, but a little more straightforward):

>>> import numpy as np
>>> arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], 
                [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]])
>>> print arr[arr.all(1)]
array([[ 0.96488889,  0.73641667,  0.67521429,  0.592875  ,  0.53172222]])

By the way, this method is much, much faster than the masked array method for large matrices. For a 2048 x 5 matrix, this method is about 1000x faster.

By the way, user333700's method (from his comment) was slightly faster in my tests, though it boggles my mind why.

How to get the new value of an HTML input after a keypress has modified it?

There are two kinds of input value: field's property and field's html attribute.

If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

Quick Sort Vs Merge Sort

The answer would slightly tilt towards quicksort w.r.t to changes brought with DualPivotQuickSort for primitive values . It is used in JAVA 7 to sort in java.util.Arrays

It is proved that for the Dual-Pivot Quicksort the average number of
comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n),
whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n)
respectively. Full mathematical proof see in attached proof.txt
and proof_add.txt files. Theoretical results are also confirmed
by experimental counting of the operations.

You can find the JAVA7 implmentation here - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Arrays.java

Further Awesome Reading on DualPivotQuickSort - http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628

jQuery - Increase the value of a counter when a button is clicked

You cannot use ++ on something which is not a variable, this would be the closest you can get:

$('#counter').html(function(i, val) { return +val+1 });

jQuery's html() method can get and set the HTML value of an element. If passed a function it can update the HTML based upon the existing value. So in the context of your code:

$("#update").click(function() {
    $('#counter').html(function(i, val) { return +val+1 });
}

DEMO: http://jsfiddle.net/marcuswhybrow/zRX2D/2/

When it comes to synchronising your counter on the page, with the counter value in your database, never trust the client! You send either an increment or decrement signal to you server side script, rather than a continuous value such as 10, or 23.

However you could send an AJAX request to the server when you change the HTML of your counter:

$("#update").click(function() {
    $('#counter').html(function(i, val) {
        $.ajax({
            url: '/path/to/script/',
            type: 'POST',
            data: {increment: true},
            success: function() { alert('Request has returned') }
        });
        return +val+1;
    });
}

How can I remove or replace SVG content?

Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();

How can I disable notices and warnings in PHP within the .htaccess file?

I used ini_set('display_errors','off'); and it worked great.

How to remove index.php from URLs?

If the other solutions don't work for you, try this:

Step 1: (if your installation is in webroot)

Replace

    #RewriteBase /magento/

with

    RewriteBase /

Step 2:

Add following lines (inclusive exclude admin because backend needs index.php internally)

RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.yourdomain.com/$1 [R=301,L]
RewriteRule ^index.php/(admin|user)($|/) - [L]
RewriteRule ^index.php/(.*) $1 [R=301,QSA,L]

right after

RewriteRule .* index.php [L] 

This works for me

In case it is still not working, double check Magento configuration: System->Configuration->Web->Search Engine Optimization. Rewrites must be enabled.

Custom height Bootstrap's navbar

I believe you are using Bootstrap 3. If so, please try this code, here is the bootply

<header>
    <div class="navbar navbar-static-top navbar-default">
        <div class="navbar-header">
            <a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="glyphicon glyphicon-th-list"></span>
            </a>
        </div>
        <div class="container" style="background:yellow;">
            <a href="/">
                <img src="img/logo.png" class="logo img-responsive">
            </a>

            <nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
                <ul class="nav navbar-nav" style="display:inline-block;">
                    <li><a href="">Portfolio</a></li>
                    <li><a href="">Blog</a></li>
                    <li><a href="">Contact</a></li>
                </ul>
            </nav>
        </div>
    </div>
</header>

What is the best collation to use for MySQL with PHP?

It is best to use character set utf8mb4 with the collation utf8mb4_unicode_ci.

The character set, utf8, only supports a small amount of UTF-8 code points, about 6% of possible characters. utf8 only supports the Basic Multilingual Plane (BMP). There 16 other planes. Each plane contains 65,536 characters. utf8mb4 supports all 17 planes.

MySQL will truncate 4 byte UTF-8 characters resulting in corrupted data.

The utf8mb4 character set was introduced in MySQL 5.5.3 on 2010-03-24.

Some of the required changes to use the new character set are not trivial:

  • Changes may need to be made in your application database adapter.
  • Changes will need to be made to my.cnf, including setting the character set, the collation and switching innodb_file_format to Barracuda
  • SQL CREATE statements may need to include: ROW_FORMAT=DYNAMIC
    • DYNAMIC is required for indexes on VARCHAR(192) and larger.

NOTE: Switching to Barracuda from Antelope, may require restarting the MySQL service more than once. innodb_file_format_max does not change until after the MySQL service has been restarted to: innodb_file_format = barracuda.

MySQL uses the old Antelope InnoDB file format. Barracuda supports dynamic row formats, which you will need if you do not want to hit the SQL errors for creating indexes and keys after you switch to the charset: utf8mb4

  • #1709 - Index column size too large. The maximum column size is 767 bytes.
  • #1071 - Specified key was too long; max key length is 767 bytes

The following scenario has been tested on MySQL 5.6.17: By default, MySQL is configured like this:

SHOW VARIABLES;

innodb_large_prefix = OFF
innodb_file_format = Antelope

Stop your MySQL service and add the options to your existing my.cnf:

[client]
default-character-set= utf8mb4

[mysqld]
explicit_defaults_for_timestamp = true
innodb_large_prefix = true
innodb_file_format = barracuda
innodb_file_format_max = barracuda
innodb_file_per_table = true

# Character collation
character_set_server=utf8mb4
collation_server=utf8mb4_unicode_ci

Example SQL CREATE statement:

CREATE TABLE Contacts (
 id INT AUTO_INCREMENT NOT NULL,
 ownerId INT DEFAULT NULL,
 created timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
 modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 contact VARCHAR(640) NOT NULL,
 prefix VARCHAR(128) NOT NULL,
 first VARCHAR(128) NOT NULL,
 middle VARCHAR(128) NOT NULL,
 last VARCHAR(128) NOT NULL,
 suffix VARCHAR(128) NOT NULL,
 notes MEDIUMTEXT NOT NULL,
 INDEX IDX_CA367725E05EFD25 (ownerId),
 INDEX created (created),
 INDEX modified_idx (modified),
 INDEX contact_idx (contact),
 PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT=DYNAMIC;
  • You can see error #1709 generated for INDEX contact_idx (contact) if ROW_FORMAT=DYNAMIC is removed from the CREATE statement.

NOTE: Changing the index to limit to the first 128 characters on contacteliminates the requirement for using Barracuda with ROW_FORMAT=DYNAMIC

INDEX contact_idx (contact(128)),

Also note: when it says the size of the field is VARCHAR(128), that is not 128 bytes. You can use have 128, 4 byte characters or 128, 1 byte characters.

This INSERT statement should contain the 4 byte 'poo' character in the 2 row:

INSERT INTO `Contacts` (`id`, `ownerId`, `created`, `modified`, `contact`, `prefix`, `first`, `middle`, `last`, `suffix`, `notes`) VALUES
(1, NULL, '0000-00-00 00:00:00', '2014-08-25 03:00:36', '1234567890', '12345678901234567890', '1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890', '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678', '', ''),
(2, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '', '', ''),
(3, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '123', '', '');

You can see the amount of space used by the last column:

mysql> SELECT BIT_LENGTH(`last`), CHAR_LENGTH(`last`) FROM `Contacts`;
+--------------------+---------------------+
| BIT_LENGTH(`last`) | CHAR_LENGTH(`last`) |
+--------------------+---------------------+
|               1024 |                 128 | -- All characters are ASCII
|               4096 |                 128 | -- All characters are 4 bytes
|               4024 |                 128 | -- 3 characters are ASCII, 125 are 4 bytes
+--------------------+---------------------+

In your database adapter, you may want to set the charset and collation for your connection:

SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'

In PHP, this would be set for: \PDO::MYSQL_ATTR_INIT_COMMAND

References:

Bootstrap 4 - Responsive cards in card-columns

Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns element in very similar ways to columns with .col-4 or .col-lg-3:

@import "bootstrap";

$card-column-counts: 1, 2, 3, 4, 5;

.card-columns {
    @each $column-count in $card-column-counts {
        &.card-columns-#{$column-count} {
            column-count: $column-count;
        }
    }

    @each $breakpoint in map-keys($grid-breakpoints) {
        @include media-breakpoint-up($breakpoint) {
            $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
            @each $column-count in $card-column-counts {
                &.card-columns#{$infix}-#{$column-count} {
                    column-count: $column-count;
                }
            }
        }
    }
}

The end result of this is if you have the following:

<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
   ...
</div>

Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts can be overridden to change the allowed numbers of columns.

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

_x000D_
_x000D_
a {_x000D_
    background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
_x000D_
_x000D_

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

Resetting a setTimeout

You can store a reference to that timeout, and then call clearTimeout on that reference.

// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);

// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);

// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);

How to display the current time and date in C#

In WPF you'll need to use the Content property instead:

label1.Content = DateTime.Now.ToString();

Laravel Check If Related Model Exists

In php 7.2+ you can't use count on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:

$model->relation()->exists()

generic solution working on all the relation types (pre php 7.2):

if (count($model->relation))
{
  // exists
}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

Escaping Double Quotes in Batch Script

Google eventually came up with the answer. The syntax for string replacement in batch is this:

set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%

Which produces "replicate me". My script now looks like this:

@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"

Which replaces all instances of " with \", properly escaped for bash.

Changing the maximum length of a varchar column?

You need

ALTER TABLE YourTable ALTER COLUMN YourColumn <<new_datatype>> [NULL | NOT NULL]

But remember to specify NOT NULL explicitly if desired.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NOT NULL;

If you leave it unspecified as below...

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500);

Then the column will default to allowing nulls even if it was originally defined as NOT NULL. i.e. omitting the specification in an ALTER TABLE ... ALTER COLUMN is always treated as.

ALTER TABLE YourTable ALTER COLUMN YourColumn VARCHAR (500) NULL;

This behaviour is different from that used for new columns created with ALTER TABLE (or at CREATE TABLE time). There the default nullability depends on the ANSI_NULL_DFLT settings.

Multiple conditions in WHILE loop

Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.

Use myChar != 'n' && myChar != 'N' instead

Generating sql insert into for Oracle

I have been searching for a solution for this and found it today. Here is how you can do it.

  1. Open Oracle SQL Developer Query Builder

  2. Run the query

  3. Right click on result set and export

    http://i.stack.imgur.com/lJp9P.png

How to set css style to asp.net button?

You can assign a class to your ASP.NET Button and then apply the desired style to it.

<asp:Button class="mybtn" Text="Button" runat="server"></asp:Button>

CSS:

.mybtn
{
   border:1px solid Red;
   //some more styles
}

Why doesn't Java offer operator overloading?

Check out Boost.Units: link text

It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?

quantity<force>     F = 2.0*newton;
quantity<length>    dx = 2.0*meter;
quantity<energy>    E = F * dx;
std::cout << "Energy = " << E << endl;

would actually output "Energy = 4 J" which is correct.

How do I update a Linq to SQL dbml file?

There is a nuance to updating tables then updating the DBML... Foreign key relationships are not immediately always brought over if changes are made to existing tables. The work around is to do a build of the project and then re-add the tables again. I reported this to MS and its being fixed for VS2010.

DBML display does not show new foreign key constraints


Note that the instructions given in the main answer are not clear. To update the table

  1. Open up the dbml design surface
  2. Select all tables with Right->Click->Select All or CTRLa
  3. CTRLx (Cut)
  4. CTRLv (Paste)
  5. Save and rebuild solution.

Why do multiple-table joins produce duplicate rows?

When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.

Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:

TableA
Id Field1
1  test
2  another test

TableB
ID Field2 field3
1  Test1  something
1  test1  More something
2  Test2  Anything

So when you join them and select all the files you get:

select * 
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1        b.id   b.field2  b.field3
1    test            1      Test1     something
1    test            1      Test1     More something
2    another test 2  2      Test2     Anything

These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.

select a.Id, a.Field1,  b.field2
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1       b.field2  
1    test           Test1     
1    test           Test1 
2    another test   Test2

This appears to be duplicates but it is not because of the multiple records in TableB.

You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

If you're trying to debug an ASP.NET project, ensure that the project's Properties > Web > Servers dropdown is set to "IIS Express" (in addition to checking everything else here).

setTimeout / clearTimeout problems

A way to use this in react:

class Timeout extends Component {
  constructor(props){
    super(props)

    this.state = {
      timeout: null
    }

  }

  userTimeout(){
    const { timeout } = this.state;
    clearTimeout(timeout);
    this.setState({
      timeout: setTimeout(() => {this.callAPI()}, 250)
    })

  }
}

Helpful if you'd like to only call an API after the user has stopped typing for instance. The userTimeout function could be bound via onKeyUp to an input.

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

Constants in Objective-C

I use a singleton class, so that I can mock the class and change the constants if necessary for testing. The constants class looks like this:

#import <Foundation/Foundation.h>

@interface iCode_Framework : NSObject

@property (readonly, nonatomic) unsigned int iBufCapacity;
@property (readonly, nonatomic) unsigned int iPort;
@property (readonly, nonatomic) NSString * urlStr;

@end

#import "iCode_Framework.h"

static iCode_Framework * instance;

@implementation iCode_Framework

@dynamic iBufCapacity;
@dynamic iPort;
@dynamic urlStr;

- (unsigned int)iBufCapacity
{
    return 1024u;
};

- (unsigned int)iPort
{
    return 1978u;
};

- (NSString *)urlStr
{
    return @"localhost";
};

+ (void)initialize
{
    if (!instance) {
        instance = [[super allocWithZone:NULL] init];
    }
}

+ (id)allocWithZone:(NSZone * const)notUsed
{
    return instance;
}

@end

And it is used like this (note the use of a shorthand for the constants c - it saves typing [[Constants alloc] init] every time):

#import "iCode_FrameworkTests.h"
#import "iCode_Framework.h"

static iCode_Framework * c; // Shorthand

@implementation iCode_FrameworkTests

+ (void)initialize
{
    c  = [[iCode_Framework alloc] init]; // Used like normal class; easy to mock!
}

- (void)testSingleton
{
    STAssertNotNil(c, nil);
    STAssertEqualObjects(c, [iCode_Framework alloc], nil);
    STAssertEquals(c.iBufCapacity, 1024u, nil);
}

@end

When should I use double or single quotes in JavaScript?

If you use PHP to generate JavaScript code you should use the following declaration.

let value = "<?php echo 'This is my message, "double quoted" - \'single quoted\' ?>";

The output will be:

This is my message, "double quoted" - 'single quoted'

For some reasons it is recommend to use single quotes rather than double quotes in PHP.

For the normal behaviour in JavaScript it is recommend to use single quotes.

_x000D_
_x000D_
var value = 'This is my message';
document.getElementById('sample-text').innerHTML = value;
_x000D_
<span id="sample-text"></span>
_x000D_
_x000D_
_x000D_

Why do we use __init__ in Python classes?

Following with your car example: when you get a car, you just don't get a random car, I mean, you choose the color, the brand, number of seats, etc. And some stuff is also "initialize" without you choosing for it, like number of wheels or registration number.

class Car:
    def __init__(self, color, brand, number_of_seats):
        self.color = color
        self.brand = brand
        self.number_of_seats = number_of_seats
        self.number_of_wheels = 4
        self.registration_number = GenerateRegistrationNumber()

So, in the __init__ method you defining the attributes of the instance you're creating. So, if we want a blue Renault car, for 2 people, we would initialize or instance of Car like:

my_car = Car('blue', 'Renault', 2)

This way, we are creating an instance of the Car class. The __init__ is the one that is handling our specific attributes (like color or brand) and its generating the other attributes, like registration_number.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

you should try this

g++-4.4 -std=c++0x or g++-4.7 -std=c++0x

Is it possible to get the current spark context settings in PySpark?

If you want to see the configuration in data bricks use the below command

spark.sparkContext._conf.getAll()

Input jQuery get old value before onchange and get value after on change

The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/

$('input').on('focusin', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
});

$('input').on('change', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

Better to use Delegated Event Handlers

Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.

Here is the same example using delegated events connected to document:

$(document).on('focusin', 'input', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
}).on('change','input', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/

Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.

*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)

What is the difference between GitHub and gist?

My Personal View of Gist and GitHub:

Gist: Gist is a simple way to share code snippets and pastes with others. It is used when you need to share a sample piece of code or technique with your co-workers or friends.

And

GitHub GitHub, on the other hand, provides a platform to share an entire project as a repo among a team(private repo) or to the whole world(public repo).

Both Will log version details.

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

Using Java to find substring of a bigger string using Regular Expression

assuming that no other closing square bracket is allowed within, /FOO\[([^\]]*)\]/

What is an example of the simplest possible Socket.io example?

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console UPPERCASED.

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

storing user input in array

You're not actually going out after the values. You would need to gather them like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

var myArray = [ title, name, tickets ];

Or many arrays:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push() method to push new values onto it:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

The new form follows:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

I've also made some changes to your JavaScript. I start by creating three empty arrays:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

var messageBox  = document.getElementById("display");

The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.

Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

How can I easily add storage to a VirtualBox machine with XP installed?

Adding a second drive is probably easiest. That would only take a few minutes, and it wouldn't require any configuration, really.

Alternatively, you could create the second, bigger drive, then run a disk imaging utility to copy all data on disk1 to disk2. That certainly shouldn't take a few hours, but it would take longer than just living with two drives.

Conda: Installing / upgrading directly from github

There's better support for this now through conda-env. You can, for example, now do:

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"

It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml file.

If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml), then run the command: conda env update -f environment.yml.

It's more likely that you would want to create a new environment:

conda env create -f environment.yml (changed as supposed in the comments)

jQuery - Get Width of Element when Not Visible (Display: None)

Based on Roberts answer, here is my function. This works for me if the element or its parent have been faded out via jQuery, can either get inner or outer dimensions and also returns the offset values.

/edit1: rewrote the function. it's now smaller and can be called directly on the object

/edit2: the function will now insert the clone just after the original element instead of the body, making it possible for the clone to maintain inherited dimensions.

$.fn.getRealDimensions = function (outer) {
    var $this = $(this);
    if ($this.length == 0) {
        return false;
    }
    var $clone = $this.clone()
        .show()
        .css('visibility','hidden')
        .insertAfter($this);        
    var result = {
        width:      (outer) ? $clone.outerWidth() : $clone.innerWidth(), 
        height:     (outer) ? $clone.outerHeight() : $clone.innerHeight(), 
        offsetTop:  $clone.offset().top, 
        offsetLeft: $clone.offset().left
    };
    $clone.remove();
    return result;
}

var dimensions = $('.hidden').getRealDimensions();

PHP Fatal error: Cannot redeclare class

i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.

Using Python's list index() method on a list of tuples or objects?

ok, it might be a mistake in vals(j), the correction is:

def getIndex(li,indices,vals):
for pos,k in enumerate(lista):
    match = True
    for i in indices:
        if k[i] != vals[indices.index(i)]:
            match = False
            break
    if(match):
        return pos

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

there may be more than 1 IBAction for a button in your view controller try finding out those and removing all previous item for that button in your controller and create new button .It will solve your problem.

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

How to style the menu items on an Android action bar

Instead of having the android:actionMenuTextAppearance item under your action bar style, move it under your app theme.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

As @ace mentioned you will need the jstl.jar in your project, so if you are using maven, you could add this dependency:

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

Source: http://mvnrepository.com/artifact/jstl/jstl/

Hope it helps.

EDIT: Most of servers already have this dependency, if you add it using maven it may cause version conflicts (like Method/ClassNotFoundException) if you don't configure the server well, so it's better set a target server for your project, as @willix mentioned.

Injecting Mockito mocks into a Spring bean

For the record, all my tests correctly work by just making the fixture lazy-initialized, e.g.:

<bean id="fixture"
      class="it.tidalwave.northernwind.rca.embeddedserver.impl.DefaultEmbeddedServer"
      lazy-init="true" /> <!-- To solve Mockito + Spring problems -->

<bean class="it.tidalwave.messagebus.aspect.spring.MessageBusAdapterFactory" />

<bean id="applicationMessageBus"
      class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="it.tidalwave.messagebus.MessageBus" />
</bean>

<bean class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="javax.servlet.ServletContext" />
</bean>

I suppose the rationale is the one Mattias explains here (at the bottom of the post), that a workaround is changing the order the beans are declared - lazy initialization is "sort of" having the fixture declared at the end.

'float' vs. 'double' precision

Floating point numbers in C use IEEE 754 encoding.

This type of encoding uses a sign, a significand, and an exponent.

Because of this encoding, many numbers will have small changes to allow them to be stored.

Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

Currency format for display

If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.

public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
{
    NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
    localFormat.CurrencySymbol = currencySymbol;
    localFormat.CurrencyDecimalDigits = decPlaces;
    return currency.ToString("c", localFormat);
}

Using Intent in an Android application to show another activity

Add this line to your AndroidManifest.xml:

<activity android:name=".OrderScreen" /> 

java.io.FileNotFoundException: the system cannot find the file specified

I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:

  1. Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
  2. Save as that File with any name that you want but with a .txt in the end of that I guess your problem is solved, but I write it to other peoples know that. Thanks.

Parsing GET request parameters in a URL that contains another URL

The correct php way is to use parse_url()

http://php.net/manual/en/function.parse-url.php

(from php manual)

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Reading entire html file to String?

You should use a StringBuilder:

StringBuilder contentBuilder = new StringBuilder();
try {
    BufferedReader in = new BufferedReader(new FileReader("mypage.html"));
    String str;
    while ((str = in.readLine()) != null) {
        contentBuilder.append(str);
    }
    in.close();
} catch (IOException e) {
}
String content = contentBuilder.toString();

How can I clear or empty a StringBuilder?

Two ways that work:

  1. Use stringBuilderObj.setLength(0).
  2. Allocate a new one with new StringBuilder() instead of clearing the buffer.

Modify request parameter with servlet filter

Try request.setAttribute("param",value);. It worked fine for me.

Please find this code sample:

private void sanitizePrice(ServletRequest request){
        if(request.getParameterValues ("price") !=  null){
            String price[] = request.getParameterValues ("price");

            for(int i=0;i<price.length;i++){
                price[i] = price[i].replaceAll("[^\\dA-Za-z0-9- ]", "").trim();
                System.out.println(price[i]);
            }
            request.setAttribute("price", price);
            //request.getParameter("numOfBooks").re
        }
    }

How do I install PyCrypto on Windows?

This probably isn't the optimal solution but you might download and install the free Visual C++ Express package from MS. This will give you the C++ compiler you need to compile the PyCrypto code.

Determining image file size + dimensions via Javascript?

You can find dimension of an image on the page using something like

document.getElementById('someImage').width

file size, however, you will have to use something server-side

Gradient of n colors ranging from color 1 and color 2

Try the following:

color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
  return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
x <- c((1:100)^2, (100:1)^2)
plot(x,col=color.gradient(x), pch=19,cex=2)

enter image description here

Best Practice: Software Versioning

We use a.b.c.d where

  • a - major (incremented on delivery to client)
  • b - minor (incremented on delivery to client)
  • c - revision (incremented on internal releases)
  • d - build (incremented by cruise control)

How do I print part of a rendered HTML page in JavaScript?

<div id="invocieContainer">
    <div class="row">
        ...Your html Page content here....
    </div>
</div>

<script src="/Scripts/printThis.js"></script>
<script>
    $(document).on("click", "#btnPrint", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $("#invocieContainer").printThis({
            debug: false, // show the iframe for debugging
            importCSS: true, // import page CSS
            importStyle: true, // import style tags
            printContainer: true, // grab outer container as well as the contents of the selector
            loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
            pageTitle: "", // add title to print page
            removeInline: false, // remove all inline styles from print elements
            printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
            header: null, // prefix to html
            formValues: true // preserve input/form values
        });

    });
</script>

For printThis.js souce code, copy and pase below URL in new tab https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

this worked:

System.out.println("resultList.toString() " + resultList);
            org.json.JSONObject obj = new JSONObject(resultList);
            org.json.JSONArray jsonArray = obj.getJSONArray(someField);

            for(int i=0;i<jsonArray.length();i++){
                System.out.println("array is " + jsonArray.get(i));

            }

this.getClass().getClassLoader().getResource("...") and NullPointerException

I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.

For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"

I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.

<build>
    <defaultGoal>package</defaultGoal>
    <directory>${basedir}/build</directory>
<build>

I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"

I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.

How to detect if user select cancel InputBox VBA Excel

If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...

EDIT to properly differentiate between empty string and cancel, according to this answer.

Your example

Private Sub test()
    Dim result As String
    result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
    If StrPtr(result) = 0 Then
        MsgBox ("User canceled!")
    ElseIf result = vbNullString Then
        MsgBox ("User didn't enter anything!")
    Else
        MsgBox ("User entered " & result)
    End If
End Sub

Would tell the user they canceled when they delete the default string, or they click cancel.

See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx

How do I use reflection to call a generic method?

You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:

MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

For a static method, pass null as the first argument to Invoke. That's nothing to do with generic methods - it's just normal reflection.

As noted, a lot of this is simpler as of C# 4 using dynamic - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.

Maximize a window programmatically and prevent the user from changing the windows state

When your form is maximized, set its minimum size = max size, so user cannot resize it.

    this.WindowState = FormWindowState.Maximized;
    this.MinimumSize = this.Size;
    this.MaximumSize = this.Size;

AWS ssh access 'Permission denied (publickey)' issue

If you're using a Bitnami image, log in as 'bitnami'.

Seems obvious, but something I overlooked.

Get nth character of a string in Swift programming language

Swift 5.3

I think this is very elegant. Kudos at Paul Hudson of "Hacking with Swift" for this solution:

@available (macOS 10.15, * )
extension String {
    subscript(idx: Int) -> String {
        String(self[index(startIndex, offsetBy: idx)])
    }
}

Then to get one character out of the String you simply do:

var string = "Hello, world!"

var firstChar = string[0] // No error, returns "H" as a String

Can an Option in a Select tag carry multiple values?

put values for each options like

<SELECT NAME="val">
   <OPTION VALUE="1" value="1:2:3:4"> 1-4  
   <OPTION VALUE="2" value="5:6:7:8"> 5-8  
   <OPTION VALUE="3" value="9:10:11:12"> 9-12
</SELECT>

at server side in case of php, use functions like explode [array] = explode([delimeter],[posted value]);

$values = explode(':',$_POST['val']

the above code return an array have only the numbers and the ':' get removed

adb server version doesn't match this client

I had this issue on one of my development machines (all run windows 7 x64) while all other machines' adb work normally. The reason I ran into this issue is I have an old version of adb.exe reside in %android-sdk%\tools while newer Android SDKs have adb.exe under %android-sdk%\platform-tools

remove the older adb.exe from %android-sdk%\tools and add %android-sdk%\platform-tools to %PATH% solves this issue

or more generally, hunt down any adb executable in your path that are out of date, just use the latest one provided with Android SDK

Git stash pop- needs merge, unable to refresh index

The stash has already been applied to other files.

It is only app.coffee that you have to merge manually. Afterwards just run

git reset

to unstage the changes and keep on hacking.

Fixing npm path in Windows 8 and 10

If after installing your npm successfully, and you want to install VueJS then this is what you should do

after running the following command (as Admin)

npm install --global vue-cli

It will place the vue.cmd in the following directory C:\Users\YourUserName\AppData\Roaming\npm

you will see this in your directory.

Now to use vue as a command in cmd. Open the cmd as admin and run the following command.

setx /M path "%path%;%appdata%\npm"

Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.

I hope this helps.

Change Timezone in Lumen or Laravel 5

For me the app.php was here /vendor/laravel/lumen-framework/config/app.php but I also could change it from the .env file where it can be set to any of the values listed here (PHP original documentation here).

Display Adobe pdf inside a div

I think its not working, because you z-index property not applied on pdf(any outside object). So when you add any control in PDF view boundary,its appear behind of pdf view.

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

How do I get a PHP class constructor to call its parent's parent's constructor?

You can call Grandpa::__construct from where you want and the $this keyword will refer to your current class instance. But be carefull with this method you cannot access to protected properties and methods of current instance from this other context, only to public elements. => All work and officialy supported.

Example

// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {
        echo $this->one; // will print 1
        echo $this->two; // error cannot access protected property
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public $one = 1;
    protected $two = 2;
    public function __construct()
    {
        Grandpa::__construct();
    }
}

new Kiddo();

JQuery create a form and add elements to it programmatically

Using Jquery

Rather than creating temp variables it can be written in a continuous flow pattern as follows:

$('</form>', { action: url, method: 'POST' }).append(
    $('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
    $('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();

How to get MAC address of your machine using a C program?

  1. On Linux, use the service of "Network Manager" over the DBus.

  2. There is also good'ol shell program which can be invoke and the result grabbed (use an exec function under C):

$ /sbin/ifconfig | grep HWaddr

How to set custom header in Volley Request

That is my code, dont forget = object: if don't put don't works

val queue = Volley.newRequestQueue(this)
        val url = "http://35.237.133.137:8080/lamarrullaWS/rest/lamarrullaAPI"
        // Request a string response from the provided URL.
        val jsonObjectRequest = object: JsonObjectRequest(Request.Method.GET, url, null,
                Response.Listener { response ->
                    txtPrueba.text = "Response: %s".format(response.toString())
                },
                Response.ErrorListener { txtPrueba.text = "That didn't work!" }
        )
        {
            @Throws(AuthFailureError::class)
            override fun getHeaders(): Map<String, String> {
                val headers = HashMap<String, String>()
                headers.put("Content-Type", "application/json")
                return headers
            }
        }
        queue.add(jsonObjectRequest)

Open JQuery Datepicker by clicking on an image w/ no input field

Turns out that a simple hidden input field does the job:

<input type="hidden" id="dp" />

And then use the buttonImage attribute for your image, like normal:

    $("#dp").datepicker({
        buttonImage: '../images/icon_star.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showOn: 'both',
     });

Initially I tried a text input field and then set a display:none style on it, but that caused the calendar to emerge from the top of the browser, rather than from where the user clicked. But the hidden field works as desired.

Spring Boot not serving static content

Given resources under src/main/resources/static, if you add this code, then all static content from src/main/resources/static will be available under "/":

@Configuration
public class StaticResourcesConfigurer implements WebMvcConfigurer {
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/static/");
    }
}

How to connect to remote Redis server?

One thing that confused me a little bit with this command is that if redis-cli fails to connect using the passed connection string it will still put you in the redis-cli shell, i.e:

redis-cli
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected> 

You'll then need to exit to get yourself out of the shell. I wasn't paying much attention here and kept passing in new redis-cli commands wondering why the command wasn't using my passed connection string.

Copy and paste content from one file to another file in vi

These remaps work like a charm for me:

vmap <C-c> "*y     " Yank current selection into system clipboard
nmap <C-c> "*Y     " Yank current line into system clipboard (if nothing is selected)
nmap <C-v> "*p     " Paste from system clipboard

So, when I'm at visual mode, I select the lines I want and press Ctrl + c and then Ctrl + v to insert the text in the receiver file. You could use "*y as well, but I think this is hard to remember sometimes.

This is also useful to copy text from Vim to clipboard.

Source: Copy and paste between sessions using a temporary file

Unfortunately MyApp has stopped. How can I solve this?

You can also get this error message on its own, without any stack trace or any further error message.

In this case you need to make sure your Android manifest is configured correctly (including any manifest merging happening from a library and any activity that would come from a library), and pay particular attention to the first activity displayed in your application in your manifest files.

How to list all functions in a Python module?

import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Here's a modification of CMS's solution that can be called in multiple places in your code:

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

Usage:

$(window).resize(function () {
    waitForFinalEvent(function(){
      alert('Resize...');
      //...
    }, 500, "some unique string");
});

CMS's solution is fine if you only call it once, but if you call it multiple times, e.g. if different parts of your code set up separate callbacks to window resizing, then it will fail b/c they share the timer variable.

With this modification, you supply a unique id for each callback, and those unique IDs are used to keep all the timeout events separate.

How to time Java program execution speed

You may also try Perf4J. Its a neat way of doing what you are looking for, and helps in aggregated performance statistics like mean, minimum, maximum, standard deviation and transactions per second over a set time span. An extract from http://perf4j.codehaus.org/devguide.html:

StopWatch stopWatch = new LoggingStopWatch();

try {
    // the code block being timed - this is just a dummy example
    long sleepTime = (long)(Math.random() * 1000L);
    Thread.sleep(sleepTime);
    if (sleepTime > 500L) {
        throw new Exception("Throwing exception");
    }

    stopWatch.stop("codeBlock2.success", "Sleep time was < 500 ms");
} catch (Exception e) {
    stopWatch.stop("codeBlock2.failure", "Exception was: " + e);
}

Output:

INFO: start[1230493236109] time[447] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493236719] time[567] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493237286] time[986] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493238273] time[194] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238467] time[463] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493238930] time[310] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239241] time[610] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]
INFO: start[1230493239852] time[84] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239937] time[30] tag[codeBlock2.success] message[Sleep time was < 500 ms]
INFO: start[1230493239968] time[852] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]

https with WCF error: "Could not find base address that matches scheme https"

It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.

Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/

Edit: I fixed my problem, which was slightly different, after talking to microsoft support.

My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https

<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />

jQuery Find and List all LI elements within a UL within a specific DIV

html

<ul class="answerList" id="oneAnswer">
    <li class="answer" value="false">info1</li>
    <li class="answer" value="false">info2</li>
    <li class="answer" value="false">info3</li>
</ul>   

Get index,text,value js

    $('#oneAnswer li').each(function (i) {

        var index = $(this).index();
        var text = $(this).text();
        var value = $(this).attr('value');
        alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
    });

How to POST JSON data with Python Requests?

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

How to increment datetime by custom months in python without using library

Similar in ideal to Dave Webb's solution, but without all of that tricky modulo arithmetic:

import datetime, calendar

def increment_month(date):
    # Go to first of this month, and add 32 days to get to the next month
    next_month = date.replace(day=1) + datetime.timedelta(32)
    # Get the day of month that corresponds
    day = min(date.day, calendar.monthrange(next_month.year, next_month.month)[1])
    return next_month.replace(day=day)

Overloading operators in typedef structs (c++)

The breakdown of your declaration and its members is somewhat littered:

Remove the typedef

The typedef is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos as-written, which is core to your current compilation failure.

Change this:

typedef struct {....} pos;

To this:

struct pos { ... };

Remove extraneous inlines

You're both declaring and defining your member operators within the class definition itself. The inline keyword is not needed so long as your implementations remain in their current location (the class definition)


Return references to *this where appropriate

This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:

a = b = c;

This assigns c to b, and the resulting value b is then assigned to a. This is not equivalent to the following code, contrary to what you may think:

a = c;
b = c;

Therefore, your assignment operator should be implemented as such:

pos& operator =(const pos& a)
{
    x = a.x;
    y = a.y;
    return *this;
}

Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)

Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:

pos& operator=(pos a) // by-value param invokes class copy-ctor
{
    this->swap(a);
    return *this;
}

Then a swap method is implemented:

void pos::swap(pos& obj)
{
    // TODO: swap object guts with obj
}

You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.


Pass objects by const reference when appropriate

All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:

Change this:

bool operator==(pos a) const{
    if(a.x==x && a.y== y)return true;
    else return false;
}

To this: (also simplified)

bool operator==(const pos& a) const
{
    return (x == a.x && y == a.y);
}

No copies of anything are made, resulting in more efficient code.


Finally, in answering your question, what is the difference between a member function or operator declared as const and one that is not?

A const member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const member functions can be invoked against const objects, or const references and pointers. For example, your operator +() does not modify your local object and thus should be declared as const. Your operator =() clearly modifies the local object, and therefore the operator should not be const.


Summary

struct pos
{
    int x;
    int y;

    // default + parameterized constructor
    pos(int x=0, int y=0) 
        : x(x), y(y)
    {
    }

    // assignment operator modifies object, therefore non-const
    pos& operator=(const pos& a)
    {
        x=a.x;
        y=a.y;
        return *this;
    }

    // addop. doesn't modify object. therefore const.
    pos operator+(const pos& a) const
    {
        return pos(a.x+x, a.y+y);
    }

    // equality comparison. doesn't modify object. therefore const.
    bool operator==(const pos& a) const
    {
        return (x == a.x && y == a.y);
    }
};

EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:

a = b = c;

Is equivalent to this:

b = c;
a = b;

And that this does not always equate to this:

a = c;
b = c;

Sample code:

#include <iostream>
#include <string>
using namespace std;

struct obj
{
    std::string name;
    int value;

    obj(const std::string& name, int value)
        : name(name), value(value)
    {
    }

    obj& operator =(const obj& o)
    {
        cout << name << " = " << o.name << endl;
        value = (o.value+1); // note: our value is one more than the rhs.
        return *this;
    }    
};

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

    obj a("a", 1), b("b", 2), c("c", 3);

    a = b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    a = c;
    b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    return 0;
}

Output

b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I still found that with the solutions above, it didn't work (for example) with the Rails plugin for TextMate. I got a similar error (when retrieving the database schema).

So what did is, open terminal:

cd /usr/local/lib
sudo ln -s ../mysql-5.5.8-osx10.6-x86_64/lib/libmysqlclient.16.dylib .

Replace mysql-5.5.8-osx10.6-x86_64 with your own path (or mysql).

This makes a symbol link to the lib, now rails runs from the command line, as-well as TextMate plugin(s) like ruby-on-rails-tmbundle.

To be clear: this also fixes the error you get when starting rails server.

How to leave a message for a github.com user

Github said on April 3rd 2012 :

Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

Source

How to run JUnit test cases from the command line

If your project is Maven-based you can run all test-methods from test-class CustomTest which belongs to module 'my-module' using next command:

mvn clean test -pl :my-module -Dtest=CustomTest

Or run only 1 test-method myMethod from test-class CustomTest using next command:

mvn clean test -pl :my-module -Dtest=CustomTest#myMethod

For this ability you need Maven Surefire Plugin v.2.7.3+ and Junit 4. More details is here: http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html

Is it safe to use Project Lombok?

It sounds like you've already decided that Project Lombok gives you significant technical advantages for your proposed new project. (To be clear from the start, I have no particular views on Project Lombok, one way or the other.)

Before you use Project Lombok (or any other game-changing technology) in some project (open source or other wise), you need to make sure that the project stake holders agree to this. This includes the developers, and any important users (e.g. formal or informal sponsors).

You mention these potential issues:

Flamewars will erupt in the ##Java Freenode channel when I mention it,

Easy. Ignore / don't participate in the flamewars, or simply refrain from mentioning Lombok.

providing code snippets will confuse possible helpers,

If the project strategy is to use Lombok, then the possible helpers will need to get used to it.

people will complain about missing JavaDoc,

That is their problem. Nobody in their right mind tries to rigidly apply their organization's source code / documentation rules to third-party open source software. The project team should be free to set project source code / documentation standards that are appropriate to the technology being used.

(FOLLOWUP - The Lombok developers recognize that not generating javadoc comments for synthesized getter and setter methods is an issue. If this is a major problem for your project(s), then one alternative is to create and submit a Lombok patch to address this.)

and future commiters might just remove it all anyway.

That's not on! If the agreed project strategy is to use Lombok, then commiters who gratuitously de-Lombok the code should be chastised, and if necessary have their commit rights withdrawn.

Of course, this assumes that you've got buy-in from the stakeholders ... including the developers. And it assumes that you are prepared to argue your cause, and appropriately handle the inevitable dissenting voices.

How to change line color in EditText

If you want a flat line, you can do this easily with xml. Here is the xml example:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-1dp"
        android:left="-1dp"
        android:right="-1dp"
        android:bottom="1dp"
        >
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#6A9A3A"/>
        </shape>
    </item>
</layer-list>

Replace the shape with a selector if you want to provide different width and color for focused edittext.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

After spending lot of time on internet. I found that NONE of the option worked for I tried Right click on the server -> Clean. didn't work.

What worked is:

You just to add<absolute-ordering/> tag to your web.xml just under the <display-name> tag and it should work.for more detail click here

Java: Enum parameter in method

Sure, you could use an enum. Would something like the following work?

enum Alignment {
    LEFT,
    RIGHT
}

private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }

If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.

How to capture no file for fs.readFileSync()?

Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:

const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);

const readContentFile = async (filePath) => {
  // Eureka, you are using good code practices here!
  const content = await readFileAsync(path.join(__dirname, filePath), {
    encoding: 'utf8'
  })
  return content;
}

Later can use this async function with try/catch from any other function:

const anyOtherFun = async () => {
  try {
    const fileContent = await readContentFile('my-file.txt');
  } catch (err) {
    // Here you get the error when the file was not found,
    // but you also get any other error
  }
}

Happy Coding!

Maven Unable to locate the Javac Compiler in:

In Eclipse, actions like importing Maven projects or invoking "Update Sources" runs in the same JVM in which Eclipse is running. If that JVM comes from JRE that isn’t part of JDK, there would be no Java compiler (the tools.jar).

So to launch Maven from within Eclipse, JRE used for launch also need to come from JDK. By default Eclipse registers JRE it is started in, but this can be configured on "Window / Preferences… / Java / Installed JREs" preference page as mentioned above by Parthasarathy

Alternatively you can specify compilerId in the pom.xml, so Maven won’t be looking for JDK when compiling Java code:

 <plugin>
  <artifactid>maven-compiler-plugin</artifactid>
  <configuration>
    <compilerid>eclipse</compilerid>
  </configuration>
  <dependencies>
    <dependency>
      <groupid>org.codehaus.plexus</groupid>
      <artifactid>plexus-compiler-eclipse</artifactid>
      <version>xxxx</version>
    </dependency>
  </dependencies>
</plugin>

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

When should you NOT use a Rules Engine?

That's certainly a good start. The other thing with rules engines is that some things are well-understood, deterministic, and straight-forward. Payroll withholding is (or use to be) like that. You could express it as rules that would be resolved by a rules engine, but you could express the same rules as a fairly simple table of values.

So, workflow engines are good when you're expressing a longer-term process that will have persistent data. Rules engines can do a similar thing, but you have to do a lot of added complexity.

Rules engines are good when you have complicated knowledge bases and need search. Rules engines can resolve complicated issues, and can be adapted quickly to changing situations, but impose a lot of complexity on the base implementation.

Many decision algorithms are simple enough to express as a simple table-driven program without the complexity implied by a real rules engine.

Protecting cells in Excel but allow these to be modified by VBA script

As a workaround, you can create a hidden worksheet, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula.

You will be able to change the displayed value through the hidden worksheet, while your users won't be able to edit it.

How to make the tab character 4 spaces instead of 8 spaces in nano?

For future viewers, there is a line in my /etc/nanorc file close to line 153 that says "set tabsize 8". The word might need to be tabsize instead of tabspace. After I replaced 8 with 4 and uncommented the line, it solved my problem.

Clone() vs Copy constructor- which is recommended in java

clone() was designed with several mistakes (see this question), so it's best to avoid it.

From Effective Java 2nd Edition, Item 11: Override clone judiciously

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

This book also describes the many advantages copy constructors have over Cloneable/clone.

  • They don't rely on a risk-prone extralinguistic object creation mechanism
  • They don't demand unenforceable adherence to thinly documented conventions
  • They don't conflict with the proper use of final fields
  • They don't throw unnecessary checked exceptions
  • They don't require casts.

All standard collections have copy constructors. Use them.

List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);

How to give spacing between buttons using bootstrap

I am pretty bad at html but I used &nbsp; between the buttons and it worked well.

How do you run your own code alongside Tkinter's event loop?

The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.

The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).

Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.

The revised code is as follows:

# Run tkinter code in another thread

import tkinter as tk
import threading

class App(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)

        label = tk.Label(self.root, text="Hello World")
        label.pack()

        self.root.mainloop()


app = App()
print('Now we can continue running code while mainloop runs!')

for i in range(100000):
    print(i)

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

Twitter Bootstrap: div in container with 100% height

Update 2019

In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.

First of all, the container (parent) needs to be full height:

Option 1_ Add a class for min-height: 100%;. Remember that min-height will only work if the parent has a defined height:

html, body {
  height: 100%;
}

.min-100 {
    min-height: 100%;
}

https://codeply.com/go/dTaVyMah1U

Option 2_ Use vh units:

.vh-100 {
    min-height: 100vh;
}

https://codeply.com/go/kMahVdZyGj

Also of Bootstrap 4.1, the vh-100 and min-vh-100 classes are included in Bootstrap so there is no need to for the extra CSS

Then, use flexbox direction column d-flex flex-column on the container, and flex-grow-1 on any child divs (ie: row) that you want to fill the remaining height.

Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height

How to change font-color for disabled input?

You can't for Internet Explorer.

See this comment I wrote on a related topic:

There doesn't seem to be a good way, see: How to change color of disabled html controls in IE8 using css - you can set the input to readonly instead, but that has other consequences (such as with readonly, the input will be sent to the server on submit, but with disabled, it won't be): http://jsfiddle.net/wCFBw/40

Also, see: Changing font colour in Textboxes in IE which are disabled

How to concatenate columns in a Postgres SELECT?

CONCAT functions sometimes not work with older postgreSQL version

see what I used to solve problem without using CONCAT

 u.first_name || ' ' || u.last_name as user,

Or also you can use

 "first_name" || ' ' || "last_name" as user,

in second case I used double quotes for first_name and last_name

Hope this will be useful, thanks

What is an ORM, how does it work, and how should I use one?

Like all acronyms it's ambiguous, but I assume they mean object-relational mapper -- a way to cover your eyes and make believe there's no SQL underneath, but rather it's all objects;-). Not really true, of course, and not without problems -- the always colorful Jeff Atwood has described ORM as the Vietnam of CS;-). But, if you know little or no SQL, and have a pretty simple / small-scale problem, they can save you time!-)

What does "Use of unassigned local variable" mean?

Use "default"!!!

    string myString = default;
    double myDouble = defaul;

    if(!String.IsNullOrEmpty(myString))
       myDouble = 1.5;

    return myDouble;

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

How do I return an int from EditText? (Android)

You can do this in 2 steps:

1: Change the input type(In your EditText field) in the layout file to android:inputType="number"

2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());

How to exclude rows that don't join with another table?

SELECT P.*
FROM primary_table P
LEFT JOIN secondary_table S on P.id = S.p_id
WHERE S.p_id IS NULL

Set a DateTime database field to "Now"

In SQL you need to use GETDATE():

UPDATE table SET date = GETDATE();

There is no NOW() function.


To answer your question:

In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.

So, if your requirement is to set it all to the same date I would do something like this (untested):

DECLARE @currDate DATETIME;
SET @currDate = GETDATE();

UPDATE table SET date = @currDate;

The import javax.servlet can't be resolved

You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar in Tomcat's lib folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.

If you want to leave the JAR in Tomcat's lib folder:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click the Libraries tab
  • Click Add External JARs...
  • Browse to find servlet-api.jar and select it.
  • Click OK to update the build path.

Or, if you copy the JAR into your project:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click Add JARs...
  • Find servlet-api.jar in your project and select it.
  • Click OK to update the build path.

How to draw a line in android

If you're working with ConstraintLayout you need to define at least 2 constraints for the line to show up. Like this:

<View
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:background="@android:color/black"
        app:layout_constraintEnd_toEndOf="@+id/someView1"
        app:layout_constraintStart_toStartOf="@+id/someView2"
        app:layout_constraintTop_toBottomOf="@+id/someView3" />

Though I defined 3 constraints.

Format string to a 3 digit number

You can also do : string.Format("{0:D3}, 3);

How to use NSURLConnection to connect with SSL for an untrusted cert?

If you want to keep using sendSynchronousRequest i work in this solution:

FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];

NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];    
NSData *d=[fcd getData];

you can see it here: Objective-C SSL Synchronous Connection

How to catch all exceptions in c# using try and catch?

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
    {
        // Ignore this exception.
    }
    
  • Catch and log all exceptions.

    catch (Exception e)
    {
        // Something unexpected went wrong.
        Log(e);
        // Maybe it is also necessary to terminate / restart the application.
    }
    
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch
    {
        SomeCleanUp();
        throw;
    }
    

Note that in the last case the exception is rethrown using throw; and not throw ex;.

How to run a stored procedure in oracle sql developer?

Consider you've created a procedure like below.

CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
  FIRST_NAME IN VARCHAR2, 
  LAST_NAME IN VARCHAR2,
  FULL_NAME OUT VARCHAR2 
) IS 
BEGIN
  FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;

In Oracle SQL Developer, you can run this procedure in two ways.

1. Using SQL Worksheet

Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5

DECLARE
  FULL_NAME Varchar2(50);
BEGIN
  GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
  Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;

2. Using GUI Controls

  • Expand Procedures

  • Right click on the procudure you've created and Click Run

  • In the pop-up window, Fill the parameters and Click OK.

Cheers!

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

You don't need to change the compliance level here, or rather, you should but that's not the issue.

The code compliance ensures your code is compatible with a given Java version.

For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).

The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.

Instead, you should check the JDK/JRE you're using to build.

In Eclipse, open the project properties and check the selected JRE in the Java build path.

If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.

CUDA incompatible with my gcc version

  1. Check the maximum supported GCC version for your CUDA version:

    CUDA version max supported GCC version
    11.1 10.0
    11 9
    10.1, 10.2 8
    9.2, 10.0 7
    9.0, 9.1 6
    8 5.3
    7 4.9
    5.5, 6 4.8
    4.2, 5 4.6
    4.1 4.5
    4.0 4.4
  2. Set an env var for that GCC version. For example, for CUDA 10.2:

    MAX_GCC_VERSION=8
    
  3. Make sure you have that version installed:

    sudo apt install gcc-$MAX_GCC_VERSION g++-$MAX_GCC_VERSION
    
  4. Add symlinks within CUDA folders:

    sudo ln -s /usr/bin/gcc-$MAX_GCC_VERSION /usr/local/cuda/bin/gcc 
    sudo ln -s /usr/bin/g++-$MAX_GCC_VERSION /usr/local/cuda/bin/g++
    

    (or substitute /usr/local/cuda with your CUDA installation path, if it's not there)

See this GitHub gist for more information on the CUDA-GCC compatibility table.

Axios handling errors

Actually, it's not possible with axios as of now. The status codes which falls in the range of 2xx only, can be caught in .then().

A conventional approach is to catch errors in the catch() block like below:

axios.get('/api/xyz/abcd')
  .catch(function (error) {
    if (error.response) {
      // Request made and server responded
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }

  });

Another approach can be intercepting requests or responses before they are handled by then or catch.

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

How to open a website when a Button is clicked in Android application?

Here is a workable answer.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.tutorial.todolist"
  android:versionCode="1"
  android:versionName="1.0">
  <uses-sdk android:minSdkVersion="3"></uses-sdk>
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".todolist"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  </application>
</manifest>

todolist.java

package com.tutorial.todolist;
import android.app.Activity; 
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle; 
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class todolist extends Activity {    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn = (Button) findViewById(R.id.btn_clickme);
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
                myWebLink.setData(Uri.parse("http://www.anddev.org"));
                    startActivity(myWebLink);
             }
        });
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="schemas.android.com/apk/res/android"
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" > 

    <Button android:id="@+id/btn_clickme" 
      android:text="Click me..." 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" /> 
</LinearLayout>

Real mouse position in canvas

The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:

canvas.addEventListener('click', event =>
{
    let bound = canvas.getBoundingClientRect();

    let x = event.clientX - bound.left - canvas.clientLeft;
    let y = event.clientY - bound.top - canvas.clientTop;

    context.fillRect(x, y, 16, 16);
});

If the canvas has padding-left or padding-top, subtract x and y via:

x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));

PostgreSQL: Drop PostgreSQL database through command line

You can run the dropdb command from the command line:

dropdb 'database name'

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name';

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname FORCE;

or

dropdb -f dbname

PHP - Redirect and send data via POST

here is the workaround sample.

function redirect_post($url, array $data)
{
    ?>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript">
            function closethisasap() {
                document.forms["redirectpost"].submit();
            }
        </script>
    </head>
    <body onload="closethisasap();">
    <form name="redirectpost" method="post" action="<? echo $url; ?>">
        <?php
        if ( !is_null($data) ) {
            foreach ($data as $k => $v) {
                echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
            }
        }
        ?>
    </form>
    </body>
    </html>
    <?php
    exit;
}

How do I check if string contains substring?

Returns number of times the keyword is included in the string.

var count = "I have one keyword".match(/keyword/g);
var clean_count = !count ? false : count.length;

How to make <a href=""> link look like a button?

Check Bootstrap's docs. A class .btn exists and works with the a tag, but you need to add a specific .btn-* class with the .btn class.

eg: <a class="btn btn-info"></a>

Ruby: character to ascii from a string

use "x".ord for a single character or "xyz".sum for a whole string.

jQuery set radio button

I found the answer here:
https://web.archive.org/web/20160421163524/http://vijayt.com/Post/Set-RadioButton-value-using-jQuery

Basically, if you want to check one radio button, you MUST pass the value as an array:

$('input:radio[name=cols]').val(['Site']);
$('input:radio[name=rows]').val(['Site']);

How to consume REST in Java

JAX-RS but you can also use regular DOM that comes with standard Java

How to debug a Flask app

You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.

CSS content generation before or after 'input' elements

With :before and :after you specify which content should be inserted before (or after) the content inside of that element. input elements have no content.

E.g. if you write <input type="text">Test</input> (which is wrong) the browser will correct this and put the text after the input element.

The only thing you could do is to wrap every input element in a span or div and apply the CSS on these.

See the examples in the specification:

For example, the following document fragment and style sheet:

<h2> Header </h2>               h2 { display: run-in; }
<p> Text </p>                   p:before { display: block; content: 'Some'; }

...would render in exactly the same way as the following document fragment and style sheet:

<h2> Header </h2>            h2 { display: run-in; }
<p><span>Some</span> Text </p>  span { display: block }

This is the same reason why it does not work for <br>, <img>, etc. (<textarea> seems to be special).

Display a jpg image on a JPanel

You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

Gmail: 530 5.5.1 Authentication Required. Learn more at

Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.

Is there a CSS selector for the first direct child only?

The CSS selector for the direct first-child in your case is:

.section > :first-child

The direct selector is > and the first child selector is :first-child

No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:

div.section > :first-child

In C#, how to check whether a string contains an integer?

You can check if string contains numbers only:

Regex.IsMatch(myStringVariable, @"^-?\d+$")

But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.

Another option - create extension method and move ugly code there:

public static bool IsInteger(this string s)
{
   if (String.IsNullOrEmpty(s))
       return false;

   int i;
   return Int32.TryParse(s, out i);
}

That will make your code more clean:

if (myStringVariable.IsInteger())
    // ...

How to get URL parameter using jQuery or plain JavaScript?

_x000D_
_x000D_
function GetRequestParam(param)_x000D_
{_x000D_
 var res = null;_x000D_
 try{_x000D_
  var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI_x000D_
  var ar = qs.split('&');_x000D_
  $.each(ar, function(a, b){_x000D_
   var kv = b.split('=');_x000D_
   if(param === kv[0]){_x000D_
    res = kv[1];_x000D_
    return false;//break loop_x000D_
   }_x000D_
  });_x000D_
 }catch(e){}_x000D_
 return res;_x000D_
}
_x000D_
_x000D_
_x000D_

Missing Maven dependencies in Eclipse project

Just in case anybody has tried all the other options and you are still stuck, try right-clicking on the project folder, head over to Maven option and click the "add dependency" button. For some reason Eclipse isn't updating the dependencies manually from the pom.xml at first try.

screen shot of menu selection

NuGet: 'X' already has a dependency defined for 'Y'

I tried the update, but it did not work for me. Helped:

  1. Uninstall NuGet => Tools => Extensions and update => Installed
  2. Install NuGet
  3. Reload Visual Studio

Format date and time in a Windows batch script

The following may not be a direct answer but a close one?

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%

At least it may be inspiring.

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Effective method to hide email from spam bots

I have a completely different take on this. I use MailHide for this.

MailHide is a system from Google whereby the user needs to complete a reCAPTCHA test to then reveal the email to them.

How to check if a file is empty in Bash?

Easiest way for checking file is empty or not:

if [ -s /path-to-file/filename.txt ]
then
     echo "File is not empty"
else
     echo "File is empty"
fi

You can also write it on single line:

[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"

How to clean node_modules folder of packages that are not in package.json?

simple just run

rm -r node_modules

in fact, you can delete any folder with this.

like rm -r AnyFolderWhichIsNotDeletableFromShiftDeleteOrDelete.

just open the gitbash move to root of the folder and run this command

Hope this will help.

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

Javascript dynamic array of strings

Just initialize an array and push the element on the array. It will automatic scale the array.

var a = [ ];

a.push('Some string'); console.log(a); // ['Some string'] 
a.push('another string'); console.log(a); // ['Some string', 'another string'] 
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".

Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.

In terms of your code, you created a view, but never specified the size. You need a

dataGridView1.ColumnCount = 5;

Before trying to access any columns. Modify

DataGridView dataGridView1 = new DataGridView();

dataGridView1.Columns[0].Name = "ItemID";

to

DataGridView dataGridView1 = new DataGridView();
dataGridView1.ColumnCount = 5;
dataGridView1.Columns[0].Name = "ItemID";

See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx

How to wait until an element exists?

This is a simple solution for those who are used to promises and don't want to use any third party libs or timers.

I have been using it in my projects for a while

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

To use it:

waitForElm('.some-class').then(elm => console.log(elm.textContent));

or with async/await

const elm = await waitForElm('.some-classs')

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.

Using Application context everywhere?

Some people have asked: how can the singleton return a null pointer? I'm answering that question. (I cannot answer in a comment because I need to post code.)

It may return null in between two events: (1) the class is loaded, and (2) the object of this class is created. Here's an example:

class X {
    static X xinstance;
    static Y yinstance = Y.yinstance;
    X() {xinstance=this;}
}
class Y {
    static X xinstance = X.xinstance;
    static Y yinstance;
    Y() {yinstance=this;}
}

public class A {
    public static void main(String[] p) {
    X x = new X();
    Y y = new Y();
    System.out.println("x:"+X.xinstance+" y:"+Y.yinstance);
    System.out.println("x:"+Y.xinstance+" y:"+X.yinstance);
    }
}

Let's run the code:

$ javac A.java 
$ java A
x:X@a63599 y:Y@9036e
x:null y:null

The second line shows that Y.xinstance and X.yinstance are null; they are null because the variables X.xinstance ans Y.yinstance were read when they were null.

Can this be fixed? Yes,

class X {
    static Y y = Y.getInstance();
    static X theinstance;
    static X getInstance() {if(theinstance==null) {theinstance = new X();} return theinstance;}
}
class Y {
    static X x = X.getInstance();
    static Y theinstance;
    static Y getInstance() {if(theinstance==null) {theinstance = new Y();} return theinstance;}
}

public class A {
    public static void main(String[] p) {
    System.out.println("x:"+X.getInstance()+" y:"+Y.getInstance());
    System.out.println("x:"+Y.x+" y:"+X.y);
    }
}

and this code shows no anomaly:

$ javac A.java 
$ java A
x:X@1c059f6 y:Y@152506e
x:X@1c059f6 y:Y@152506e

BUT this is not an option for the Android Application object: the programmer does not control the time when it is created.

Once again: the difference between the first example and the second one is that the second example creates an instance if the static pointer is null. But a programmer cannot create the Android application object before the system decides to do it.

UPDATE

One more puzzling example where initialized static fields happen to be null.

Main.java:

enum MyEnum {
    FIRST,SECOND;
    private static String prefix="<", suffix=">";
    String myName;
    MyEnum() {
        myName = makeMyName();
    }
    String makeMyName() {
        return prefix + name() + suffix;
    }
    String getMyName() {
        return myName;
    }
}
public class Main {
    public static void main(String args[]) {
        System.out.println("first: "+MyEnum.FIRST+" second: "+MyEnum.SECOND);
        System.out.println("first: "+MyEnum.FIRST.makeMyName()+" second: "+MyEnum.SECOND.makeMyName());
        System.out.println("first: "+MyEnum.FIRST.getMyName()+" second: "+MyEnum.SECOND.getMyName());
    }
}

And you get:

$ javac Main.java
$ java Main
first: FIRST second: SECOND
first: <FIRST> second: <SECOND>
first: nullFIRSTnull second: nullSECONDnull

Note that you cannot move the static variable declaration one line upper, the code will not compile.

What is the convention for word separator in Java package names?

All three are not the conventions.

Use com.stackoverflow.mypackage.

The package names do not follow camel casing or underscores or hyphens package naming convention.

Also, Google Java Style Guide specifies exactly the same (i.e. com.stackoverflow.mypackage) convention:

5.2.1 Package names

Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.

Google Java Style Guide: 5.2 Rules by identifier type: 5.2.1 Package names.

What does the "+=" operator do in Java?

As others have said, it's bitwise XOR. If you want to raise a number to a given power, use Math.pow(a , b), where a is a number and b is the power.

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

Call a Vue.js component method from outside the component

Say you have a child_method() in the child component:

export default {
    methods: {
        child_method () {
            console.log('I got clicked')
        }
    }
}

Now you want to execute the child_method from parent component:

<template>
    <div>
        <button @click="exec">Execute child component</button>
        <child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
    </div>
</template>

export default {
    methods: {
        exec () { //accessing the child component instance through $refs
            this.$refs.child.child_method() //execute the method belongs to the child component
        }
    }
}

If you want to execute a parent component method from child component:

this.$parent.name_of_method()

NOTE: It is not recommended to access the child and parent component like this.

Instead as best practice use Props & Events for parent-child communication.

If you want communication between components surely use vuex or event bus

Please read this very helpful article


C# with MySQL INSERT parameters

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

The following code works lately:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}

How do I change the root directory of an Apache server?

In RedHat 7.0: /etc/httpd/conf/httpd.conf