Programs & Examples On #Integer division

Anything related to the integer division operation, i.e. that special form of division which is performed between two integer numbers and which in math results in a quotient and a remainder. This is mostly relevant for languages which have specific integer data-types, for which the division is an integer division, or for languages having a specific operator/function to perform integer division.

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

Integer division with remainder in JavaScript?

If you need to calculate the remainder for very large integers, which the JS runtime cannot represent as such (any integer greater than 2^32 is represented as a float and so it loses precision), you need to do some trick.

This is especially important for checking many case of check digits which are present in many instances of our daily life (bank account numbers, credit cards, ...)

First of all you need your number as a string (otherwise you have already lost precision and the remainder does not make sense).

str = '123456789123456789123456789'

You now need to split your string in smaller parts, small enough so the concatenation of any remainder and a piece of string can fit in 9 digits.

digits = 9 - String(divisor).length

Prepare a regular expression to split the string

splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g')

For instance, if digits is 7, the regexp is

/.{1,7}(?=(.{7})+$)/g

It matches a nonempty substring of maximum length 7, which is followed ((?=...) is a positive lookahead) by a number of characters that is multiple of 7. The 'g' is to make the expression run through all string, not stopping at first match.

Now convert each part to integer, and calculate the remainders by reduce (adding back the previous remainder - or 0 - multiplied by the correct power of 10):

reducer = (rem, piece) => (rem * Math.pow(10, digits) + piece) % divisor

This will work because of the "subtraction" remainder algorithm:

n mod d = (n - kd) mod d

which allows to replace any 'initial part' of the decimal representation of a number with its remainder, without affecting the final remainder.

The final code would look like:

function remainder(num, div) {
  const digits = 9 - String(div).length;
  const splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g');
  const mult = Math.pow(10, digits);
  const reducer = (rem, piece) => (rem * mult + piece) % div;

  return str.match(splitter).map(Number).reduce(reducer, 0);
}

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

What is the behavior of integer division?

Will result always be the floor of the division?

No. The result varies, but variation happens only for negative values.

What is the defined behavior?

To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)

For positive values they are the same

int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0

For negative value this is different

int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0

Why does dividing two int not yield the right value when assigned to double?

c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is

  1. a/b is evaluated, creating a temporary of type int
  2. the value of the temporary is assigned to c after conversion to type double.

The value of a/b is determined without reference to its context (assignment to double).

Int division: Why is the result of 1/3 == 0?

Because you are doing integer division.

As @Noldorin says, if both operators are integers, then integer division is used.

The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.

If any of the operators is a double / float, then floating point arithmetic will take place. But you'll have the same problem if you do that:

int n = 1.0 / 3.0;

Find the division remainder of a number

The remainder of a division can be discovered using the operator %:

>>> 26%7
5

In case you need both the quotient and the modulo, there's the builtin divmod function:

>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)

How to do integer division in javascript (Getting division answer in int not float)?

var x = parseInt(455/10);

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

Integer division: How do you produce a double?

double num = 5;

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

[...]

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

5 can be expressed exactly as a double.

Rounding integer division (instead of truncating)

For some algorithms you need a consistent bias when 'nearest' is a tie.

// round-to-nearest with mid-value bias towards positive infinity
int div_nearest( int n, int d )
   {
   if (d<0) n*=-1, d*=-1;
   return (abs(n)+((d-(n<0?1:0))>>1))/d * ((n<0)?-1:+1);
   }

This works regardless of the sign of the numerator or denominator.


If you want to match the results of round(N/(double)D) (floating-point division and rounding), here are a few variations that all produce the same results:

int div_nearest( int n, int d )
   {
   int r=(n<0?-1:+1)*(abs(d)>>1); // eliminates a division
// int r=((n<0)^(d<0)?-1:+1)*(d/2); // basically the same as @ericbn
// int r=(n*d<0?-1:+1)*(d/2); // small variation from @ericbn
   return (n+r)/d;
   }

Note: The relative speed of (abs(d)>>1) vs. (d/2) is likely to be platform dependent.

Why is division in Ruby returning an integer instead of decimal value?

Fixnum#to_r is not mentioned here, it was introduced since ruby 1.9. It converts Fixnum into rational form. Below are examples of its uses. This also can give exact division as long as all the numbers used are Fixnum.

 a = 1.to_r  #=> (1/1) 
 a = 10.to_r #=> (10/1) 
 a = a / 3   #=> (10/3) 
 a = a * 3   #=> (10/1) 
 a.to_f      #=> 10.0

Example where a float operated on a rational number coverts the result to float.

a = 5.to_r   #=> (5/1) 
a = a * 5.0  #=> 25.0 

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

How to store images in mysql database using php

insert image zh

-while we insert image in database using insert query

$Image = $_FILES['Image']['name'];
    if(!$Image)
    {
      $Image="";
    }
    else
    {
      $file_path = 'upload/';
      $file_path = $file_path . basename( $_FILES['Image']['name']);    
      if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) 
     { 
}
}

Auto-click button element on page load using jQuery

You can use that and adjust the time you want to launch 1= onload 2000= 2 sec

_x000D_
_x000D_
$(document).ready(function(){
 $('#click').click(function(){
        alert('button clicked');
    });
  // set time out 2 sec
     setTimeout(function(){
        $('#click').trigger('click');
    }, 2000);
});
_x000D_
.container{
padding-top:50px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="col text-center">
<button id="click" class="btn btn-danger">Jquery Auto Click</button>
  </div>
   </div>
_x000D_
_x000D_
_x000D_

How to check whether a Button is clicked by using JavaScript

You can add a click event handler for this:

document.getElementById('button').onclick = function() {
   alert("button was clicked");
}?;?

This will alert when it's clicked, if you want to track it for later, just set a variable to true in that function instead of alerting, or variable++ if you want to count the number of clicks, whatever your ultimate use is. You can see an example here.

AngularJS does not send hidden field value

Here I would like to share my working code :

_x000D_
_x000D_
<input type="text" name="someData" ng-model="data" ng-init="data=2" style="display: none;"/>_x000D_
OR_x000D_
<input type="hidden" name="someData" ng-model="data" ng-init="data=2"/>_x000D_
OR_x000D_
<input type="hidden" name="someData" ng-init="data=2"/>
_x000D_
_x000D_
_x000D_

How to convert a string with comma-delimited items to a list in Python?

m = '[[1,2,3],[4,5,6],[7,8,9]]'

m= eval(m.split()[0])

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Formatting MM/DD/YYYY dates in textbox in VBA

While I agree with what's mentioned in the answers below, suggesting that this is a very bad design for a Userform unless copious amounts of error checks are included...

to accomplish what you need to do, with minimal changes to your code, there are two approaches.

  1. Use KeyUp() event instead of Change event for the textbox. Here is an example:

    Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    
        Dim TextStr As String
        TextStr = TextBox2.Text
    
        If KeyCode <> 8 Then ' i.e. not a backspace
    
            If (Len(TextStr) = 2 Or Len(TextStr) = 5) Then
                TextStr = TextStr & "/"
            End If
    
        End If
        TextBox2.Text = TextStr
    End Sub
    
  2. Alternately, if you need to use the Change() event, use the following code. This alters the behavior so the user keeps entering the numbers, as

    12072003
    

while the result as he's typing appears as

    12/07/2003

But the '/' character appears only once the first character of the DD i.e. 0 of 07 is entered. Not ideal, but will still handle backspaces.

    Private Sub TextBox1_Change()
        Dim TextStr As String

        TextStr = TextBox1.Text

        If (Len(TextStr) = 3 And Mid(TextStr, 3, 1) <> "/") Then
            TextStr = Left(TextStr, 2) & "/" & Right(TextStr, 1)
        ElseIf (Len(TextStr) = 6 And Mid(TextStr, 6, 1) <> "/") Then
            TextStr = Left(TextStr, 5) & "/" & Right(TextStr, 1)
        End If

        TextBox1.Text = TextStr
    End Sub

How to round up a number to nearest 10?

round($number, -1);

This will round $number to the nearest 10. You can also pass a third variable if necessary to change the rounding mode.

More info here: http://php.net/manual/en/function.round.php

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

How to write an XPath query to match two attributes?

//div[@id='..' and @class='...]

should do the trick. That's selecting the div operators that have both attributes of the required value.

It's worth using one of the online XPath testbeds to try stuff out.

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

You can parse the date using the Date constructor, then spit out the individual time components:

_x000D_
_x000D_
function convert(str) {_x000D_
  var date = new Date(str),_x000D_
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
    day = ("0" + date.getDate()).slice(-2);_x000D_
  return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
_x000D_
_x000D_

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

_x000D_
_x000D_
function convert(str) {_x000D_
  var mnths = {_x000D_
      Jan: "01",_x000D_
      Feb: "02",_x000D_
      Mar: "03",_x000D_
      Apr: "04",_x000D_
      May: "05",_x000D_
      Jun: "06",_x000D_
      Jul: "07",_x000D_
      Aug: "08",_x000D_
      Sep: "09",_x000D_
      Oct: "10",_x000D_
      Nov: "11",_x000D_
      Dec: "12"_x000D_
    },_x000D_
    date = str.split(" ");_x000D_
_x000D_
  return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
_x000D_
_x000D_

Get the value of checked checkbox?

None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):

_x000D_
_x000D_
function checkbox() {_x000D_
  var checked = false;_x000D_
  if (document.querySelector('#opt1:checked')) {_x000D_
     checked = true;_x000D_
  }_x000D_
  document.getElementById('msg').innerText = checked;_x000D_
}
_x000D_
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
_x000D_
_x000D_
_x000D_

How to create a trie in Python

from collections import defaultdict

Define Trie:

_trie = lambda: defaultdict(_trie)

Create Trie:

trie = _trie()
for s in ["cat", "bat", "rat", "cam"]:
    curr = trie
    for c in s:
        curr = curr[c]
    curr.setdefault("_end")

Lookup:

def word_exist(trie, word):
    curr = trie
    for w in word:
        if w not in curr:
            return False
        curr = curr[w]
    return '_end' in curr

Test:

print(word_exist(trie, 'cam'))

Calculate relative time in C#

/** 
 * {@code date1} has to be earlier than {@code date2}.
 */
public static String relativize(Date date1, Date date2) {
    assert date2.getTime() >= date1.getTime();

    long duration = date2.getTime() - date1.getTime();
    long converted;

    if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "day" : "days");
    } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "hour" : "hours");
    } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "minute" : "minutes");
    } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "second" : "seconds");
    } else {
        return "just now";
    }
}

Can I restore a single table from a full mysql mysqldump file?

You can try to use sed in order to extract only the table you want.

Let say the name of your table is mytable and the file mysql.dump is the file containing your huge dump:

$ sed -n -e '/CREATE TABLE.*`mytable`/,/Table structure for table/p' mysql.dump > mytable.dump

This will copy in the file mytable.dump what is located between CREATE TABLE mytable and the next CREATE TABLE corresponding to the next table.

You can then adjust the file mytable.dump which contains the structure of the table mytable, and the data (a list of INSERT).

I keep getting "Uncaught SyntaxError: Unexpected token o"

Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.

Parsed data from jquery success handler for text/html response:

var parsed = JSON.parse(data);

Parsed data from jquery success handler for application/json response:

var parsed = data;

Check if value already exists within list of dictionaries?

Perhaps a function along these lines is what you're after:

 def add_unique_to_dict_list(dict_list, key, value):
  for d in dict_list:
     if key in d:
        return d[key]

  dict_list.append({ key: value })
  return value

How to prepend a string to a column value in MySQL?

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

How do I put double quotes in a string in vba?

All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard", In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.

Get file size before uploading

Best solution working on all browsers ;)

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject, 
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

UPDATE : We'll use this function to check if it's IE browser or not

function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){  
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}

Accidentally committed .idea directory files into git

You should add a .gitignore file to your project and add /.idea to it. You should add each directory / file in one line.

If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea to the new line.

After that run git rm -r --cached .idea command.

If you faced an error you can run git rm -r -f --cached .idea command. After all run git add . and then git commit -m "Removed .idea directory and added a .gitignore file" and finally push the changes by running git push command.

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

Twitter Bootstrap modal on mobile devices

The solution by niftylettuce in issue 2130 seems to fix modals in all mobile platforms...

9/1/12 UPDATE: The fix has been updated here: twitter bootstrap jquery plugins

(the code below is older but still works)

// # Twitter Bootstrap modal responsive fix by @niftylettuce
//  * resolves #407, #1017, #1339, #2130, #3361, #3362, #4283
//   <https://github.com/twitter/bootstrap/issues/2130>
//  * built-in support for fullscreen Bootstrap Image Gallery
//    <https://github.com/blueimp/Bootstrap-Image-Gallery>

// **NOTE:** If you are using .modal-fullscreen, you will need
//  to add the following CSS to `bootstrap-image-gallery.css`:
//
//  @media (max-width: 480px) {
//    .modal-fullscreen {
//      left: 0 !important;
//      right: 0 !important;
//      margin-top: 0 !important;
//      margin-left: 0 !important;
//    }
//  }
//

var adjustModal = function($modal) {
  var top;
  if ($(window).width() <= 480) {
    if ($modal.hasClass('modal-fullscreen')) {
      if ($modal.height() >= $(window).height()) {
        top = $(window).scrollTop();
      } else {
        top = $(window).scrollTop() + ($(window).height() - $modal.height()) / 2;
      }
    } else if ($modal.height() >= $(window).height() - 10) {
      top = $(window).scrollTop() + 10;
    } else {
      top = $(window).scrollTop() + ($(window).height() - $modal.height()) / 2;
    }
  } else {
    top = '50%';
    if ($modal.hasClass('modal-fullscreen')) {
      $modal.stop().animate({
          marginTop  : -($modal.outerHeight() / 2)
        , marginLeft : -($modal.outerWidth() / 2)
        , top        : top
      }, "fast");
      return;
    }
  }
  $modal.stop().animate({ 'top': top }, "fast");
};

var show = function() {
  var $modal = $(this);
  adjustModal($modal);
};

var checkShow = function() {
  $('.modal').each(function() {
    var $modal = $(this);
    if ($modal.css('display') !== 'block') return;
    adjustModal($modal);
  });
};

var modalWindowResize = function() {
  $('.modal').not('.modal-gallery').on('show', show);
  $('.modal-gallery').on('displayed', show);
  checkShow();
};

$(modalWindowResize);
$(window).resize(modalWindowResize);
$(window).scroll(checkShow);

How to use Object.values with typescript?

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

You can do the following with Unnamed Columns:

  1. Delete unnamed columns
  2. Rename them (if you want to use them)

file.csv

,A,B,C
0,1,2,3
1,4,5,6
2,7,8,9

#read file df = pd.read_csv('file.csv')

Method 1: Delete Unnamed Columns

# delete one by one like column is 'Unnamed: 0' so use it's name
df.drop('Unnamed: 0', axis=1, inplace=True)

#delete all Unnamed Columns in a single code of line using regex
df.drop(df.filter(regex="Unnamed"),axis=1, inplace=True)

Method 2: Rename Unnamed Columns

df.rename(columns = {'Unnamed: 0':'Name'}, inplace = True)

If you want to write out with a blank header as in the input file, just choose 'Name' above to be ''.

Running Jupyter via command line on Windows

Using python 3.6.3. Here after installing Jupyter through command 'python -m pip install jupyter', 'jupyter notebook' command didn't work for me using windows command prompt.

But, finally 'python -m notebook' did work and made jupyter notebook to run on local.

http://localhost:8888/tree

How to Create Multiple Where Clause Query Using Laravel Eloquent?

public function search()
{
    if (isset($_GET) && !empty($_GET))
    {
        $prepareQuery = '';
        foreach ($_GET as $key => $data)
        {
            if ($data)
            {
                $prepareQuery.=$key . ' = "' . $data . '" OR ';
            }
        }
        $query = substr($prepareQuery, 0, -3);
        if ($query)
            $model = Businesses::whereRaw($query)->get();
        else
            $model = Businesses::get();

        return view('pages.search', compact('model', 'model'));
    }
}

Adding quotes to a string in VBScript

I usually do this:

Const Q = """"

Dim a, g
a = "xyz"  
g = "abcd " & Q & a & Q

If you need to wrap strings in quotes more often in your code and find the above approach noisy or unreadable, you can also wrap it in a function:

a = "xyz"  
g = "abcd " & Q(a)

Function Q(s)
  Q = """" & s & """"
End Function

Filter an array using a formula (without VBA)

Today, in Office 365, Excel has so called 'array functions'. The filter function does exactly what you want. No need to use CTRL+SHIFT+ENTER anymore, a simple enter will suffice.

In Office 365, your problem would be simply solved by using:

=VLOOKUP(A3, FILTER(A2:C6, B2:B6="B"), 3, FALSE)

Parsing date string in Go

I will suggest using time.RFC3339 constant from time package. You can check other constants from time package. https://golang.org/pkg/time/#pkg-constants

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Time parsing");
    dateString := "2014-11-12T11:45:26.371Z"
    time1, err := time.Parse(time.RFC3339,dateString);
    if err!=nil {
    fmt.Println("Error while parsing date :", err);
    }
    fmt.Println(time1); 
}

How to get the first word of a sentence in PHP?

personally strsplit / explode / strtok does not support word boundaries, so to get a more accute split use regular expression with the \w

preg_split('/[\s]+/',$string,1);

This would split words with boundaries to a limit of 1.

Can I make a phone call from HTML on Android?

Generally on Android, if you simply display the phone number, and the user taps on it, it will pull it up in the dialer. So, you could simply do

For more information, call us at <b>416-555-1234</b>

When the user taps on the bold part, since it's formatted like a phone number, the dialer will pop up, and show 4165551234 in the phone number field. The user then just has to hit the call button.

You might be able to do

For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a>

to cover both devices, but I'm not sure how well this would work. I'll give it a try shortly and let you know.

EDIT: I just gave this a try on my HTC Magic running a rooted Rogers 1.5 with SenseUI:

For more information, call us at <a href='tel:416-555-1234'>416-555-1234</a><br />
<br />
Call at <a href='tel:416-555-1234'>our number</a>
<br />
<br />
<a href='416-555-1234'>Blah</a>
<br />
<br />
For more info, call <b>416-555-1234</b>

The first one, surrounding with the link and printing the phone number, worked perfectly. Pulled up the dialer with the hyphens and all. The second, saying our number with the link, worked exactly the same. This means that using <a href='tel:xxx-xxx-xxxx'> should work across the board, but I wouldn't suggest taking my one test as conclusive.

Linking straight to the number did the expected: Tried to pull up the nonexistent file from the server.

The last one did as I mentioned above, and pulled up the dialer, but without the nice formatting hyphens.

How can I find out the current route in Rails?

In rails 3 you can access the Rack::Mount::RouteSet object via the Rails.application.routes object, then call recognize on it directly

route, match, params = Rails.application.routes.set.recognize(controller.request)

that gets the first (best) match, the following block form loops over the matching routes:

Rails.application.routes.set.recognize(controller.request) do |r, m, p|
  ... do something here ...
end

once you have the route, you can get the route name via route.name. If you need to get the route name for a particular URL, not the current request path, then you'll need to mock up a fake request object to pass down to rack, check out ActionController::Routing::Routes.recognize_path to see how they're doing it.

Get all variables sent with POST?

So, something like the $_POST array?

You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Centering a Twitter Bootstrap button

Wrap in a div styled with "text-center" class.

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

How to Parse JSON Array with Gson

Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.

To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.

It is necessary to include the Json library in the project. If you are developing on Android, it is included:

/**
 * Convert JSON string to a list of objects
 * @param sJson String sJson to be converted
 * @param tClass Class
 * @return List<T> list of objects generated or null if there was an error
 */
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){

    try{
        Gson gson = new Gson();
        List<T> listObjects = new ArrayList<>();

        //read each object of array with Json library
        JSONArray jsonArray = new JSONArray(sJson);
        for(int i=0; i<jsonArray.length(); i++){

            //get the object
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            //get string of object from Json library to convert it to real object with Gson library
            listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
        }

        //return list with all generated objects
        return listObjects;

    }catch(Exception e){
        e.printStackTrace();
    }

    //error: return null
    return null;
}

BACKUP LOG cannot be performed because there is no current database backup

I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.

Bootstrap-select - how to fire event on change

Simplest solution would be -

$('.selectpicker').trigger('change');

Does Index of Array Exist

You can use the length of the array, and see if your arbitrary number fits in that range. For example, if you have an array of size 10, then array[25] isn't valid because 25 is not less than 10.

Scala how can I count the number of occurrences in a list

I ran into the same problem but wanted to count multiple items in one go..

val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.foldLeft(Map.empty[String, Int]) { (m, x) => m + ((x, m.getOrElse(x, 0) + 1)) }
res1: scala.collection.immutable.Map[String,Int] = Map(apple -> 3, oranges -> 3, banana -> 1)

https://gist.github.com/sharathprabhal/6890475

How do I add a bullet symbol in TextView?

Another best way to add bullet in any text view is stated below two steps:

First, create a drawable

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <!--set color of the bullet-->
   <solid 
       android:color="#666666"/> //set color of bullet

    <!--set size of the bullet-->
   <size 
       android:width="120dp"
        android:height="120dp"/>
</shape>

Then add this drawable in textview and set its pedding by using below properties

android:drawableStart="@drawable/bullet"
android:drawablePadding="10dp"

Html.fromHtml deprecated in Android N

update: as @Andy mentioned below Google has created HtmlCompat which can be used instead of the method below. Add this dependency implementation 'androidx.core:core:1.0.1 to the build.gradle file of your app. Make sure you use the latest version of androidx.core:core.

This allows you to use:

HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY);

You can read more about the different flags on the HtmlCompat-documentation

original answer: In Android N they introduced a new Html.fromHtml method. Html.fromHtml now requires an additional parameter, named flags. This flag gives you more control about how your HTML gets displayed.

On Android N and above you should use this new method. The older method is deprecated and may be removed in the future Android versions.

You can create your own Util-method which will use the old method on older versions and the newer method on Android N and above. If you don't add a version check your app will break on lower Android versions. You can use this method in your Util class.

@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    if(html == null){
        // return an empty spannable if the html is null
        return new SpannableString("");
    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        // FROM_HTML_MODE_LEGACY is the behaviour that was used for versions below android N
        // we are using this flag to give a consistent behaviour
        return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    } else {
        return Html.fromHtml(html);
    }
}

You can convert the HTML.FROM_HTML_MODE_LEGACY into an additional parameter if you want. This gives you more control about it which flag to use.

You can read more about the different flags on the Html class documentation

How do I get next month date from today's date and insert it in my database?

You do not actually need PHP functions to achieve this. You can already do simple date manipulations directly in SQL, for example:

$sql1 = "
    UPDATE `users` SET 
    `start_date` = CURDATE(), 
    `end_date` = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)  
    WHERE `users`.`id` = '" . $id . "';
";

Refer to http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_addtime

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

ASP.NET MVC controller actions that return JSON or partial html

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

Method from the jquery getJSON method by simply...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

Loginto your gmail account https://myaccount.google.com/u/4/security-checkup/4

enter image description here

(See photo) review all locations Google may have blocked for "unknown" or suspicious activity.

mkdir -p functionality in Python

With Pathlib from python3 standard library:

Path(mypath).mkdir(parents=True, exist_ok=True)

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command). If exist_ok is false (the default), an FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.

Changed in version 3.5: The exist_ok parameter was added.

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

It's the Simple way to convert to format

 DateTime.Now.ToString("yyyyMMdd");

MySql server startup error 'The server quit without updating PID file '

If your system has multiple version of Mysql then you are likely going to hit this PID error

we can begin with killing all MySQL process
sudo killall mysqld

Go to /usr/local choose which MySQL version you want to have, then provide the MySQL permission to that. In my case I needed version 8.
sudo chown -R mysql mysql-8.0.21-macos10.15-x86_64

Go to the folder /usr/local/mysql-8.0.21-macos10.15-x86_64 & start SQL server
sudo ./mysql.server start(Enter your laptop password) If it gives below output... the PID issue is solved

@xxxx-M-R0SU support-files $ sudo ./mysql.server start Starting MySQL .. SUCCESS!

Spring Data JPA and Exists query

Since Spring data 1.12 you can use the query by Example functionnality by extending the QueryByExampleExecutor interface (The JpaRepositoryalready extends it).
Then you can use this query (among others) :

<S extends T> boolean exists(Example<S> example);

Consider an entity MyEntity which as a property name, you want to know if an entity with that name exists, ignoring case, then the call to this method can look like this :

//The ExampleMatcher is immutable and can be static I think
ExampleMatcher NAME_MATCHER = ExampleMatcher.matching()
            .withMatcher("name", GenericPropertyMatchers.ignoreCase());
Example<MyEntity> example = Example.<MyEntity>of(new MyEntity("example name"), NAME_MATCHER);
boolean exists = myEntityRepository.exists(example);

How do I display image in Alert/confirm box in Javascript?

Snarky yet potentially useful answer: http://picascii.com/ (currently down)

https://www.ascii-art-generator.org/es.html (don't forget to put a \n after each line!)

How to get Python requests to trust a self signed SSL certificate?

With the verify parameter you can provide a custom certificate authority bundle

requests.get(url, verify=path_to_bundle_file)

From the docs:

You can pass verify the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

Why use the INCLUDE clause when creating an index?

There is a limit to the total size of all columns inlined into the index definition. That said though, I have never had to create index that wide. To me, the bigger advantage is the fact that you can cover more queries with one index that has included columns as they don't have to be defined in any particular order. Think about is as an index within the index. One example would be the StoreID (where StoreID is low selectivity meaning that each store is associated with a lot of customers) and then customer demographics data (LastName, FirstName, DOB): If you just inline those columns in this order (StoreID, LastName, FirstName, DOB), you can only efficiently search for customers for which you know StoreID and LastName.

On the other hand, defining the index on StoreID and including LastName, FirstName, DOB columns would let you in essence do two seeks- index predicate on StoreID and then seek predicate on any of the included columns. This would let you cover all possible search permutationsas as long as it starts with StoreID.

How do I view 'git diff' output with my preferred diff tool/ viewer?

Solution for Windows/msys git

After reading the answers, I discovered a simpler way that involves changing only one file.

  1. Create a batch file to invoke your diff program, with argument 2 and 5. This file must be somewhere in your path. (If you don't know where that is, put it in c:\windows). Call it, for example, "gitdiff.bat". Mine is:

    @echo off
    REM This is gitdiff.bat
    "C:\Program Files\WinMerge\WinMergeU.exe" %2 %5
    
  2. Set the environment variable to point to your batch file. For example:GIT_EXTERNAL_DIFF=gitdiff.bat. Or through powershell by typing git config --global diff.external gitdiff.bat.

    It is important to not use quotes, or specify any path information, otherwise it won't work. That's why gitdiff.bat must be in your path.

Now when you type "git diff", it will invoke your external diff viewer.

How to convert a time string to seconds?

def time_to_sec(time):
    sep = ','
    rest = time.split(sep, 1)[0]
    splitted = rest.split(":")
    emel = len(splitted) - 1
    i = 0
    summa = 0
    for numb in splitted:
        szor = 60 ** (emel - i)
        i += 1
        summa += int(numb) * szor
    return summa

How to set a default value with Html.TextBoxFor?

You can simply do :

<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>

or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :

@Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.

Can I set the height of a div based on a percentage-based width?

This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box CSS attribute:

_x000D_
_x000D_
div {_x000D_
  border: 1px solid red;_x000D_
  width: 40%;_x000D_
  padding: 40%;_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
}_x000D_
p {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div>_x000D_
  <p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adjust percentages to your liking. Here is a JSFiddle

CodeIgniter removing index.php from url

you can go to application\config\config.php file and remove index.php


 $config['index_page'] = 'index.php';   // delete index.php

Change to


 $config['index_page'] = '';

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

How to force Selenium WebDriver to click on element which is not currently visible?

You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.

If this error happens, check if:

  • element is visible in your viewport, try to maximize the current window that webdriver is using (e.g. maximize() in node.js, maximize_window() in Python),
  • your element is not appearing twice (under the same selector), and you're selecting the wrong one,
  • if your element is hidden, then consider making it visible,
  • if you'd like to access/change value of hidden element despite of the limitation, then use Javascript for that (e.g. executeScript() in node.js, execute_script() in Python).

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Sorry, no reputation to add this as a comment. So it goes as an complementary answer.

Depending on how often you will call clock_gettime(), you should keep in mind that only some of the "clocks" are provided by Linux in the VDSO (i.e. do not require a syscall with all the overhead of one -- which only got worse when Linux added the defenses to protect against Spectre-like attacks).

While clock_gettime(CLOCK_MONOTONIC,...), clock_gettime(CLOCK_REALTIME,...), and gettimeofday() are always going to be extremely fast (accelerated by the VDSO), this is not true for, e.g. CLOCK_MONOTONIC_RAW or any of the other POSIX clocks.

This can change with kernel version, and architecture.

Although most programs don't need to pay attention to this, there can be latency spikes in clocks accelerated by the VDSO: if you hit them right when the kernel is updating the shared memory area with the clock counters, it has to wait for the kernel to finish.

Here's the "proof" (GitHub, to keep bots away from kernel.org): https://github.com/torvalds/linux/commit/2aae950b21e4bc789d1fc6668faf67e8748300b7

JQuery Validate Dropdown list

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Remove Existing/Configured System Library: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries -> (Select) JRE System Library [(For me)jre1.8.0_231] -> Remove.

Currently you are at same location: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries

Now Add Same System Library Again: Add Library -> JRE System Library -> Workspace default JRE ((For me)jre1.8.0_231) -> Finish -> Apply -> Close.

Now wait to finish it.

How to setup FTP on xampp

XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.

Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :

  1. Open a new Linux terminal and ensure you are logged in as root.

  2. Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.

groupadd ftp

  1. Add your account (in this example, susan) to the new group. Add other users if needed.

usermod -a -G ftp susan

  1. Change the ownership and permissions of the htdocs/ subdirectory of the XAMPP installation directory (typically, /opt/lampp) so that it is writable by the the new ftp group.

cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs

  1. Ensure that proFTPD is running in the XAMPP control panel.

You can now transfer files to the XAMPP server using the steps below:

  1. Start an FTP client like winSCP or FileZilla and enter connection details as below.

If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.

Use "21" as the port.

Enter your Linux username and password as your FTP credentials.

Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.

  1. Transfer the file from your home directory to the server using normal FTP transfer conventions. If you’re using a graphical FTP client, you can usually drag and drop the file from one directory to the other. If you’re using a command-line FTP client, you can use the FTP PUT command.

Once the file is successfully transferred, you should be able to see it in action.

Read XLSX file in Java

I'm not very happy with any of the options so I ended up requesting the file in Excel 97 formate. The POI works great for that. Thanks everyone for the help.

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

Find first element by predicate

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

Define "First"? If the table has a PK then it will be ordered by that, and you can delete by that:

DECLARE @TABLE TABLE
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Data NVARCHAR(50) NOT NULL
)

INSERT INTO @TABLE(Data)
SELECT 'Hello' UNION
SELECT 'World' 

SET ROWCOUNT 1
DELETE FROM @TABLE
SET ROWCOUNT 0

SELECT * FROM @TABLE

If the table has no PK, then ordering won't be guaranteed...

How to determine if a point is in a 2D triangle?

By using the analytic solution to the barycentric coordinates (pointed out by Andreas Brinck) and:

  • not distributing the multiplication over the parenthesized terms
  • avoiding computing several times the same terms by storing them
  • reducing comparisons (as pointed out by coproc and Thomas Eding)

One can minimize the number of "costly" operations:

function ptInTriangle(p, p0, p1, p2) {
    var dX = p.x-p2.x;
    var dY = p.y-p2.y;
    var dX21 = p2.x-p1.x;
    var dY12 = p1.y-p2.y;
    var D = dY12*(p0.x-p2.x) + dX21*(p0.y-p2.y);
    var s = dY12*dX + dX21*dY;
    var t = (p2.y-p0.y)*dX + (p0.x-p2.x)*dY;
    if (D<0) return s<=0 && t<=0 && s+t>=D;
    return s>=0 && t>=0 && s+t<=D;
}

Code can be pasted in Perro Azul jsfiddle or try it by clicking "Run code snippet" below

_x000D_
_x000D_
var ctx = $("canvas")[0].getContext("2d");_x000D_
var W = 500;_x000D_
var H = 500;_x000D_
_x000D_
var point = { x: W / 2, y: H / 2 };_x000D_
var triangle = randomTriangle();_x000D_
_x000D_
$("canvas").click(function(evt) {_x000D_
    point.x = evt.pageX - $(this).offset().left;_x000D_
    point.y = evt.pageY - $(this).offset().top;_x000D_
    test();_x000D_
});_x000D_
_x000D_
$("canvas").dblclick(function(evt) {_x000D_
    triangle = randomTriangle();_x000D_
    test();_x000D_
});_x000D_
_x000D_
test();_x000D_
_x000D_
function test() {_x000D_
    var result = ptInTriangle(point, triangle.a, triangle.b, triangle.c);_x000D_
    _x000D_
    var info = "point = (" + point.x + "," + point.y + ")\n";_x000D_
    info += "triangle.a = (" + triangle.a.x + "," + triangle.a.y + ")\n";_x000D_
    info += "triangle.b = (" + triangle.b.x + "," + triangle.b.y + ")\n";_x000D_
    info += "triangle.c = (" + triangle.c.x + "," + triangle.c.y + ")\n";_x000D_
    info += "result = " + (result ? "true" : "false");_x000D_
_x000D_
    $("#result").text(info);_x000D_
    render();_x000D_
}_x000D_
_x000D_
function ptInTriangle(p, p0, p1, p2) {_x000D_
    var A = 1/2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);_x000D_
    var sign = A < 0 ? -1 : 1;_x000D_
    var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;_x000D_
    var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;_x000D_
    _x000D_
    return s > 0 && t > 0 && (s + t) < 2 * A * sign;_x000D_
}_x000D_
_x000D_
function render() {_x000D_
    ctx.fillStyle = "#CCC";_x000D_
    ctx.fillRect(0, 0, 500, 500);_x000D_
    drawTriangle(triangle.a, triangle.b, triangle.c);_x000D_
    drawPoint(point);_x000D_
}_x000D_
_x000D_
function drawTriangle(p0, p1, p2) {_x000D_
    ctx.fillStyle = "#999";_x000D_
    ctx.beginPath();_x000D_
    ctx.moveTo(p0.x, p0.y);_x000D_
    ctx.lineTo(p1.x, p1.y);_x000D_
    ctx.lineTo(p2.x, p2.y);_x000D_
    ctx.closePath();_x000D_
    ctx.fill();_x000D_
    ctx.fillStyle = "#000";_x000D_
    ctx.font = "12px monospace";_x000D_
    ctx.fillText("1", p0.x, p0.y);_x000D_
    ctx.fillText("2", p1.x, p1.y);_x000D_
    ctx.fillText("3", p2.x, p2.y);_x000D_
}_x000D_
_x000D_
function drawPoint(p) {_x000D_
    ctx.fillStyle = "#F00";_x000D_
    ctx.beginPath();_x000D_
    ctx.arc(p.x, p.y, 5, 0, 2 * Math.PI);_x000D_
    ctx.fill();_x000D_
}_x000D_
_x000D_
function rand(min, max) {_x000D_
 return Math.floor(Math.random() * (max - min + 1)) + min;_x000D_
}_x000D_
_x000D_
function randomTriangle() {_x000D_
    return {_x000D_
        a: { x: rand(0, W), y: rand(0, H) },_x000D_
        b: { x: rand(0, W), y: rand(0, H) },_x000D_
        c: { x: rand(0, W), y: rand(0, H) }_x000D_
    };_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<pre>Click: place the point._x000D_
Double click: random triangle.</pre>_x000D_
<pre id="result"></pre>_x000D_
<canvas width="500" height="500"></canvas>
_x000D_
_x000D_
_x000D_

Leading to:

  • variable "recalls": 30
  • variable storage: 7
  • additions: 4
  • subtractions: 8
  • multiplications: 6
  • divisions: none
  • comparisons: 4

This compares quite well with Kornel Kisielewicz solution (25 recalls, 1 storage, 15 subtractions, 6 multiplications, 5 comparisons), and might be even better if clockwise/counter-clockwise detection is needed (which takes 6 recalls, 1 addition, 2 subtractions, 2 multiplications and 1 comparison in itself, using the analytic solution determinant, as pointed out by rhgb).

jQuery select option elements by value

You can use .val() to select the value, like the following:

function select_option(i) {
    $("#span_id select").val(i);
}

Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

how to fetch data from database in Hibernate

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

Python IndentationError: unexpected indent

Run your program with

python -t script.py

This will warn you if you have mixed tabs and spaces.

On *nix systems, you can see where the tabs are by running

cat -A script.py

and you can automatically convert tabs to 4 spaces with the command

expand -t 4 script.py > fixed_script.py

PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won't get this problem with a programming editor.

PPS. For emacs users, M-x whitespace-mode will show the same info as cat -A from within an emacs buffer!

What are the differences between normal and slim package of jquery?

The short answer taken from the announcement of jQuery 3.0 Final Release :

Along with the regular version of jQuery that includes the ajax and effects modules, we’re releasing a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code.

The file size (gzipped) is about 6k smaller, 23.6k vs 30k.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

Latest VS code :

  • if you can't see the settings.json, go to menu File -> Preferences -> Settings (or press on Ctrl+,)
  • Settings appear, see two tabs User (selected by default) and Workspace. Go to User -> Features -> Terminal
  • Terminal section appear, see link edit in settings.json. Click and add "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",
  • Save and Restart VS code.

Bash terminal will reflect on the terminal.

TypeScript hashmap/dictionary interface

var x : IHash = {};
x['key1'] = 'value1';
x['key2'] = 'value2';

console.log(x['key1']);
// outputs value1

console.log(x['key2']);
// outputs value2

If you would like to then iterate through your dictionary, you can use.

Object.keys(x).forEach((key) => {console.log(x[key])});

Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.

You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.

You could use it like a hashset by just assigning the same value to the key and its value.

if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.

var valueToAdd = 'one';
if(!x[valueToAdd])
   x[valueToAdd] = valueToAdd;

or you could build your own class to act as a hashset of sorts.

Class HashSet{
  private var keys: IHash = {};
  private var values: string[] = [];

  public Add(key: string){
    if(!keys[key]){
      values.push(key);
      keys[key] = key;
    }
  }

  public GetValues(){
    // slicing the array will return it by value so users cannot accidentally
    // start playing around with your array
    return values.slice();
  }
}

How to stop a PowerShell script on the first error?

Sadly, due to buggy cmdlets like New-RegKey and Clear-Disk, none of these answers are enough. I've currently settled on the following code in a file called ps_support.ps1:

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$PSDefaultParameterValues['*:ErrorAction']='Stop'
function ThrowOnNativeFailure {
    if (-not $?)
    {
        throw 'Native Failure'
    }
}

Then in any powershell file, after the CmdletBinding and Param for the file (if present), I have the following:

$ErrorActionPreference = "Stop"
. "$PSScriptRoot\ps_support.ps1"

The duplicated ErrorActionPreference = "Stop" line is intentional. If I've goofed and somehow gotten the path to ps_support.ps1 wrong, that needs to not silently fail!

I keep ps_support.ps1 in a common location for my repo/workspace, so the path to it for the dot-sourcing may change depending on where the current .ps1 file is.

Any native call gets this treatment:

native_call.exe
ThrowOnNativeFailure

Having that file to dot-source has helped me maintain my sanity while writing powershell scripts. :-)

How do a send an HTTPS request through a proxy in Java?

HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.

You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,

http://www.javaworld.com/javaworld/javatips/jw-javatip111.html

EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,

 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
      tunnelHost = proxyhost;
      tunnelPort = Integer.parseInt(proxyport);
      dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
 }

 ...

 connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
 connection.setDefaultHostnameVerifier( new HostnameVerifier()
 {
    public boolean verify( String arg0, SSLSession arg1 )
    {
        return true;
    }
 }  );

EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,

http://bugs.sun.com/view_bug.do?bug_id=6614957

The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,

public class SSLContextTest {

    public static void main(String[] args) {

        System.setProperty("https.proxyHost", "proxy.xxx.com");
        System.setProperty("https.proxyPort", "8888");

        try {

            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkServerTrusted =============");
                }
            } }, new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(
                    sslContext.getSocketFactory());

            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String arg0, SSLSession arg1) {
                            System.out.println("hostnameVerifier =============");
                            return true;
                        }
                    });

            URL url = new URL("https://www.verisign.net");
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

This is what I get when I run the program,

checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......

As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.

Multi-character constant warnings

Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:

int x = *(int*)"abcd";

Or a bit more specific:

int x = *(int32_t*)"abcd";

One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):

int x = ((union {char s[5]; int number;}){"abcd"}).number;

/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");

Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).

Can't use method return value in write context

The alternative way to check if an array is empty could be:

count($array)>0

It works for me without that error

Save Javascript objects in sessionStorage

Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.

I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.

How to watch for form changes in Angular

If you are using FormBuilder, see @dfsq's answer.

If you are not using FormBuilder, there are two ways to be notified of changes.

Method 1

As discussed in the comments on the question, use an event binding on each input element. Add to your template:

<input type="text" class="form-control" required [ngModel]="model.first_name"
         (ngModelChange)="doSomething($event)">

Then in your component:

doSomething(newValue) {
  model.first_name = newValue;
  console.log(newValue)
}

The Forms page has some additional information about ngModel that is relevant here:

The ngModelChange is not an <input> element event. It is actually an event property of the NgModel directive. When Angular sees a binding target in the form [(x)], it expects the x directive to have an x input property and an xChange output property.

The other oddity is the template expression, model.name = $event. We're used to seeing an $event object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an Angular EventEmitter property that returns the input box value when it fires..

We almost always prefer [(ngModel)]. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.

In your case, I suppose you want to do something special.

Method 2

Define a local template variable and set it to ngForm.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
  ....
  <input type="text" ngControl="firstName" class="form-control" 
   required [(ngModel)]="model.first_name">
  ...
  <input type="text" ngControl="lastName" class="form-control" 
   required [(ngModel)]="model.last_name">

class MyForm {
  @ViewChild('myForm') form;
  ...
  ngAfterViewInit() {
    console.log(this.form)
    this.form.control.valueChanges
      .subscribe(values => this.doSomething(values));
  }
  doSomething(values) {
    console.log(values);
  }
}

plunker

For more information on Method 2, see Savkin's video.

See also @Thierry's answer for more information on what you can do with the valueChanges observable (such as debouncing/waiting a bit before processing changes).

How to connect to LocalDB in Visual Studio Server Explorer?

Scenario: Windows 8.1, VS2013 Ultimate, SQL Express Installed and running, SQL Server Browser Disabled. This worked for me:

  1. First I enabled SQL Server Browser under services.
  2. In Visual Studio: Open the Package Manager Console then type: Enable-Migrations; Then Type Enable-Migrations -ContextTypeName YourContextDbName that created the Migrations folder in VS.
  3. Inside the Migrations folder you will find the "Configuration.cs" file, turn on automatic migrations by: AutomaticMigrationsEnabled = true;
  4. Run your application again, the environment creates a DefaultConnection and you will see the new tables from your context. This new connection points to the localdb. The created connection string shows: Data Source=(LocalDb)\v11.0 ... (more parameters and path to the created mdf file)

You can now create a new connection with Server name: (LocalDb)\v11.0 (hit refresh) Connect to a database: Select your new database under the dropdown.

I hope it helps.

Convert Unix timestamp into human readable date using MySQL

Why bother saving the field as readable? Just us AS

SELECT theTimeStamp, FROM_UNIXTIME(theTimeStamp) AS readableDate
               FROM theTable
               WHERE theTable.theField = theValue;

EDIT: Sorry, we store everything in milliseconds not seconds. Fixed it.

How to use <DllImport> in VB.NET?

Imports System.Runtime.InteropServices

Is there a way to detect if an image is blurry?

i implemented it use fft in matlab and check histogram of the fft compute mean and std but also fit function can be done

fa =  abs(fftshift(fft(sharp_img)));
fb = abs(fftshift(fft(blured_img)));

f1=20*log10(0.001+fa);
f2=20*log10(0.001+fb);

figure,imagesc(f1);title('org')
figure,imagesc(f2);title('blur')

figure,hist(f1(:),100);title('org')
figure,hist(f2(:),100);title('blur')

mf1=mean(f1(:));
mf2=mean(f2(:));

mfd1=median(f1(:));
mfd2=median(f2(:));

sf1=std(f1(:));
sf2=std(f2(:));

Retrieve all values from HashMap keys in an ArrayList Java

Java 8 solution for produce string like "key1: value1,key2: value2"

private static String hashMapToString(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.joining(","));

}

and produce a list simple collect as list

private static List<String> hashMapToList(HashMap<String, String> hashMap) {

    return hashMap.keySet().stream()
            .map((key) -> key + ": " + hashMap.get(key))
            .collect(Collectors.toList());

}

How do I remove a specific element from a JSONArray?

We can use iterator to filter out the array entries instead of creating a new  Array. 

'public static void removeNullsFrom(JSONArray array) throws JSONException {
                if (array != null) {
                    Iterator<Object> iterator = array.iterator();
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if (o == null || o == JSONObject.NULL) {
                            iterator.remove();
                        }
                    }
                }
            }'

Ant is using wrong java version

According to the Ant Documentation, set JAVACMD environment variable to complete path to java.exe of the JRE version that you want to run Ant under.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

How to uninstall/upgrade Angular CLI?

Run this command

npm uninstall angular-cli

Event when window.location.href changes

There is a default onhashchange event that you can use.

Documented HERE

And can be used like this:

function locationHashChanged( e ) {
    console.log( location.hash );
    console.log( e.oldURL, e.newURL );
    if ( location.hash === "#pageX" ) {
        pageX();
    }
}

window.onhashchange = locationHashChanged;

If the browser doesn't support oldURL and newURL you can bind it like this:

//let this snippet run before your hashChange event binding code
if( !window.HashChangeEvent )( function() {
    let lastURL = document.URL;
    window.addEventListener( "hashchange", function( event ) {
        Object.defineProperty( event, "oldURL", { enumerable: true, configurable: true, value: lastURL } );
        Object.defineProperty( event, "newURL", { enumerable: true, configurable: true, value: document.URL } );
        lastURL = document.URL;
    } );
} () );

Add vertical whitespace using Twitter Bootstrap?

<form>
 <fieldset class="form-group"><input type="text" class="form-control" placeholder="Input"/></fieldset>
 <fieldset class="form-group"><button class="btn btn-primary"/>Button</fieldset>
</form>

http://v4-alpha.getbootstrap.com/components/forms/#form-controls

Will using 'var' affect performance?

If the compiler can do automatic type inferencing, then there wont be any issue with performance. Both of these will generate same code

var    x = new ClassA();
ClassA x = new ClassA();

however, if you are constructing the type dynamically (LINQ ...) then var is your only question and there is other mechanism to compare to in order to say what is the penalty.

Plugin with id 'com.google.gms.google-services' not found

You can find the correct dependencies here apply changes to app.gradle and project.gradle and tell me about this, greetings!


Your apply plugin: 'com.google.gms.google-services' in app.gradle looks like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"

    defaultConfig {
        applicationId "com.example.personal.numbermania"
        minSdkVersion 10
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"

        multiDexEnabled true
    }

    dexOptions {
        incremental true
        javaMaxHeapSize "4g" //Here stablished how many cores you want to use your android studi 4g = 4 cores
    }

    buildTypes {
        debug
                {
                    debuggable true
                }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:24.2.1'
        compile 'com.android.support:design:24.2.1'
        compile 'com.google.firebase:firebase-ads:9.6.1'
        compile 'com.google.firebase:firebase-core:9.6.1'
        compile 'com.google.android.gms:play-services:9.6.1'
}

apply plugin: 'com.google.gms.google-services'

Add classpath to the project's gradle:

classpath 'com.google.gms:google-services:3.0.0'

Google play services library on SDK Manager:

enter image description here

React-Native: Module AppRegistry is not a registered callable module

restart packager worked for me. just kill react native packager and run it again.

What is the difference between atomic / volatile / synchronized?

I know that two threads can not enter in Synchronize block at the same time

Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.

private Integer i = 0;

synchronized(i) {
   i++;
}

This will not behave as expected as it could be locking on a different object each time.

if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??

yes. It doesn't use locking to achieve thread safety.

If you want to know how they work in more detail, you can read the code for them.

And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??

Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.

i read in some article that thread has local copy of variables what is that ??

I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.

This is only an issue when memory is shared at least one thread updates it.

Casting a variable using a Type variable

Other answers do not mention "dynamic" type. So to add one more answer, you can use "dynamic" type to store your resulting object without having to cast converted object with a static type.

dynamic changedObj = Convert.ChangeType(obj, typeVar);
changedObj.Method();

Keep in mind that with the use of "dynamic" the compiler is bypassing static type checking which could introduce possible runtime errors if you are not careful.

Also, it is assumed that the obj is an instance of Type typeVar or is convertible to that type.

How to make URL/Phone-clickable UILabel?

Swift 4.2, Xcode 9.3 version

class LinkedLabel: UILabel {

    fileprivate let layoutManager = NSLayoutManager()
    fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
    fileprivate var textStorage: NSTextStorage?


    override init(frame aRect:CGRect){
        super.init(frame: aRect)
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.initialize()
    }

    func initialize(){

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTapOnLabel))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)
    }

    override var attributedText: NSAttributedString?{
        didSet{
            if let _attributedText = attributedText{
                self.textStorage = NSTextStorage(attributedString: _attributedText)

                self.layoutManager.addTextContainer(self.textContainer)
                self.textStorage?.addLayoutManager(self.layoutManager)

                self.textContainer.lineFragmentPadding = 0.0;
                self.textContainer.lineBreakMode = self.lineBreakMode;
                self.textContainer.maximumNumberOfLines = self.numberOfLines;
            }

        }
    }

    @objc func handleTapOnLabel(tapGesture:UITapGestureRecognizer){

        let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
        let labelSize = tapGesture.view?.bounds.size
        let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
        let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)


        self.attributedText?.enumerateAttribute(NSAttributedStringKey.link, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
            (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in

            if NSLocationInRange(indexOfCharacter, range){
                if let _attrs = attrs{

                    UIApplication.shared.openURL(URL(string: _attrs as! String)!)
                }
            }
        })

    }}

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

I have faced this type of error. to call a function from the razor.

public ActionResult EditorAjax(int id, int? jobId, string type = ""){}

solved that by changing the line

from

<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" /> 

to

<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />

where my route.config is

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
        );

Remove background drawable programmatically in Android

Best performance on this method :

imageview.setBackgroundResource(R.drawable.location_light_green);

Use this.

Intent.putExtra List

If you use ArrayList instead of list then also your problem wil be solved. In your code only modify List into ArrayList.

private List<Item> data;

How do I create a circle or square with just CSS - with a hollow center?

In case of circle all you need is one div, but in case of hollow square you need to have 2 divs. The divs are having a display of inline-block which you can change accordingly. Live Codepen link: Click Me

In case of circle all you need to change is the border properties and the dimensions(width and height) of circle. If you want to change color just change the border color of hollow-circle.

In case of the square background-color property needs to be changed depending upon the background of page or the element upon which you want to place the hollow-square. Always keep the inner-circle dimension small as compared to the hollow-square. If you want to change color just change the background-color of hollow-square. The inner-circle is centered upon the hollow-square using the position, top, left, transform properties just don't mess with them.

Code is as follows:

_x000D_
_x000D_
/* CSS Code */_x000D_
_x000D_
.hollow-circle {_x000D_
  width: 4rem;_x000D_
  height: 4rem;_x000D_
  background-color: transparent;_x000D_
  border-radius: 50%;_x000D_
  display: inline-block;_x000D_
  _x000D_
  /* Use this */_x000D_
  border-color: black;_x000D_
  border-width: 5px;_x000D_
  border-style: solid;_x000D_
  /* or */_x000D_
  /* Shorthand Property */_x000D_
  /* border: 5px solid #000; */_x000D_
}_x000D_
_x000D_
.hollow-square {_x000D_
  position: relative;_x000D_
  width: 4rem;_x000D_
  height: 4rem;_x000D_
  display: inline-block;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner-circle {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  width: 3rem;_x000D_
  height: 3rem;_x000D_
  border-radius: 50%;_x000D_
  background-color: white;_x000D_
}
_x000D_
<!-- HTML Code -->_x000D_
_x000D_
<div class="hollow-circle">_x000D_
</div>_x000D_
_x000D_
<br/><br/><br/>_x000D_
_x000D_
<div class="hollow-square">_x000D_
  <div class="inner-circle"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Image is not showing in browser?

I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg

Try this instead:

<img  src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />

UPDATE:

I don't know what your $PROJECTHOME is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.

Then in your HTML you can simply reference the image within the images folder relative to the site, like so:

<img  src="images/66.jpg" width="400" height="400" />

Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):

<img  src="/images/66.jpg" width="400" height="400" />

Split pandas dataframe in two if it has more than 10 rows

Below is a simple function implementation which splits a DataFrame to chunks and a few code examples:

import pandas as pd

def split_dataframe_to_chunks(df, n):
    df_len = len(df)
    count = 0
    dfs = []

    while True:
        if count > df_len-1:
            break

        start = count
        count += n
        #print("%s : %s" % (start, count))
        dfs.append(df.iloc[start : count])
    return dfs


# Create a DataFrame with 10 rows
df = pd.DataFrame([i for i in range(10)])

# Split the DataFrame to chunks of maximum size 2
split_df_to_chunks_of_2 = split_dataframe_to_chunks(df, 2)
print([len(i) for i in split_df_to_chunks_of_2])
# prints: [2, 2, 2, 2, 2]

# Split the DataFrame to chunks of maximum size 3
split_df_to_chunks_of_3 = split_dataframe_to_chunks(df, 3)
print([len(i) for i in split_df_to_chunks_of_3])
# prints [3, 3, 3, 1]

Arrays in unix shell?

You can try of the following type :

#!/bin/bash
 declare -a arr

 i=0
 j=0

  for dir in $(find /home/rmajeti/programs -type d)
   do
        arr[i]=$dir
        i=$((i+1))
   done


  while [ $j -lt $i ]
  do
        echo ${arr[$j]}
        j=$((j+1))
  done

Java: How to Indent XML Generated by Transformer

import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory

transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

How do I accomplish an if/else in mustache.js?

Your else statement should look like this (note the ^):

{{^avatar}}
 ...
{{/avatar}}

In mustache this is called 'Inverted sections'.

Any way to make plot points in scatterplot more transparent in R?

Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?

addTrans <- function(color,trans)
{
  # This function adds transparancy to a color.
  # Define transparancy with an integer between 0 and 255
  # 0 being fully transparant and 255 being fully visable
  # Works with either color and trans a vector of equal length,
  # or one of the two of length 1.

  if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
  if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
  if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))

  num2hex <- function(x)
  {
    hex <- unlist(strsplit("0123456789ABCDEF",split=""))
    return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
  }
  rgb <- rbind(col2rgb(color),trans)
  res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
  return(res)
}

Some examples:

cols <- sample(c("red","green","pink"),100,TRUE)

# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)

# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)

# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

Virtualenv Command Not Found

On ubuntu 18.4 on AWS installation with pip don't work correctly. Using apt-get install the problem was solved for me.

sudo apt-get install python-virtualenv

and to check

virtualenv --version

How to test for $null array in PowerShell

If your solution requires returning 0 instead of true/false, I've found this to be useful:

PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0

This operation is different from the count property of the array, because Measure-Object is counting objects. Since there are none, it will return 0.

How to wait for a process to terminate to execute another process in batch file

This is my adaptation johnrefling's. This work also in WindowsXP; in my case i start the same application at the end, because i want reopen it with different parametrs. My application is a WindowForm .NET

@echo off
taskkill -im:MyApp.exe
:loop1
tasklist | find /i "MyApp.exe" >nul 2>&1
if errorlevel 1 goto cont1
echo "Waiting termination of process..."
:: timeout /t 1 /nobreak >nul 2>&1      ::this don't work in windows XP
:: from: https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd/33286113#33286113
typeperf "\System\Processor Queue Length" -si 1 -sc 1 >nul s
goto loop1
:cont1
echo "Process terminated, start new application"
START "<SYMBOLIC-TEXT-NAME>" "<full-path-of-MyApp2.exe>" "MyApp2-param1" "MyApp2-param2"
pause

How do you get the current text contents of a QComboBox?

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

How to set text size in a button in html

Try this

<input type="submit" 
       value="HOME" 
       onclick="goHome()" 
       style="font-size : 20px; width: 100%; height: 100px;" /> 

How do I make the return type of a method generic?

 private static T[] prepareArray<T>(T[] arrayToCopy, T value)
    {
        Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
        arrayToCopy[arrayToCopy.Length - 1] = value;
        return (T[])arrayToCopy;
    }

I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.

IntelliJ and Tomcat.. Howto..?

NOTE: Community Edition doesn't support JEE.

First, you will need to install a local Tomcat server. It sounds like you may have already done this.

Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.

From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.

Javascript Date: next month

If you use moment.js, they have an add function. Here's the link - https://momentjs.com/docs/#/manipulating/add/

moment().add(7, 'months');

I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.

function addMonths(after = 1, now = new Date()) {
        var current;
        if (now.getMonth() == 11) {
            current = new Date(now.getFullYear() + 1, 0, 1);
        } else {
            current = new Date(now.getFullYear(), now.getMonth() + 1, 1);            
        }
        return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
    }

Example

console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))

Output -

Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)

How to get row number from selected rows in Oracle

you can just do

select rownum, l.* from student  l where name like %ram%

this assigns the row number as the rows are fetched (so no guaranteed ordering of course).

if you wanted to order first do:

select rownum, l.*
  from (select * from student l where name like %ram% order by...) l;

Calling virtual functions inside constructors

Other answers have already explained why virtual function calls don't work as expected when called from a constructor. I'd like to instead propose another possible work around for getting polymorphic-like behavior from a base type's constructor.

By adding a template constructor to the base type such that the template argument is always deduced to be the derived type it's possible to be aware of the derived type's concrete type. From there, you can call static member functions for that derived type.

This solution does not allow non-static member functions to be called. While execution is in the base type's constructor, the derived type's constructor hasn't even had time to go through it's member initialization list. The derived type portion of the instance being created hasn't begun being initialized it. And since non-static member functions almost certainly interact with data members it would be unusual to want to call the derived type's non-static member functions from the base type's constructor.

Here is a sample implementation :

#include <iostream>
#include <string>

struct Base {
protected:
    template<class T>
    explicit Base(const T*) : class_name(T::Name())
    {
        std::cout << class_name << " created\n";
    }

public:
    Base() : class_name(Name())
    {
        std::cout << class_name << " created\n";
    }


    virtual ~Base() {
        std::cout << class_name << " destroyed\n";
    }

    static std::string Name() {
        return "Base";
    }

private:
    std::string class_name;
};


struct Derived : public Base
{   
    Derived() : Base(this) {} // `this` is used to allow Base::Base<T> to deduce T

    static std::string Name() {
        return "Derived";
    }
};

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

    Derived{};  // Create and destroy a Derived
    Base{};     // Create and destroy a Base

    return 0;
}

This example should print

Derived created
Derived destroyed
Base created
Base destroyed

When a Derived is constructed, the Base constructor's behavior depends on the actual dynamic type of the object being constructed.

Exception from HRESULT: 0x800A03EC Error

I was getting the same error but it's sorted now. In my case, I had columns with the heading "Key1", "Key2", and "Key3". I have changed the column names to something else and it's sorted.

It seems that these are reserved keywords.

Regards, Mahesh

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

Regular Expression to get a string between parentheses in Javascript

Simple: (?<value>(?<=\().*(?=\)))

I hope I've helped.

Apply style to only first level of td tags

I guess you could try

table tr td { color: red; }
table tr td table tr td { color: black; }

Or

body table tr td { color: red; }

where 'body' is a selector for your table's parent

But classes are most likely the right way to go here.

How can I see CakePHP's SQL dump in the controller?

for cakephp 2.0 Write this function in AppModel.php

function getLastQuery()
{
    $dbo = $this->getDatasource();
    $logs = $dbo->getLog();
    $lastLog = end($logs['log']);
    return $lastLog['query'];
}

To use this in Controller Write : echo $this->YourModelName->getLastQuery();

working with negative numbers in python

The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb is negative.

So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.

#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0

#output the total
for count in range(abs(numb)):
    total += numa

if numb < 0:
    total = -total

print total

Initializing a dictionary in python with a key value and no corresponding values

you could use a defaultdict. It will let you set dictionary values without worrying if the key already exists. If you access a key that has not been initialized yet it will return a value you specify (in the below example it will return None)

from collections import defaultdict
your_dict = defaultdict(lambda : None)

time data does not match format

To compare date time, you can try this. Datetime format can be changed

from datetime import datetime

>>> a = datetime.strptime("10/12/2013", "%m/%d/%Y")
>>> b = datetime.strptime("10/15/2013", "%m/%d/%Y")
>>> a>b
False

Getting Class type from String

You can use the forName method of Class:

Class cls = Class.forName(clsName);
Object obj = cls.newInstance();

Boolean checking in the 'if' condition

Former, of course. Latter is redundant, and only goes to show that you haven't understood the concept of booleans very well.

One more suggestion: Choose a different name for your boolean variable. As per this Java style guide:

is prefix should be used for boolean variables and methods.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages.

Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

AngularJS - Multiple ng-view in single template

I believe you can accomplish it by just having single ng-view. In the main template you can have ng-include sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include sections. This is same as having multiple ng-view

You can check the example given in ng-include documentation

in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.

Check if a class `active` exist on element with jquery

I think you want to use hasClass()

$('li.menu').hasClass('active');

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

I suggest that newbies connect a PL2303 to Ubuntu, chmod 777 /dev/ttyUSB0 (file-permissions) and connect to a CuteCom serial terminal. The CuteCom UI is simple \ intuitive. If the PL2303 is continuously broadcasting data, then Cutecom will display data in hex format

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

Font Awesome 5 font-family issue

I found a solution.

  • Integrate fontawesome-all.css
  • At the end of file Search the second @font-face and replace

    font-family: 'Font Awesome 5 Free';

With

font-family: 'Font Awesome 5 FreeR';

And replace:

.far {
  font-family: 'Font Awesome 5 Free';
  font-weight: 400; }

With

.far {
  font-family: 'Font Awesome 5 FreeR';
  font-weight: 400; }

Fully backup a git repo?

You can backup the git repo with git-copy at minimum storage size.

git copy /path/to/project /backup/project.repo.backup

Then you can restore your project with git clone

git clone /backup/project.repo.backup project

Twitter Bootstrap Multilevel Dropdown Menu

I just added class="span2" to the <li> for the dropdown items and that worked.

Bootstrap 3 offset on right not left

Since Google seems to like this answer...

If you're looking to match Bootstrap 4's naming convention, i.e. offset-*-#, here's that modification:

.offset-right-12 {
  margin-right: 100%;
}
.offset-right-11 {
  margin-right: 91.66666667%;
}
.offset-right-10 {
  margin-right: 83.33333333%;
}
.offset-right-9 {
  margin-right: 75%;
}
.offset-right-8 {
  margin-right: 66.66666667%;
}
.offset-right-7 {
  margin-right: 58.33333333%;
}
.offset-right-6 {
  margin-right: 50%;
}
.offset-right-5 {
  margin-right: 41.66666667%;
}
.offset-right-4 {
  margin-right: 33.33333333%;
}
.offset-right-3 {
  margin-right: 25%;
}
.offset-right-2 {
  margin-right: 16.66666667%;
}
.offset-right-1 {
  margin-right: 8.33333333%;
}
.offset-right-0 {
  margin-right: 0;
}
@media (min-width: 576px) {
  .offset-sm-right-12 {
    margin-right: 100%;
  }
  .offset-sm-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-sm-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-sm-right-9 {
    margin-right: 75%;
  }
  .offset-sm-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-sm-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-sm-right-6 {
    margin-right: 50%;
  }
  .offset-sm-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-sm-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-sm-right-3 {
    margin-right: 25%;
  }
  .offset-sm-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-sm-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-sm-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 768px) {
  .offset-md-right-12 {
    margin-right: 100%;
  }
  .offset-md-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-md-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-md-right-9 {
    margin-right: 75%;
  }
  .offset-md-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-md-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-md-right-6 {
    margin-right: 50%;
  }
  .offset-md-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-md-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-md-right-3 {
    margin-right: 25%;
  }
  .offset-md-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-md-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-md-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .offset-lg-right-12 {
    margin-right: 100%;
  }
  .offset-lg-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-lg-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-lg-right-9 {
    margin-right: 75%;
  }
  .offset-lg-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-lg-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-lg-right-6 {
    margin-right: 50%;
  }
  .offset-lg-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-lg-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-lg-right-3 {
    margin-right: 25%;
  }
  .offset-lg-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-lg-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-lg-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .offset-xl-right-12 {
    margin-right: 100%;
  }
  .offset-xl-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-xl-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-xl-right-9 {
    margin-right: 75%;
  }
  .offset-xl-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-xl-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-xl-right-6 {
    margin-right: 50%;
  }
  .offset-xl-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-xl-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-xl-right-3 {
    margin-right: 25%;
  }
  .offset-xl-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-xl-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-xl-right-0 {
    margin-right: 0;
  }
}

How to change the color of an svg element?

Target the path within the svg:

<svg>
   <path>....
</svg>

You can do inline, like:

<path fill="#ccc">

Or

svg{
   path{
        fill: #ccc

How to add hamburger menu in bootstrap

All you have to do is read the code on getbootstrap.com:

Codepen

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
  <div class="container">_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
      <ul class="nav navbar-nav">_x000D_
        <li><a href="index.php">Home</a></li>_x000D_
        <li><a href="about.php">About</a></li>_x000D_
        <li><a href="#portfolio">Portfolio</a></li>_x000D_
        <li><a href="#">Blog</a></li>_x000D_
        <li><a href="contact.php">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

Prevent jQuery UI dialog from setting focus to first textbox

In my opinion this solution is very nice:

$("#dialog").dialog({
    open: function(event, ui) {
        $("input").blur();
    }
});

Found here: unable-to-remove-autofocus-in-ui-dialog

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Have you tried?

var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;

// "2013-10-10T22:10:00"
 dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); 

// "2013-10-10 22:10:00Z"    
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)

Also try using parameters when you store the c# datetime value in the mySql database, this might help.

How do I display local image in markdown?

I suspect the path is not correct. As mentioned by user7412219 ubuntu and windows deal with path differently. Try to put the image in the same folder as your Notebook and use:

![alt text](Isolated.png "Title")

On windows the desktop should be at: C:\Users\jzhang\Desktop

What is the best way to get all the divisors of a number?

Although there are already many solutions to this, I really have to post this :)

This one is:

  • readable
  • short
  • self contained, copy & paste ready
  • quick (in cases with a lot of prime factors and divisors, > 10 times faster than the accepted solution)
  • python3, python2 and pypy compliant

Code:

def divisors(n):
    # get factors and their counts
    factors = {}
    nn = n
    i = 2
    while i*i <= nn:
        while nn % i == 0:
            factors[i] = factors.get(i, 0) + 1
            nn //= i
        i += 1
    if nn > 1:
        factors[nn] = factors.get(nn, 0) + 1

    primes = list(factors.keys())

    # generates factors from primes[k:] subset
    def generate(k):
        if k == len(primes):
            yield 1
        else:
            rest = generate(k+1)
            prime = primes[k]
            for factor in rest:
                prime_to_i = 1
                # prime_to_i iterates prime**i values, i being all possible exponents
                for _ in range(factors[prime] + 1):
                    yield factor * prime_to_i
                    prime_to_i *= prime

    # in python3, `yield from generate(0)` would also work
    for factor in generate(0):
        yield factor

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I ran into a similar problem with the same error message using following code:

@Html.DisplayFor(model => model.EndDate.Value.ToShortDateString())

I found a good answer here

Turns out you can decorate the property in your model with a displayformat then apply a dataformatstring.

Be sure to import the following lib into your model:

using System.ComponentModel.DataAnnotations;

In C can a long printf statement be broken up into multiple lines?

If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:

printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n", 
sp->name, 
sp->args, 
sp->value, 
sp->arraysize);

Eclipse - Failed to create the java virtual machine

You can also try closing other programs. :)

It's pretty simple, but worked for me. In my case the VM just don't had enough memory to run, and i got the same message. So i had to clean up the ram, by closing unnecessary programs.

Setting a property with an EventTrigger

As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.

Laravel - Return json along with http status code

return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity

Hope my answer was helpful.

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

How to kill a child process after a given timeout in Bash?

#Kill command after 10 seconds
timeout 10 command

#If you don't have timeout installed, this is almost the same:
sh -c '(sleep 10; kill "$$") & command'

#The same as above, with muted duplicate messages:
sh -c '(sleep 10; kill "$$" 2>/dev/null) & command'

How do I change Bootstrap 3 column order on mobile layout?

In Bootstrap 4, if you want to do something like this:

    Mobile  |   Desktop
-----------------------------
    A       |       A
    C       |   B       C
    B       |       D
    D       |

You need to reverse the order of B then C then apply order-{breakpoint}-first to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:

  • Smaller screens: 12 cols to B and 12 cols to C

  • Larger screens: 12 cols between the sum of them (B + C = 12)

Like this

<div class='row no-gutters'>
    <div class='col-12'>
        A
    </div>
    <div class='col-12'>
        <div class='row no-gutters'>
            <div class='col-12 col-md-6'>
                C
            </div>
            <div class='col-12 col-md-6 order-md-first'>
                B
            </div>
        </div>
    </div>
    <div class='col-12'>
        D
    </div>
</div>

Demo: https://codepen.io/anon/pen/wXLGKa

SQL Server tables: what is the difference between @, # and ##?

#table refers to a local (visible to only the user who created it) temporary table.

##table refers to a global (visible to all users) temporary table.

@variableName refers to a variable which can hold values depending on its type.

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Regex to get NUMBER only from String

The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:

string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342

How to select the first, second, or third element with a given class name?

Perhaps using the "~" selector of CSS?

.myclass {
    background: red;
}

.myclass~.myclass {
    background: yellow;
}

.myclass~.myclass~.myclass {
    background: green;
}

See my example on jsfiddle

Which exception should I raise on bad/illegal argument combinations in Python?

It depends on what the problem with the arguments is.

If the argument has the wrong type, raise a TypeError. For example, when you get a string instead of one of those Booleans.

if not isinstance(save, bool):
    raise TypeError(f"Argument save must be of type bool, not {type(save)}")

Note, however, that in Python we rarely make any checks like this. If the argument really is invalid, some deeper function will probably do the complaining for us. And if we only check the boolean value, perhaps some code user will later just feed it a string knowing that non-empty strings are always True. It might save him a cast.

If the arguments have invalid values, raise ValueError. This seems more appropriate in your case:

if recurse and not save:
    raise ValueError("If recurse is True, save should be True too")

Or in this specific case, have a True value of recurse imply a True value of save. Since I would consider this a recovery from an error, you might also want to complain in the log.

if recurse and not save:
    logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
    save = True

Including an anchor tag in an ASP.NET MVC Html.ActionLink

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

Using sed, how do you print the first 'N' characters of a line?

To print the N first characters you can remove the N+1 characters up to the end of line:

$ sed 's/.//5g' <<< "defn-test"
defn

Insert current date into a date column using T-SQL?

If you're looking to store the information in a table, you need to use an INSERT or an UPDATE statement. It sounds like you need an UPDATE statement:

UPDATE  SomeTable
SET     SomeDateField = GETDATE()
WHERE   SomeID = @SomeID

What is the shortcut in IntelliJ IDEA to find method / functions?

If I need navigate to method in currently opened class, I use this combination: ALT+7 (CMD+7 on Mac) to open structure view, and press two times (first time open, second time focus on view), type name of methods, select on of needed.

Select Pandas rows based on list index

you can also use iloc:

df.iloc[[1,3],:]

This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:

df.index.isin([1,3])

... as suggested in other responses.

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I had the same problem for Winforms.

The solution for me is:

Install-Package Microsoft.ReportViewer.Runtime.Winforms

Converting integer to binary in python

Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.

could be useful when you apply binary to power sets

import numpy as np
np.binary_repr(6, width=8)

Default password of mysql in ubuntu server 16.04

If you install your mysql with apt install mysql.
you can just login to your mysql with sudo mysql.

How to import other Python files?

If the function defined is in a file x.py:

def greet():
    print('Hello! How are you?')

In the file where you are importing the function, write this:

from x import greet

This is useful if you do not wish to import all the functions in a file.

ImportError: No module named site on Windows

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same "No module named site" error. I've set PYTHONHOME to c:\Python27 and it's working. But the mystery remains why this is now needed when it wasn't with previous releases. And, if it is needed, why doesn't the installer set this var?

Iterating over each line of ls -l output

As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:

for x in * ; do echo `ls -ld $x` ; done

Setting focus to a textbox control

I think what you're looking for is:

textBox1.Select();

in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)

From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :

Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

Android Studio - Device is connected but 'offline'

Besides the solution mentioned above, try to download Samsung's Android USB Driver for your platform. Here is a link to the Windows one:

https://developer.samsung.com/galaxy/others/android-usb-driver-for-windows

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

Does Hive have a String split function?

Just a clarification on the answer given by Bkkbrad.

I tried this suggestion and it did not work for me.

For example,

split('aa|bb','\\|')

produced:

["","a","a","|","b","b",""]

But,

split('aa|bb','[|]')

produced the desired result:

["aa","bb"]

Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.

For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

XAMPP: Couldn't start Apache (Windows 10)

After playing around, really all you have to do is change two lines in the httpd.conf file:

Change "Listen 80" to "Listen 122" (or anything else you want)

and

"ServerName Localhost:80" to "Localhost:122" (or the port you changed above)

Then it all should fire right up :P

How to access private data members outside the class without making "friend"s?

Start making friends of class A. e.g.

void foo ();

class A{
  int iData;
  friend void foo ();
};

Edit:

If you can't change class A body then A::iData is not accessible with the given conditions in your question.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

In my apache error log, I saw:

[Tue Feb 16 14:55:02 2010] [notice] child pid 9985 exit signal File size limit exceeded (25)

So I, removed all the contents of my largest log file 2.1GB /var/log/system.log. Now everything works.

How to get terminal's Character Encoding

locale command with no arguments will print the values of all of the relevant environment variables except for LANGUAGE.

For current encoding:

locale charmap

For available locales:

locale -a

For available encodings:

locale -m