Programs & Examples On #Object lifetime

The object lifetime (or life cycle) of an object in object-oriented programming is the time between an object is created (also known as instantiation or construction) till the object is no longer used and then destructed or freed.

How to pass macro definition from "make" command line arguments (-D) to C source code?

Just use a specific variable for that.

$ cat Makefile 
all:
    echo foo | gcc $(USER_DEFINES) -E -xc - 

$ make USER_DEFINES="-Dfoo=one"
echo foo | gcc -Dfoo=one -E -xc - 
...
one

$ make USER_DEFINES="-Dfoo=bar"
echo foo | gcc -Dfoo=bar -E -xc - 
...
bar

$ make 
echo foo | gcc  -E -xc - 
...
foo

How to convert an entire MySQL database characterset and collation to UTF-8?

To change the character set encoding to UTF-8 follow simple steps in PHPMyAdmin

  1. Select your Database SS

  2. Go To Operations SS

  3. In operations tab, on the bottom collation drop down menu, select you desire encoding i.e(utf8_general_ci), and also check the checkbox (1)change all table collations, (2) Change all tables columns collations. and hit Go.

SS

Iterating through all the cells in Excel VBA or VSTO 2005

You can use a For Each to iterate through all the cells in a defined range.

Public Sub IterateThroughRange()

Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range

Set wb = Application.Workbooks(1)
Set ws = wb.Sheets(1)
Set rng = ws.Range("A1", "C3")

For Each cell In rng.Cells
    cell.Value = cell.Address
Next cell

End Sub

How to use this boolean in an if statement?

= is for assignment

write

if(stop){
   //your code
}

or

if(stop == true){
   //your code
}

PHP: HTTP or HTTPS?

This can get more complicated depending on where PHP sits in your environment, since your question is quite broad. This may depend on whether there's a load-balancer and how it's configured. Here are are a few related questions:

Array initializing in Scala

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

"Eliminate render-blocking CSS in above-the-fold content"

I too have struggled with this new pagespeed metric.

Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.

Combining all css into one file helped a lot. All my sites are back up to %95 - %98.

The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

What is the difference between i++ & ++i in a for loop?

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4

Scraping html tables into R data frames using the XML package

library(RCurl)
library(XML)

# Download page using RCurl
# You may need to set proxy details, etc.,  in the call to getURL
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
# Process escape characters
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

# Parse the html tree, ignoring errors on the page
pagetree <- htmlTreeParse(webpage, error=function(...){})

# Navigate your way through the tree. It may be possible to do this more efficiently using getNodeSet
body <- pagetree$children$html$children$body 
divbodyContent <- body$children$div$children[[1]]$children$div$children[[4]]
tables <- divbodyContent$children[names(divbodyContent)=="table"]

#In this case, the required table is the only one with class "wikitable sortable"  
tableclasses <- sapply(tables, function(x) x$attributes["class"])
thetable  <- tables[which(tableclasses=="wikitable sortable")]$table

#Get columns headers
headers <- thetable$children[[1]]$children
columnnames <- unname(sapply(headers, function(x) x$children$text$value))

# Get rows from table
content <- c()
for(i in 2:length(thetable$children))
{
   tablerow <- thetable$children[[i]]$children
   opponent <- tablerow[[1]]$children[[2]]$children$text$value
   others <- unname(sapply(tablerow[-1], function(x) x$children$text$value)) 
   content <- rbind(content, c(opponent, others))
}

# Convert to data frame
colnames(content) <- columnnames
as.data.frame(content)

Edited to add:

Sample output

                     Opponent Played Won Drawn Lost Goals for Goals against  % Won
    1               Argentina     94  36    24   34       148           150  38.3%
    2                Paraguay     72  44    17   11       160            61  61.1%
    3                 Uruguay     72  33    19   20       127            93  45.8%
    ...

In AVD emulator how to see sdcard folder? and Install apk to AVD?

DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

Best Way to View Generated Source of Webpage?

alert(document.documentElement.outerHTML);

If WorkSheet("wsName") Exists

Another version of the function without error handling. This time it is not case sensitive and a little bit more efficient.

Function WorksheetExists(wsName As String) As Boolean
    Dim ws As Worksheet
    Dim ret As Boolean        
    wsName = UCase(wsName)
    For Each ws In ThisWorkbook.Sheets
        If UCase(ws.Name) = wsName Then
            ret = True
            Exit For
        End If
    Next
    WorksheetExists = ret
End Function

C++ performance vs. Java/C#

On top of what some others have said, from my understanding .NET and Java are better at memory allocation. E.g. they can compact memory as it gets fragmented while C++ cannot (natively, but it can if you're using a clever garbage collector).

How to find the serial port number on Mac OS X?

mac os x don't use com numbers. you have to use something like 'ser:devicename' , 9600

How can I convert tabs to spaces in every file of a directory?

I used astyle to re-indent all my C/C++ code after finding mixed tabs and spaces. It also has options to force a particular brace style if you'd like.

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

How do I find which rpm package supplies a file I'm looking for?

To know the package owning (or providing) an already installed file:

rpm -qf myfilename

How can I mimic the bottom sheet from the Maps app?

I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.

See below link for more details.

https://github.com/OfTheWolf/UBottomSheet

ubottom sheet

Is there a way to crack the password on an Excel VBA Project?

With my turn, this is built upon kaybee99's excellent answer which is built upon Ð?c Thanh Nguy?n's fantastic answer to allow this method to work with both x86 and amd64 versions of Office.

An overview of what is changed, we avoid push/ret which is limited to 32bit addresses and replace it with mov/jmp reg.

Tested and works on

Word/Excel 2016 - 32 bit version.
Word/Excel 2016 - 64 bit version.

how it works

  1. Open the file(s) that contain your locked VBA Projects.
  2. Create a new file with the same type as the above and store this code in Module1

    Option Explicit
    
    Private Const PAGE_EXECUTE_READWRITE = &H40
    
    Private Declare PtrSafe Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" _
    (Destination As LongPtr, Source As LongPtr, ByVal Length As LongPtr)
    
    Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As LongPtr, _
    ByVal dwSize As LongPtr, ByVal flNewProtect As LongPtr, lpflOldProtect As LongPtr) As LongPtr
    
    Private Declare PtrSafe Function GetModuleHandleA Lib "kernel32" (ByVal lpModuleName As String) As LongPtr
    
    Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, _
    ByVal lpProcName As String) As LongPtr
    
    Private Declare PtrSafe Function DialogBoxParam Lib "user32" Alias "DialogBoxParamA" (ByVal hInstance As LongPtr, _
    ByVal pTemplateName As LongPtr, ByVal hWndParent As LongPtr, _
    ByVal lpDialogFunc As LongPtr, ByVal dwInitParam As LongPtr) As Integer
    
    Dim HookBytes(0 To 11) As Byte
    Dim OriginBytes(0 To 11) As Byte
    Dim pFunc As LongPtr
    Dim Flag As Boolean
    
    Private Function GetPtr(ByVal Value As LongPtr) As LongPtr
        GetPtr = Value
    End Function
    
    Public Sub RecoverBytes()
        If Flag Then MoveMemory ByVal pFunc, ByVal VarPtr(OriginBytes(0)), 12
    End Sub
    
    Public Function Hook() As Boolean
        Dim TmpBytes(0 To 11) As Byte
        Dim p As LongPtr, osi As Byte
        Dim OriginProtect As LongPtr
    
        Hook = False
    
        #If Win64 Then
            osi = 1
        #Else
            osi = 0
        #End If
    
        pFunc = GetProcAddress(GetModuleHandleA("user32.dll"), "DialogBoxParamA")
    
        If VirtualProtect(ByVal pFunc, 12, PAGE_EXECUTE_READWRITE, OriginProtect) <> 0 Then
    
            MoveMemory ByVal VarPtr(TmpBytes(0)), ByVal pFunc, osi+1
            If TmpBytes(osi) <> &HB8 Then
    
                MoveMemory ByVal VarPtr(OriginBytes(0)), ByVal pFunc, 12
    
                p = GetPtr(AddressOf MyDialogBoxParam)
    
                If osi Then HookBytes(0) = &H48
                HookBytes(osi) = &HB8
                osi = osi + 1
                MoveMemory ByVal VarPtr(HookBytes(osi)), ByVal VarPtr(p), 4 * osi
                HookBytes(osi + 4 * osi) = &HFF
                HookBytes(osi + 4 * osi + 1) = &HE0
    
                MoveMemory ByVal pFunc, ByVal VarPtr(HookBytes(0)), 12
                Flag = True
                Hook = True
            End If
        End If
    End Function
    
    Private Function MyDialogBoxParam(ByVal hInstance As LongPtr, _
    ByVal pTemplateName As LongPtr, ByVal hWndParent As LongPtr, _
    ByVal lpDialogFunc As LongPtr, ByVal dwInitParam As LongPtr) As Integer
    
        If pTemplateName = 4070 Then
            MyDialogBoxParam = 1
        Else
            RecoverBytes
            MyDialogBoxParam = DialogBoxParam(hInstance, pTemplateName, _
                       hWndParent, lpDialogFunc, dwInitParam)
            Hook
        End If
    End Function
    
  3. Paste this code in Module2 and run it

    Sub unprotected()
        If Hook Then
            MsgBox "VBA Project is unprotected!", vbInformation, "*****"
        End If
    End Sub
    

How do you change the colour of each category within a highcharts column chart?

just put chart

$('#container').highcharts({
colors: ['#31BFA2'], // change color here
chart: {
        type: 'column'
}, .... Continue chart

Passing arguments to an interactive program non-interactively

Just want to add one more way. Found it elsewhere, and is quite simple. Say I want to pass yes for all the prompts at command line for a command "execute_command", Then I would simply pipe yes to it.

yes | execute_command

This will use yes as the answer to all yes/no prompts.

How does Java import work?

In dynamic languages, when the interpreter imports, it simply reads a file and evaluates it.

In C, external libraries are located by the linker at compile time to build the final object if the library is statically compiled, while for dynamic libraries a smaller version of the linker is called at runtime which remaps addresses and so makes code in the library available to the executable.

In Java, import is simply used by the compiler to let you name your classes by their unqualified name, let's say String instead of java.lang.String. You don't really need to import java.lang.* because the compiler does it by default. However this mechanism is just to save you some typing. Types in Java are fully qualified class names, so a String is really a java.lang.String object when the code is run. Packages are intended to prevent name clashes and allow two classes to have the same simple name, instead of relying on the old C convention of prefixing types like this. java_lang_String. This is called namespacing.

BTW, in Java there's the static import construct, which allows to further save typing if you use lots of constants from a certain class. In a compilation unit (a .java file) which declares

import static java.lang.Math.*;

you can use the constant PI in your code, instead of referencing it through Math.PI, and the method cos() instead of Math.cos(). So for example you can write

double r = cos(PI * theta);

Once you understand that classes are always referenced by their fully qualified name in the final bytecode, you must understand how the class code is actually loaded. This happens the first time an object of that class is created, or the first time a static member of the class is accessed. At this time, the ClassLoader tries to locate the class and instantiate it. If it can't find the class a NoClassDefFoundError is thrown (or a a ClassNotFoundException if the class is searched programmatically). To locate the class, the ClassLoader usually checks the paths listed in the $CLASSPATH environment variable.

To solve your problem, it seems you need an applet element like this

<applet
  codebase = "http://san.redenetimoveis.com"
  archive="test.jar, core.jar"
  code="com.colorfulwolf.webcamapplet.WebcamApplet"      
  width="550" height="550" >

BTW, you don't need to import the archives in the standard JRE.

RegEx to extract all matches from string using RegExp.exec

If you're able to use matchAll here's a trick:

Array.From has a 'selector' parameter so instead of ending up with an array of awkward 'match' results you can project it to what you really need:

Array.from(str.matchAll(regexp), m => m[0]);

If you have named groups eg. (/(?<firstname>[a-z][A-Z]+)/g) you could do this:

Array.from(str.matchAll(regexp), m => m.groups.firstName);

How to consume REST in Java

Apache Http Client APIs are very commonly used for calling HTTP Rest services.

Here is one of example of consuming HTTP GET call.

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;

public class CallHTTPGetService {

public static void main(String[] args) throws ClientProtocolException, IOException {


    HttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest httpUriRequest = new HttpGet("URL");

    HttpResponse response = client.execute(httpUriRequest);
    System.out.println(response);

}
}

Use following maven dependency if using Maven project.

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.1</version>
    </dependency>

ASP.NET MVC Conditional validation

Thanks Merritt :)

I've just updated this to MVC 3 in case anyone finds it useful: Conditional Validation in ASP.NET MVC 3.

How to validate IP address in Python?

Consider IPv4 address as "ip".

if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip):  
    print "Valid IP"  
else:
    print "Invalid IP"

SQL alias for SELECT statement

You could store this into a temporary table.

So instead of doing the CTE/sub query you would use a temp table.

Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/

Error using eclipse for Android - No resource found that matches the given name

One general solution to such tiny errors is that you close eclipse and start is again.. 3 irritating problems were solved.. its the problem with eclipse.. some times it didn resolve "R.id", the it didn find @string/somebutton, and then again some random thing... if nothing logical comes in your mind, try this, n conjure d result.. :)

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

PHP date() with timezone?

You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.

javac : command not found

Install same version javac as your JRE

yum install java-devel

Comparing user-inputted characters in C

For a start, your answer variable should be of type char, not char*.

As for the if statement:

if (answer == ('Y' || 'y'))

This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

You could use the more correct:

if ((answer == 'Y') || (answer == 'y'))

but you really should be using:

if (toupper(answer) == 'Y')

since that's the more portable way to achieve the same end.


*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

<code> vs <pre> vs <samp> for inline and block code snippets

Something I completely missed: the non-wrapping behaviour of <pre> can be controlled with CSS. So this gives the exact result I was looking for:

_x000D_
_x000D_
code { _x000D_
    background: hsl(220, 80%, 90%); _x000D_
}_x000D_
_x000D_
pre {_x000D_
    white-space: pre-wrap;_x000D_
    background: hsl(30,80%,90%);_x000D_
}
_x000D_
Here's an example demonstrating the <code>&lt;code&gt;</code> tag._x000D_
_x000D_
<pre>_x000D_
Here's a very long pre-formatted formatted using the &lt;pre&gt; tag. Notice how it wraps?  It goes on and on and on and on and on and on and on and on and on and on..._x000D_
</pre>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/9mCN7/

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.

If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.

How to add image in a TextView text?

fun TextView.addImage(atText: String, @DrawableRes imgSrc: Int, imgWidth: Int, imgHeight: Int) {
    val ssb = SpannableStringBuilder(this.text)

    val drawable = ContextCompat.getDrawable(this.context, imgSrc) ?: return
    drawable.mutate()
    drawable.setBounds(0, 0,
            imgWidth,
            imgHeight)
    val start = text.indexOf(atText)
    ssb.setSpan(VerticalImageSpan(drawable), start, start + atText.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
    this.setText(ssb, TextView.BufferType.SPANNABLE)
}

VerticalImageSpan class from great answer https://stackoverflow.com/a/38788432/5381331

Using

val textView = findViewById<TextView>(R.id.textview)
textView.setText("Send an [email-icon] to [email protected].")
textView.addImage("[email-icon]", R.drawable.ic_email,
        resources.getDimensionPixelOffset(R.dimen.dp_30),
        resources.getDimensionPixelOffset(R.dimen.dp_30))

Result

Note
Why VerticalImageSpan class?
ImageSpan.ALIGN_CENTER attribute requires API 29.
Also, after the test, I see that ImageSpan.ALIGN_CENTER only work if the image smaller than the text, if the image bigger than the text then only image is in center, text not center, it align on bottom of image

how to get program files x86 env variable?

IMHO, one point that is missing in this discussion is that whatever variable you use, it is guaranteed to always point at the appropriate folder. This becomes critical in the rare cases where Windows is installed on a drive other than C:\

How to split string using delimiter char using T-SQL?

You simply need to do a SUBSTR on the string in col3....

    Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'), 
    (instr(col3, '|', instr(col3, 'Client Name')  -
    instr(col3, 'Client Name'))
    ),
'Client Name = ',
'')
    from Table01 

And yes, that is a bad DB design for the reasons stated in the original issue

Difference between 'struct' and 'typedef struct' in C++?

There is no difference in C++, but I believe in C it would allow you to declare instances of the struct Foo without explicitly doing:

struct Foo bar;

How can I set the value of a DropDownList using jQuery?

In case when you load all <options ....></options> by Ajax call
Follow these step to do this.

1). Create a separate method for set value of drop-down
For Ex:

function set_ip_base_country(countryCode)
    $('#country').val(countryCode)
} 

2). Call this method when ajax call success all html append task complete

For Ex:

success: function (doc) {
  .....
  .....
  $("#country").append('<option style="color:black;" value="' + key + '">'  +   value + '</option>')
  set_ip_base_country(ip_base_country)
}

Sort Pandas Dataframe by Date

The data containing the date column can be read by using the below code:

data = pd.csv(file_path,parse_dates=[date_column])

Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time() like:

pd.date_time(data[date_column], format = '%d/%m/%y')

to change the format of date as per the requirement.

Change Button color onClick

Every time setColor gets hit, you are setting count = 1. You would need to define count outside of the scope of the function. Example:

var count=1;
function setColor(btn, color){
    var property = document.getElementById(btn);
    if (count == 0){
        property.style.backgroundColor = "#FFFFFF"
        count=1;        
    }
    else{
        property.style.backgroundColor = "#7FFF00"
        count=0;
    }

}

Find html label associated with a given input

For future searchers... The following is a jQuery-ified version of FlySwat's accepted answer:

var labels = $("label");
for (var i = 0; i < labels.length; i++) {
    var fieldId = labels[i].htmlFor;
    if (fieldId != "") {
        var elem = $("#" + fieldId);
        if (elem.length != 0) {
            elem.data("label", $(labels[i]));   
        }
    }
}

Using:

$("#myFormElemId").data("label").css("border","3px solid red");

Limit to 2 decimal places with a simple pipe

Well now will be different after angular 5:

{{ number | currency :'GBP':'symbol':'1.2-2' }}

Nullable type as a generic parameter possible?

I just encountered the same problem myself.

... = reader["myYear"] as int?; works and is clean.

It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.

Confirm deletion in modal / dialog using Twitter Bootstrap?

  // ---------------------------------------------------------- Generic Confirm  

  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal hide fade">' +    
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    });

    confirmModal.modal('show');     
  };

  // ---------------------------------------------------------- Confirm Put To Use

  $("i#deleteTransaction").live("click", function(event) {
    // get txn id from current table row
    var id = $(this).data('id');

    var heading = 'Confirm Transaction Delete';
    var question = 'Please confirm that you wish to delete transaction ' + id + '.';
    var cancelButtonTxt = 'Cancel';
    var okButtonTxt = 'Confirm';

    var callback = function() {
      alert('delete confirmed ' + id);
    };

    confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);

  });

Using Git with Visual Studio

I use Git with Visual Studio for my port of Protocol Buffers to C#. I don't use the GUI - I just keep a command line open as well as Visual Studio.

For the most part it's fine - the only problem is when you want to rename a file. Both Git and Visual Studio would rather that they were the one to rename it. I think that renaming it in Visual Studio is the way to go though - just be careful what you do at the Git side afterwards. Although this has been a bit of a pain in the past, I've heard that it actually should be pretty seamless on the Git side, because it can notice that the contents will be mostly the same. (Not entirely the same, usually - you tend to rename a file when you're renaming the class, IME.)

But basically - yes, it works fine. I'm a Git newbie, but I can get it to do everything I need it to. Make sure you have a git ignore file for bin and obj, and *.user.

How to take MySQL database backup using MySQL Workbench?

  1. On ‘HOME’ page -- > select 'Manage Import / Export' under 'Server Administration'

  2. A box comes up... choose which server holds the data you want to back up.

  3. On the 'Export to Disk' tab, then select which databases you want to export.

  4. If you want all the tables, select option ‘Export to self-contained file’, otherwise choose the other option for a selective restore

  5. If you need advanced options, see other post, otherwise then click ‘Start Export’

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

I believe you need to reference the current HttpContext if you are outside of the controller. The MVC controllers have a base reference to the current context. However, outside of that, you have to explicitly declare you want the current HttpContext

return HttpContext.Current.GetOwinContext().Authentication;

As for it not showing up, a new MVC 5 project template using the code you show above (the IAuthenticationManager) has the following using statements at the top of the account controller:

using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using WebApplication2.Models;

Commenting out each one, it appears the GetOwinContext() is actually a part of the System.Web.Mvc assembly.

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

I also struggled finding articles on how to just generate the token part. I never found one and wrote my own. So if it helps:

The things to do are:

  • Create a new web application
  • Install the following NuGet packages:
    • Microsoft.Owin
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security.OAuth
    • Microsoft.AspNet.Identity.Owin
  • Add a OWIN startup class

Then create a HTML and a JavaScript (index.js) file with these contents:

var loginData = 'grant_type=password&[email protected]&password=test123';

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        alert(xmlhttp.responseText);
    }
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="index.js"></script>
</body>
</html>

The OWIN startup class should have this content:

using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;

[assembly: OwinStartup(typeof(Startup))]

namespace OAuth20
{
    public class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            OAuthOptions = new OAuthAuthorizationServerOptions()
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new OAuthAuthorizationServerProvider()
                {
                    OnValidateClientAuthentication = async (context) =>
                    {
                        context.Validated();
                    },
                    OnGrantResourceOwnerCredentials = async (context) =>
                    {
                        if (context.UserName == "[email protected]" && context.Password == "test123")
                        {
                            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                            context.Validated(oAuthIdentity);
                        }
                    }
                },
                AllowInsecureHttp = true,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
            };

            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

Run your project. The token should be displayed in the pop-up.

MAVEN_HOME, MVN_HOME or M2_HOME

M2_HOME (and the like) is not to be used as of Maven 3.5.0. See MNG-5607 and Release Notes for details.

google maps v3 marker info window on mouseover

Thanks to duncan answer, I end up with this:

marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())

Why do you have to link the math library in C?

An explanation is given here:

So if your program is using math functions and including math.h, then you need to explicitly link the math library by passing the -lm flag. The reason for this particular separation is that mathematicians are very picky about the way their math is being computed and they may want to use their own implementation of the math functions instead of the standard implementation. If the math functions were lumped into libc.a it wouldn't be possible to do that.

[Edit]

I'm not sure I agree with this, though. If you have a library which provides, say, sqrt(), and you pass it before the standard library, a Unix linker will take your version, right?

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

Github: Can I see the number of downloads for a repo?

I ended up writing a scraper script to find my clone count:

#!/bin/sh
#
# This script requires:
#   apt-get install html-xml-utils
#   apt-get install jq
#
USERNAME=dougluce
PASSWORD="PASSWORD GOES HERE, BE CAREFUL!"
REPO="dougluce/node-autovivify"

TOKEN=`curl https://github.com/login -s -c /tmp/cookies.txt | \
     hxnormalize | \
     hxselect 'input[name=authenticity_token]' 2>/dev/null | \
     perl -lne 'print $1 if /value=\"(\S+)\"/'`

curl -X POST https://github.com/session \
     -s -b /tmp/cookies.txt -c /tmp/cookies2.txt \
     --data-urlencode commit="Sign in" \
     --data-urlencode authenticity_token="$TOKEN" \
     --data-urlencode login="$USERNAME" \
     --data-urlencode password="$PASSWORD" > /dev/null

curl "https://github.com/$REPO/graphs/clone-activity-data" \
     -s -b /tmp/cookies2.txt \
     -H "x-requested-with: XMLHttpRequest" | jq '.summary'

This'll grab the data from the same endpoint that Github's clone graph uses and spit out the totals from it. The data also includes per-day counts, replace .summary with just . to see those pretty-printed.

How can I verify if an AD account is locked?

I found also this list of property flags: How to use the UserAccountControl flags

SCRIPT  0x0001  1
ACCOUNTDISABLE  0x0002  2
HOMEDIR_REQUIRED    0x0008  8
LOCKOUT 0x0010  16
PASSWD_NOTREQD  0x0020  32
PASSWD_CANT_CHANGE 0x0040   64
ENCRYPTED_TEXT_PWD_ALLOWED  0x0080  128
TEMP_DUPLICATE_ACCOUNT  0x0100  256
NORMAL_ACCOUNT  0x0200  512
INTERDOMAIN_TRUST_ACCOUNT   0x0800  2048
WORKSTATION_TRUST_ACCOUNT   0x1000  4096
SERVER_TRUST_ACCOUNT    0x2000  8192
DONT_EXPIRE_PASSWORD    0x10000 65536
MNS_LOGON_ACCOUNT   0x20000 131072
SMARTCARD_REQUIRED  0x40000 262144
TRUSTED_FOR_DELEGATION  0x80000 524288
NOT_DELEGATED   0x100000    1048576
USE_DES_KEY_ONLY    0x200000    2097152
DONT_REQ_PREAUTH    0x400000    4194304
PASSWORD_EXPIRED    0x800000    8388608
TRUSTED_TO_AUTH_FOR_DELEGATION  0x1000000   16777216
PARTIAL_SECRETS_ACCOUNT 0x04000000      67108864

You must make a binary-AND of property userAccountControl with 0x002. In order to get all locked (i.e. disabled) accounts you can filter on this:

(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))

For operator 1.2.840.113556.1.4.803 see LDAP Matching Rules

What is the regex for "Any positive integer, excluding 0"

Just for fun, another alternative using lookaheads:

^(?=\d*[1-9])\d+$

As many digits as you want, but at least one must be [1-9].

collapse cell in jupyter notebook

JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell. enter image description here

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

add in project root path google-services.json

dependencies {
compile 'com.android.support:support-v4:25.0.1'
**compile 'com.google.firebase:firebase-ads:9.0.2'**
compile files('libs/StartAppInApp-3.5.0.jar')
compile 'com.android.support:multidex:1.0.1'
  }
apply plugin: 'com.google.gms.google-services'

How to position the Button exactly in CSS

So, the trick here is to use absolute positioning calc like this:

top: calc(50% - XYpx);
left: calc(50% - XYpx);

where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

How to enable TLS 1.2 in Java 7

You should probably be looking to the configuration that controls the underlying platform TLS implementation via -Djdk.tls.client.protocols=TLSv1.2.

mongodb group values by multiple fields

TLDR Summary

In modern MongoDB releases you can brute force this with $slice just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push to an array.

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$project": {
        "books": { "$slice": [ "$books", 2 ] },
        "count": 1
    }}
])

MongoDB 3.6 Preview

Still not resolving SERVER-9377, but in this release $lookup allows a new "non-correlated" option which takes an "pipeline" expression as an argument instead of the "localFields" and "foreignFields" options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit in order to return the "top-n" results.

db.books.aggregate([
  { "$group": {
    "_id": "$addr",
    "count": { "$sum": 1 }
  }},
  { "$sort": { "count": -1 } },
  { "$limit": 2 },
  { "$lookup": {
    "from": "books",
    "let": {
      "addr": "$_id"
    },
    "pipeline": [
      { "$match": { 
        "$expr": { "$eq": [ "$addr", "$$addr"] }
      }},
      { "$group": {
        "_id": "$book",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1  } },
      { "$limit": 2 }
    ],
    "as": "books"
  }}
])

The other addition here is of course the ability to interpolate the variable through $expr using $match to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit each result separately.

This would be the next best option to running parallel queries, and actually would be better if the $match were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push" as the referenced issue asks, it actually delivers something that should work better.


Original Content

You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 }
])

Now that will give you a result like this:

{
    "result" : [
            {
                    "_id" : "address1",
                    "books" : [
                            {
                                    "book" : "book4",
                                    "count" : 1
                            },
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 3
                            }
                    ],
                    "count" : 5
            },
            {
                    "_id" : "address2",
                    "books" : [
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 2
                            }
                    ],
                    "count" : 3
            }
    ],
    "ok" : 1
}

So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.

This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$unwind": "$books" },
    { "$sort": { "count": 1, "books.count": -1 } },
    { "$group": {
        "_id": "$_id",
        "books": { "$push": "$books" },
        "count": { "$first": "$count" }
    }},
    { "$project": {
        "_id": {
            "_id": "$_id",
            "books": "$books",
            "count": "$count"
        },
        "newBooks": "$books"
    }},
    { "$unwind": "$newBooks" },
    { "$group": {
      "_id": "$_id",
      "num1": { "$first": "$newBooks" }
    }},
    { "$project": {
        "_id": "$_id",
        "newBooks": "$_id.books",
        "num1": 1
    }},
    { "$unwind": "$newBooks" },
    { "$project": {
        "_id": "$_id",
        "num1": 1,
        "newBooks": 1,
        "seen": { "$eq": [
            "$num1",
            "$newBooks"
        ]}
    }},
    { "$match": { "seen": false } },
    { "$group":{
        "_id": "$_id._id",
        "num1": { "$first": "$num1" },
        "num2": { "$first": "$newBooks" },
        "count": { "$first": "$_id.count" }
    }},
    { "$project": {
        "num1": 1,
        "num2": 1,
        "count": 1,
        "type": { "$cond": [ 1, [true,false],0 ] }
    }},
    { "$unwind": "$type" },
    { "$project": {
        "books": { "$cond": [
            "$type",
            "$num1",
            "$num2"
        ]},
        "count": 1
    }},
    { "$group": {
        "_id": "$_id",
        "count": { "$first": "$count" },
        "books": { "$push": "$books" }
    }},
    { "$sort": { "count": -1 } }
])

So that will actually give you the top 2 "books" from the top two "address" entries.

But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.


Demonstration Code

The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.

index.js

const { MongoClient } = require('mongodb');
const fs = require('mz/fs');

const uri = 'mongodb://localhost:27017';

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {
    const client = await MongoClient.connect(uri);

    const db = client.db('bookDemo');
    const books = db.collection('books');

    let { version } = await db.command({ buildInfo: 1 });
    version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);

    // Clear and load books
    await books.deleteMany({});

    await books.insertMany(
      (await fs.readFile('books.json'))
        .toString()
        .replace(/\n$/,"")
        .split("\n")
        .map(JSON.parse)
    );

    if ( version >= 3.6 ) {

    // Non-correlated pipeline with limits
      let result = await books.aggregate([
        { "$group": {
          "_id": "$addr",
          "count": { "$sum": 1 }
        }},
        { "$sort": { "count": -1 } },
        { "$limit": 2 },
        { "$lookup": {
          "from": "books",
          "as": "books",
          "let": { "addr": "$_id" },
          "pipeline": [
            { "$match": {
              "$expr": { "$eq": [ "$addr", "$$addr" ] }
            }},
            { "$group": {
              "_id": "$book",
              "count": { "$sum": 1 },
            }},
            { "$sort": { "count": -1 } },
            { "$limit": 2 }
          ]
        }}
      ]).toArray();

      log({ result });
    }

    // Serial result procesing with parallel fetch

    // First get top addr items
    let topaddr = await books.aggregate([
      { "$group": {
        "_id": "$addr",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1 } },
      { "$limit": 2 }
    ]).toArray();

    // Run parallel top books for each addr
    let topbooks = await Promise.all(
      topaddr.map(({ _id: addr }) =>
        books.aggregate([
          { "$match": { addr } },
          { "$group": {
            "_id": "$book",
            "count": { "$sum": 1 }
          }},
          { "$sort": { "count": -1 } },
          { "$limit": 2 }
        ]).toArray()
      )
    );

    // Merge output
    topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
    log({ topaddr });

    client.close();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

books.json

{ "addr": "address1",  "book": "book1"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book5"  }
{ "addr": "address3",  "book": "book9"  }
{ "addr": "address2",  "book": "book5"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book1"  }
{ "addr": "address15", "book": "book1"  }
{ "addr": "address9",  "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4",  "book": "book3"  }
{ "addr": "address5",  "book": "book1"  }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1",  "book": "book1"  }

Calculating powers of integers

Best the algorithm is based on the recursive power definition of a^b.

long pow (long a, int b)
{
    if ( b == 0)        return 1;
    if ( b == 1)        return a;
    if (isEven( b ))    return     pow ( a * a, b/2); //even a=(a^2)^b/2
    else                return a * pow ( a * a, b/2); //odd  a=a*(a^2)^b/2

}

Running time of the operation is O(logb). Reference:More information

from unix timestamp to datetime

Without moment.js:

_x000D_
_x000D_
var time_to_show = 1509968436; // unix timestamp in seconds_x000D_
_x000D_
var t = new Date(time_to_show * 1000);_x000D_
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);_x000D_
_x000D_
document.write(formatted);
_x000D_
_x000D_
_x000D_

ERROR 1148: The used command is not allowed with this MySQL version

SpringBoot 2.1 with Default MySQL connector

To Solve this please follow the instructions

1. SET GLOBAL local_infile = 1;

to set this global variable please follow the instruction provided in MySQL documentation https://dev.mysql.com/doc/refman/8.0/en/load-data-local.html

2. Change the MySQL Connector String

allowLoadLocalInfile=true Example : jdbc:mysql://localhost:3306/xxxx?useSSL=false&useUnicode=yes&characterEncoding=UTF-8&allowLoadLocalInfile=true

Print text instead of value from C enum

Enumerations in C are numbers that have convenient names inside your code. They are not strings, and the names assigned to them in the source code are not compiled into your program, and so they are not accessible at runtime.

The only way to get what you want is to write a function yourself that translates the enumeration value into a string. E.g. (assuming here that you move the declaration of enum Days outside of main):

const char* getDayName(enum Days day) 
{
   switch (day) 
   {
      case Sunday: return "Sunday";
      case Monday: return "Monday";
      /* etc... */
   }
}

/* Then, later in main: */
printf("%s", getDayName(TheDay));

Alternatively, you could use an array as a map, e.g.

const char* dayNames[] = {"Sunday", "Monday", "Tuesday", /* ... etc ... */ };

/* ... */

printf("%s", dayNames[TheDay]);

But here you would probably want to assign Sunday = 0 in the enumeration to be safe... I'm not sure if the C standard requires compilers to begin enumerations from 0, although most do (I'm sure someone will comment to confirm or deny this).

Stored procedure - return identity as output parameter or scalar

I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.

Swift - How to hide back button in navigation item?

In case you're using a UITabBarController:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBarController?.navigationItem.hidesBackButton = true
}

How to parse a CSV file using PHP

Just use the function for parsing a CSV file

http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
  }
  fclose($handle);
}

When to use static keyword before global variables?

The static keyword is used in C to restrict the visibility of a function or variable to its translation unit. Translation unit is the ultimate input to a C compiler from which an object file is generated.

Check this: Linkage | Translation unit

Submit form with Enter key without submit button?

Change #form to your form's ID

$('#form input').keydown(function(e) {
    if (e.keyCode == 13) {
        $('#form').submit();
    }
});

Or alternatively

$('input').keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).closest('form').submit();
    }
});

How to make Git "forget" about a file that was tracked but is now in .gitignore?

The accepted answer does not "make Git "forget" about a file..." (historically). It only makes git ignore the file in the present/future.

This method makes git completely forget ignored files (past/present/future), but does not delete anything from working directory (even when re-pulled from remote).

This method requires usage of /.git/info/exclude (preferred) OR a pre-existing .gitignore in all the commits that have files to be ignored/forgotten. 1

All methods of enforcing git ignore behavior after-the-fact effectively re-write history and thus have significant ramifications for any public/shared/collaborative repos that might be pulled after this process. 2

General advice: start with a clean repo - everything committed, nothing pending in working directory or index, and make a backup!

Also, the comments/revision history of this answer (and revision history of this question) may be useful/enlightening.

#commit up-to-date .gitignore (if not already existing)
#this command must be run on each branch

git add .gitignore
git commit -m "Create .gitignore"

#apply standard git ignore behavior only to current index, not working directory (--cached)
#if this command returns nothing, ensure /.git/info/exclude AND/OR .gitignore exist
#this command must be run on each branch

git ls-files -z --ignored --exclude-standard | xargs -0 git rm --cached

#Commit to prevent working directory data loss!
#this commit will be automatically deleted by the --prune-empty flag in the following command
#this command must be run on each branch

git commit -m "ignored index"

#Apply standard git ignore behavior RETROACTIVELY to all commits from all branches (--all)
#This step WILL delete ignored files from working directory UNLESS they have been dereferenced from the index by the commit above
#This step will also delete any "empty" commits.  If deliberate "empty" commits should be kept, remove --prune-empty and instead run git reset HEAD^ immediately after this command

git filter-branch --tree-filter 'git ls-files -z --ignored --exclude-standard | xargs -0 git rm -f --ignore-unmatch' --prune-empty --tag-name-filter cat -- --all

#List all still-existing files that are now ignored properly
#if this command returns nothing, it's time to restore from backup and start over
#this command must be run on each branch

git ls-files --other --ignored --exclude-standard

Finally, follow the rest of this GitHub guide (starting at step 6) which includes important warnings/information about the commands below.

git push origin --force --all
git push origin --force --tags
git for-each-ref --format="delete %(refname)" refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --prune=now

Other devs that pull from now-modified remote repo should make a backup and then:

#fetch modified remote

git fetch --all

#"Pull" changes WITHOUT deleting newly-ignored files from working directory
#This will overwrite local tracked files with remote - ensure any local modifications are backed-up/stashed

git reset FETCH_HEAD

Footnotes

1 Because /.git/info/exclude can be applied to all historical commits using the instructions above, perhaps details about getting a .gitignore file into the historical commit(s) that need it is beyond the scope of this answer. I wanted a proper .gitignore to be in the root commit, as if it was the first thing I did. Others may not care since /.git/info/exclude can accomplish the same thing regardless where the .gitignore exists in the commit history, and clearly re-writing history is a very touchy subject, even when aware of the ramifications.

FWIW, potential methods may include git rebase or a git filter-branch that copies an external .gitignore into each commit, like the answers to this question

2 Enforcing git ignore behavior after-the-fact by committing the results of a standalone git rm --cached command may result in newly-ignored file deletion in future pulls from the force-pushed remote. The --prune-empty flag in the following git filter-branch command avoids this problem by automatically removing the previous "delete all ignored files" index-only commit. Re-writing git history also changes commit hashes, which will wreak havoc on future pulls from public/shared/collaborative repos. Please understand the ramifications fully before doing this to such a repo. This GitHub guide specifies the following:

Tell your collaborators to rebase, not merge, any branches they created off of your old (tainted) repository history. One merge commit could reintroduce some or all of the tainted history that you just went to the trouble of purging.

Alternative solutions that do not affect the remote repo are git update-index --assume-unchanged </path/file> or git update-index --skip-worktree <file>, examples of which can be found here.

How to extract IP Address in Spring MVC Controller get call?

private static final String[] IP_HEADER_CANDIDATES = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR"
    };

    public static String getIPFromRequest(HttpServletRequest request) {
        String ip = null;
        if (request == null) {
            if (RequestContextHolder.getRequestAttributes() == null) {
                return null;
            }
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }

        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(ip))
            return ip;

        for (String header : IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                return ipList.split(",")[0];
            }
        }

        return request.getRemoteAddr();
    }

I combie the code above to this code work for most case. Pass the HttpServletRequest request you get from the api to the method

Writing/outputting HTML strings unescaped

In ASP.NET MVC 3 You should do something like this:

// Say you have a bit of HTML like this in your controller:
ViewBag.Stuff = "<li>Menu</li>"
//  Then you can do this in your view:
@MvcHtmlString.Create(ViewBag.Stuff)

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

you can use this method just pass your date to it

-(NSString *)getDateFromString:(NSString *)string
{

    NSString * dateString = [NSString stringWithFormat: @"%@",string];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"your current date format"];
    NSDate* myDate = [dateFormatter dateFromString:dateString];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"your desired format"];
    NSString *stringFromDate = [formatter stringFromDate:myDate];

    NSLog(@"%@", stringFromDate);
    return stringFromDate;
}

Real differences between "java -server" and "java -client"?

This is really linked to HotSpot and the default option values (Java HotSpot VM Options) which differ between client and server configuration.

From Chapter 2 of the whitepaper (The Java HotSpot Performance Engine Architecture):

The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults.

Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint.

The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs.

So the real difference is also on the compiler level:

The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint.

The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.

Note: The release of jdk6 update 10 (see Update Release Notes:Changes in 1.6.0_10) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel.


G. Demecki points out in the comments that in 64-bit versions of JDK, the -client option is ignored for many years.
See Windows java command:

-client

Selects the Java HotSpot Client VM.
A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM.

Getting the current Fragment instance in the viewpager

The scenario in question is better served by each Fragment adding its own menu items and directly handling onOptionsItemSelected(), as described in official documentation. It is better to avoid undocumented tricks.

How to align entire html body to the center?

If I have one thing that I love to share with respect to CSS, it's MY FAVE WAY OF CENTERING THINGS ALONG BOTH AXES!!!

Advantages of this method:

  1. Full compatibility with browsers that people actually use
  2. No tables required
  3. Highly reusable for centering any other elements inside their parent
  4. Accomodates parents and children with dynamic (changing) dimensions!

I always do this by using 2 classes: One to specify the parent element, whose content will be centered (.centered-wrapper), and the 2nd one to specify which child of the parent is centered (.centered-content). This 2nd class is useful in the case where the parent has multiple children, but only 1 needs to be centered). In this case, body will be the .centered-wrapper, and an inner div will be .centered-content.

<html>
    <head>...</head>
    <body class="centered-wrapper">
        <div class="centered-content">...</div>
    </body>
</html>

The idea for centering will now be to make .centered-content an inline-block. This will easily facilitate horizontal centering, through text-align: center;, and also allows for vertical centering as you shall see.

.centered-wrapper {
    position: relative;
    text-align: center;
}
.centered-wrapper:before {
    content: "";
    position: relative;
    display: inline-block;
    width: 0; height: 100%;
    vertical-align: middle;
}
.centered-content {
    display: inline-block;
    vertical-align: middle;
}

This gives you 2 really reusable classes for centering any child inside of any parent! Just add the .centered-wrapper and .centered-content classes.

So, what's up with that :before element? It facilitates vertical-align: middle; and is necessary because vertical alignment isn't relative to the height of the parent - vertical alignment is relative to the height of the tallest sibling!!!. Therefore, by ensuring that there is a sibling whose height is the parent's height (100% height, 0 width to make it invisible), we know that vertical alignment will be with respect to the parent's height.

One last thing: You need to ensure that your html and body tags are the size of the window so that centering to them is the same as centering to the browser!

html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

Fiddle: https://jsfiddle.net/gershy/g121g72a/

PHP to search within txt file and echo the whole line

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

<?php
$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
print_r($matches);
?>

Note the way strpos is used with !== operator.

How do you execute SQL from within a bash script?

If you do not want to install sqlplus on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.

The tool can be used to run any SQL from the Linux bash or Windows command line.

Example:

java -jar sql-runner-0.2.0-with-dependencies.jar \
     -j jdbc:oracle:thin:@//oracle-db:1521/ORCLPDB1.localdomain \
     -U "SYS as SYSDBA" \
     -P Oradoc_db1 \
      "select 1 from dual"

Documentation is here.

You can download the binary file from here.

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

Convert number to varchar in SQL with formatting

What is the value range? Is it 0 through 10? If so, then try:

SELECT REPLICATE('0',2-LEN(@t)) + CAST(@t AS VARCHAR)

That handles 0 through 9 as well as 10 through 99.

Now, tinyint can go up to the value of 255. If you want to handle > 99 through 255, then try this solution:

declare @t  TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',2-LEN(@t)),'') + CAST(@t AS VARCHAR)

To understand the solution, the expression to the left of the + calculates the number of zeros to prefix to the string.

In case of the value 3, the length is 1. 2 - 1 is 1. REPLICATE Adds one zero. In case of the value 10, the length is 2. 2 - 2 is 0. REPLICATE Adds nothing. In the case of the value 100, the length is -1 which produces a NULL. However, the null value is handled and set to an empty string.

Now if you decide that because tinyint can contain up to 255 and you want your formatting as three characters, just change the 2-LEN to 3-LEN in the left expression and you're set.

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

Access Database opens as read only

Check that there are no missing references - to do this, go to the database window and click on "Modules", then "Design", then select the menu "Tools" and then "References". Or try doing a compile and see if it compiles fully (go to the Debug menu then select Compile) - it might tell you of a missing reference e.g. Microsoft Office 11.0 Object Library. Select References from the Tools menu again and see if any references are ticked and say "MISSING:". In some cases you can select a different version from the list, if 11.0 is missing, look for version 12.0 then recompile. That usually does the trick for me.

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

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

How to get an isoformat datetime string including the default timezone?

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>

What is a good naming convention for vars, methods, etc in C++?

Do whatever you want as long as its minimal, consistent, and doesn't break any rules.

Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on m and p prefixes to members and parameters, respectively, giving:

#ifndef NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#define NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP

#include <boost/headers/go/first>
#include <boost/in_alphabetical/order>
#include <then_standard_headers>
#include <in_alphabetical_order>

#include "then/any/detail/headers"
#include "in/alphabetical/order"
#include "then/any/remaining/headers/in"
// (you'll never guess)
#include "alphabetical/order/duh"

#define NAMESPACE_NAMES_THEN_MACRO_NAME(pMacroNames) ARE_ALL_CAPS

namespace lowercase_identifers
{
    class separated_by_underscores
    {
    public:
        void because_underscores_are() const
        {
            volatile int mostLikeSpaces = 0; // but local names are condensed

            while (!mostLikeSpaces)
                single_statements(); // don't need braces

            for (size_t i = 0; i < 100; ++i)
            {
                but_multiple(i);
                statements_do();
            }             
        }

        const complex_type& value() const
        {
            return mValue; // no conflict with value here
        }

        void value(const complex_type& pValue)
        {
            mValue = pValue ; // or here
        }

    protected:
        // the more public it is, the more important it is,
        // so order: public on top, then protected then private

        template <typename Template, typename Parameters>
        void are_upper_camel_case()
        {
            // gman was here                
        }

    private:
        complex_type mValue;
    };
}

#endif

That. (And like I've said in comments, do not adopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)

Windows Batch: How to add Host-Entries?

Sometime I have to work from home and connect to office through vpn. Internal domain names should be resolved to different IPs at home. There are several names that have to be changed between office and home. For example:

At office, a => 192.168.0.3, b => 192.168.0.52. 
At home, a => 10.6.1.7, b => 10.4.5.23. 

My solution is to create two files: C:\WINDOWS\system32\drivers\etc\hosts-home and C:\WINDOWS\system32\drivers\etc\hosts-office. Each of them contains set of name-to-IP mapping. From Administrator PowerShell, When I work at the office, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-office .\drivers\etc\hosts

When I arrive at home, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-home .\drivers\etc\hosts

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

How to find indices of all occurrences of one string in another in JavaScript?

You sure can do this!

//make a regular expression out of your needle
var needle = 'le'
var re = new RegExp(needle,'gi');
var haystack = 'I learned to play the Ukulele';

var results = new Array();//this is the results you want
while (re.exec(haystack)){
  results.push(re.lastIndex);
}

Edit: learn to spell RegExp

Also, I realized this isn't exactly what you want, as lastIndex tells us the end of the needle not the beginning, but it's close - you could push re.lastIndex-needle.length into the results array...

Edit: adding link

@Tim Down's answer uses the results object from RegExp.exec(), and all my Javascript resources gloss over its use (apart from giving you the matched string). So when he uses result.index, that's some sort of unnamed Match Object. In the MDC description of exec, they actually describe this object in decent detail.

What is difference between XML Schema and DTD?

Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:

  • XML schemas are written in XML while DTD are derived from SGML syntax.
  • XML schemas define datatypes for elements and attributes while DTD doesn't support datatypes.
  • XML schemas allow support for namespaces while DTD does not.
  • XML schemas define number and order of child elements, while DTD does not.
  • XML schemas can be manipulated on your own with XML DOM but it is not possible in case of DTD.
  • using XML schema user need not to learn a new language but working with DTD is difficult for a user.
  • XML schema provides secure data communication i.e sender can describe the data in a way that receiver will understand, but in case of DTD data can be misunderstood by the receiver.
  • XML schemas are extensible while DTD is not extensible.

Not all these bullet points are 100% accurate, but you get the gist.

On the other hand:

  • DTD lets you define new ENTITY values for use in your XML file.
  • DTD lets you extend it local to an individual XML file.

How to add property to a class dynamically?

Just another example how to achieve desired effect

class Foo(object):

    _bar = None

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, value):
        self._bar = value

    def __init__(self, dyn_property_name):
        setattr(Foo, dyn_property_name, Foo.bar)

So now we can do stuff like:

>>> foo = Foo('baz')
>>> foo.baz = 5
>>> foo.bar
5
>>> foo.baz
5

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

BEWARE OF parse_requirements BEHAVIOUR!

Please note that pip.req.parse_requirements will change underscores to dashes. This was enraging me for a few days before I discovered it. Example demonstrating:

from pip.req import parse_requirements  # tested with v.1.4.1

reqs = '''
example_with_underscores
example-with-dashes
'''

with open('requirements.txt', 'w') as f:
    f.write(reqs)

req_deps = parse_requirements('requirements.txt')
result = [str(ir.req) for ir in req_deps if ir.req is not None]
print result

produces

['example-with-underscores', 'example-with-dashes']

How to display line numbers in 'less' (GNU)

You could filter the file through cat -n before piping to less:

cat -n file.txt | less

Or, if your version of less supports it, the -N option:

less -N file.txt

Plotting of 1-dimensional Gaussian distribution function

you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np 

#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)

x = np.arange(-10, 10, .1)

#plot the pdfs of these normal distributions 
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

How to sort an array based on the length of each element?

I adapted @shareef's answer to make it concise. I use,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

UIWebView open links in Safari

In Swift you can use the following code:

extension YourViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if let url = request.url, navigationType == UIWebView.NavigationType.linkClicked {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
            return false
        }
        return true
    }

}

Make sure you check for the URL value and the navigationType.

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

How do I limit the number of results returned from grep?

The -m option is probably what you're looking for:

grep -m 10 PATTERN [FILE]

From man grep:

-m NUM, --max-count=NUM
        Stop reading a file after NUM matching lines.  If the  input  is
        standard  input  from a regular file, and NUM matching lines are
        output, grep ensures that the standard input  is  positioned  to
        just  after the last matching line before exiting, regardless of
        the presence of trailing context lines.  This enables a  calling
        process  to resume a search.

Note: grep stops reading the file once the specified number of matches have been found!

Removing all empty elements from a hash / YAML?

If you're using Ruby 2.4+, you can call compact and compact!

h = { a: 1, b: false, c: nil }
h.compact! #=> { a: 1, b: false }

https://ruby-doc.org/core-2.4.0/Hash.html#method-i-compact-21

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. Click on Start menu > Programs > Microsoft Sql Server > Configuration Tools

  2. Select Sql Server Surface Area Configuration.

  3. Now click on Surface Area configuration for services and connections

  4. On the left pane of pop up window click on Remote Connections and Select Local and Remote connections radio button.

  5. Select Using both TCP/IP and named pipes radio button.

  6. click on apply and ok.

Now when try to connect to sql server using sql username and password u'll get the error mentioned below

Cannot connect to SQLEXPRESS.

ADDITIONAL INFORMATION:

Login failed for user 'username'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) ation To fix this error follow steps mentioned below

  1. connect to sql server using window authentication.

  2. Now right click on your server name at the top in left pane and select properties.

  3. Click on security and select sql server and windows authentication mode radio button.

  4. Click on OK.

  5. restart sql server servive by right clicking on server name and select restart.

Now your problem should be fixed and u'll be able to connect using sql server username and password.

Have fun. Ateev Gupta

Function for 'does matrix contain value X?'

For floating point data, you can use the new ismembertol function, which computes set membership with a specified tolerance. This is similar to the ismemberf function found in the File Exchange except that it is now built-in to MATLAB. Example:

>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
   5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
     1

What is Haskell used for in the real world?

One example of Haskell in action is xmonad, a "featureful window manager in less than 1200 lines of code".

PHP, MySQL error: Column count doesn't match value count at row 1

Your query has 8 or possibly even 9 variables, ie. Name, Description etc. But the values, these things ---> '', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", only total 7, the number of variables have to be the same as the values.

I had the same problem but I figured it out. Hopefully it will also work for you.

How Long Does it Take to Learn Java for a Complete Newbie?

I have to say that you are taking on a lot in just 10 weeks, I just finished a semester of Java programming at Indiana University Southeast, and I don't think I have begun to scratch the surface yet. Java is a very strict language in that its syntax is very tough to get a handle on if you have no programming experience at all. I will offer these pieces of advice go to www.bluej.org and down load there, Java compiler it is said to be the easiest to work with and that most college's use this. It is also, what we learned on and from what I know now I can say, they are right. Java is an object oriented language, and Bluej gives you a great understanding of objects. They also show you how to design, classes, methods, array, array list, hash maps, all of that is on this site and it is free. I hope this helps and good luck with your challange.

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

Java: how to initialize String[]?

I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).

public class StringTest {
    public static void main(String[] args) {
        String[] errorSoon = new String[100];
        errorSoon[0] = "Error, why?";
        //another approach would be direct initialization
        String[] errorsoon = {"Error , why?"};   
    }
}

How do I convert a number to a numeric, comma-separated formatted string?

I looked at several of the options. Here are my two favorites, because I needed to round the value.

,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2   = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy --------- 
--- Hank Freeman : [email protected] 
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
   SELECT
   FileGroupName = DS.name
   ,FileGroupType =
      CASE DS.[type]
        WHEN 'FG' THEN 'Filegroup'
        WHEN 'FD' THEN 'Filestream'
        WHEN 'FX' THEN 'Memory-optimized'
        WHEN 'PS' THEN 'Partition Scheme'
        ELSE 'Unknown'
      END
   ,SchemaName = SCH.name
   ,TableName = OBJ.name
   ,IndexType =
      CASE IDX.[type]
        WHEN 0 THEN 'Heap'
        WHEN 1 THEN 'Clustered'
        WHEN 2 THEN 'Nonclustered'
        WHEN 3 THEN 'XML'
        WHEN 4 THEN 'Spatial'
        WHEN 5 THEN 'Clustered columnstore'
        WHEN 6 THEN 'Nonclustered columnstore'
        WHEN 7 THEN 'Nonclustered hash'
      END
   ,IndexName = IDX.name
   ,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','')  --- MUST show for all types when no Primary key
   --,( Case WHEN IDX.[type] IN (2,6,7) then 0  else  p.rows  end )as Rowcounts_T
   ,AllocationDesc = AU.type_desc
/*
   ,RowCounts = p.rows  --- MUST show for all types when no Primary key
   ,TotalSizeKB2  = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
   ,UsedSizeKB    = Cast(Round(SUM(AU.used_pages / 0.128),0)as int) 
   ,DataSizeKB    = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
    --replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
   ,TotalSizeKB   = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
   ,UsedSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','') 
   ,DataSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
   ,DataSizeKB2   = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
   ,DataSizeKB3   = format(SUM(AU.data_pages / 0.128),'##,##0')
   --SELECT Format(1234567.8, '##,##0.00')
   ---
   ,is_default    = CONVERT(INT,DS.is_default)
   ,is_read_only = CONVERT(INT,DS.is_read_only)
  FROM
   sys.filegroups DS -- you could also use sys.data_spaces
    LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
    LEFT JOIN sys.partitions PA
      ON (AU.[type] IN (1,3) AND
          AU.container_id = PA.hobt_id) OR
         (AU.[type] = 2 AND
          AU.container_id = PA.[partition_id])
    LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
    LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
    LEFT JOIN sys.indexes IDX
      ON PA.[object_id] = IDX.[object_id] AND
         PA.index_id = IDX.index_id
    -----
    INNER JOIN 
      sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
  WHERE
    OBJ.type_desc = 'USER_TABLE' -- only include user tables
    OR
    DS.[type] = 'FD' -- or the filestream filegroup
  GROUP BY
    DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type]  ,DS.is_default   ,DS.is_read_only -- discard different allocation units
   ,p.rows  ,AU.type_desc  --- 
  ORDER BY
    DS.name ,SCH.name ,OBJ.name ,IDX.name
   ---
   ;

Text overwrite in visual studio 2010

If you don't have an insert key, and you're using Visual Studio 2019, then double-clicking the OVR text in the bottom right corner does not work. You'll have to use an on-screen keyboard, if you have one of those, or figure out what your insert key is mapped to. For me, on my mac keyboard hooked up to windows 10, it is the 0 key on the keypad.

Linux: Which process is causing "device busy" when doing umount?

That's exactly why the "fuser -m /mount/point" exists.

BTW, I don't think "fuser" or "lsof" will indicate when a resource is held by kernel module, although I don't usually have that issue..

Implode an array with JavaScript?

Like This:

[1,2,3,4].join('; ')

Html: Difference between cell spacing and cell padding

Cellpadding is the amount of space between the outer edges of the table cell and the content of the cell.

Cellspacing is the amount of space in between the individual table cells.

More Details *Link 1*

Link 2

Link 3

Count occurrences of a char in a string using Bash

awk is very cool, but why not keep it simple?

num=$(echo $var | grep -o "," | wc -l)

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

Solve the following equation system:

p = p0 + (p1 - p0) * s + (p2 - p0) * t

The point p is inside the triangle if 0 <= s <= 1 and 0 <= t <= 1 and s + t <= 1.

s,t and 1 - s - t are called the barycentric coordinates of the point p.

How to set maximum height for table-cell?

By CSS 2.1 rules, the height of a table cell is “the minimum height required by the content”. Thus, you need to restrict the height indirectly using inner markup, normally a div element (<td><div>content</div></td>), and set height and overflow properties on the the div element (without setting display: table-cell on it, of course, as that would make its height obey CSS 2.1 table cell rules).

How can I make git accept a self signed certificate?

Be careful when you are using one liner using sslKey or sslCert, as in Josh Peak's answer:

git clone -c http.sslCAPath="/path/to/selfCA" \
  -c http.sslCAInfo="/path/to/selfCA/self-signed-certificate.crt" \
  -c http.sslVerify=1 \
  -c http.sslCert="/path/to/privatekey/myprivatecert.pem" \
  -c http.sslCertPasswordProtected=0 \
https://mygit.server.com/projects/myproject.git myproject

Only Git 2.14.x/2.15 (Q3 2015) would be able to interpret a path like ~username/mykey correctly (while it still can interpret an absolute path like /path/to/privatekey).

See commit 8d15496 (20 Jul 2017) by Junio C Hamano (gitster).
Helped-by: Charles Bailey (hashpling).
(Merged by Junio C Hamano -- gitster -- in commit 17b1e1d, 11 Aug 2017)

http.c: http.sslcert and http.sslkey are both pathnames

Back when the modern http_options() codepath was created to parse various http.* options at 29508e1 ("Isolate shared HTTP request functionality", 2005-11-18, Git 0.99.9k), and then later was corrected for interation between the multiple configuration files in 7059cd9 ("http_init(): Fix config file parsing", 2009-03-09, Git 1.6.3-rc0), we parsed configuration variables like http.sslkey, http.sslcert as plain vanilla strings, because git_config_pathname() that understands "~[username]/" prefix did not exist.

Later, we converted some of them (namely, http.sslCAPath and http.sslCAInfo) to use the function, and added variables like http.cookeyFile http.pinnedpubkey to use the function from the beginning. Because of that, these variables all understand "~[username]/" prefix.

Make the remaining two variables, http.sslcert and http.sslkey, also aware of the convention, as they are both clearly pathnames to files.

Redirect all output to file in Bash

Command:

foo >> output.txt 2>&1

appends to the output.txt file, without replacing the content.

What order are the Junit @Before/@After called?

Yes, this behaviour is guaranteed:

@Before:

The @Before methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.

@After:

The @After methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.

Find all zero-byte files in directory and subdirectories

To print the names of all files in and below $dir of size 0:

find "$dir" -size 0

Note that not all implementations of find will produce output by default, so you may need to do:

find "$dir" -size 0 -print

Two comments on the final loop in the question:

Rather than iterating over every other word in a string and seeing if the alternate values are zero, you can partially eliminate the issue you're having with whitespace by iterating over lines. eg:

printf '1 f1\n0 f 2\n10 f3\n' | while read size path; do
    test "$size" -eq 0 && echo "$path"; done

Note that this will fail in your case if any of the paths output by ls contain newlines, and this reinforces 2 points: don't parse ls, and have a sane naming policy that doesn't allow whitespace in paths.

Secondly, to output the data from the loop, there is no need to store the output in a variable just to echo it. If you simply let the loop write its output to stdout, you accomplish the same thing but avoid storing it.

div with dynamic min-height based on browser window height

Just look for my solution on jsfiddle, it is based on csslayout

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  height: 100%; /* needed for container min-height */_x000D_
}_x000D_
div#container {_x000D_
  position: relative; /* needed for footer positioning*/_x000D_
  height: auto !important; /* real browsers */_x000D_
  min-height: 100%; /* real browsers */_x000D_
}_x000D_
div#header {_x000D_
  padding: 1em;_x000D_
  background: #efe;_x000D_
}_x000D_
div#content {_x000D_
  /* padding:1em 1em 5em; *//* bottom padding for footer */_x000D_
}_x000D_
div#footer {_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  bottom: 0; /* stick to bottom */_x000D_
  background: #ddd;_x000D_
}
_x000D_
<div id="container">_x000D_
_x000D_
  <div id="header">header</div>_x000D_
_x000D_
  <div id="content">_x000D_
    content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>_x000D_
  </div>_x000D_
_x000D_
  <div id="footer">_x000D_
    footer_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Case-insensitive string comparison in C++

A simple way to compare two string in c++ (tested for windows) is using _stricmp

// Case insensitive (could use equivalent _stricmp)  
result = _stricmp( string1, string2 );  

If you are looking to use with std::string, an example:

std::string s1 = string("Hello");
if ( _stricmp(s1.c_str(), "HELLO") == 0)
   std::cout << "The string are equals.";

For more information here: https://msdn.microsoft.com/it-it/library/e0z9k731.aspx

Array vs ArrayList in performance

When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.

How to Get a Sublist in C#

Use the Where clause from LINQ:

List<object> x = new List<object>();
x.Add("A");
x.Add("B");
x.Add("C");
x.Add("D");
x.Add("B");

var z = x.Where(p => p == "A");
z = x.Where(p => p == "B");

In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:

public class Client
{
    public string Name { get; set; }
}

then your linq would look like this:

List<Client> x = new List<Client>();
x.Add(new Client() { Name = "A" });
x.Add(new Client() { Name = "B" });
x.Add(new Client() { Name = "C" });
x.Add(new Client() { Name = "D" });
x.Add(new Client() { Name = "B" });

var z = x.Where(p => p.Name == "A");
z = x.Where(p => p.Name == "B");

Google Maps V3 - How to calculate the zoom level for a given bounds

For swift version

func getBoundsZoomLevel(bounds: GMSCoordinateBounds, mapDim: CGSize) -> Double {
        var bounds = bounds
        let WORLD_DIM = CGSize(width: 256, height: 256)
        let ZOOM_MAX: Double = 21.0
        func latRad(_ lat: Double) -> Double {
            let sin2 = sin(lat * .pi / 180)
            let radX2 = log10((1 + sin2) / (1 - sin2)) / 2
            return max(min(radX2, .pi), -.pi) / 2
        }
        func zoom(_ mapPx: CGFloat,_ worldPx: CGFloat,_ fraction: Double) -> Double {
            return floor(log10(Double(mapPx) / Double(worldPx) / fraction / log10(2.0)))
        }
        let ne = bounds.northEast
        let sw = bounds.southWest
        let latFraction = (latRad(ne.latitude) - latRad(sw.latitude)) / .pi
        let lngDiff = ne.longitude - sw.longitude
        let lngFraction = lngDiff < 0 ? (lngDiff + 360) : (lngDiff / 360)
        let latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
        let lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
        return min(latZoom, lngZoom, ZOOM_MAX)
    }

Remove the last line from a file in Bash

Mac Users

if you only want the last line deleted output without changing the file itself do

sed -e '$ d' foo.txt

if you want to delete the last line of the input file itself do

sed -i '' -e '$ d' foo.txt

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

TABLOCK vs TABLOCKX

Big difference, TABLOCK will try to grab "shared" locks, and TABLOCKX exclusive locks.

If you are in a transaction and you grab an exclusive lock on a table, EG:

SELECT 1 FROM TABLE WITH (TABLOCKX)

No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.

TABLOCK only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED (default). If your isolation level is higher, for example: SERIALIZABLE, shared locks are held until the end of a transaction.


Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK). However, if transaction A holds a shared lock on a table, transaction B will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.


Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).

In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.

In general you would not use TABLOCK or TABLOCKX unless you absolutely needed it for some edge case.

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

Git and nasty "error: cannot lock existing info/refs fatal"

This is how it works for me.

  1. look up the Apache DAV lock file on your server (e.g. /var/lock/apache2/DAVlock)
  2. delete it
  3. recreate it with write permissions for the webserver
  4. restart the webserver

Even faster alternative:

  1. look up the Apache DAV lock file on your server (e.g. /var/lock/apache2/DAVlock)
  2. Empty the file: cat /dev/null > /var/lock/apache2/DAVlock
  3. restart the webserver

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

Storing a file in a database as opposed to the file system?

While performance is an issue, I think modern database designs have made it much less of an issue for small files.

Performance aside, it also depends on just how tightly-coupled the data is. If the file contains data that is closely related to the fields of the database, then it conceptually belongs close to it and may be stored in a blob. If it contains information which could potentially relate to multiple records or may have some use outside of the context of the database, then it belongs outside. For example, an image on a web page is fetched on a separate request from the page that links to it, so it may belong outside (depending on the specific design and security considerations).

Our compromise, and I don't promise it's the best, has been to store smallish XML files in the database but images and other files outside it.

Add CSS class to a div in code behind

For a non ASP.NET control, i.e. HTML controls like div, table, td, tr, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:

ASPX page

<head>
    <style type="text/css">
        .top_rounded
        {
            height: 75px;
            width: 75px;
            border: 2px solid;
            border-radius: 5px;
            -moz-border-radius: 5px; /* Firefox 3.6 and earlier */
            border-color: #9c1c1f;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="myDiv">This is my div</div>
    </form>
</body>

CS page

myDiv.Attributes.Add("class", "top_rounded");

How to replace special characters in a string?

string Output = Regex.Replace(Input, @"([ a-zA-Z0-9&, _]|^\s)", "");

Here all the special characters except space, comma, and ampersand are replaced. You can also omit space, comma and ampersand by the following regular expression.

string Output = Regex.Replace(Input, @"([ a-zA-Z0-9_]|^\s)", "");

Where Input is the string which we need to replace the characters.

How to add a Java Properties file to my Java Project in Eclipse

If you have created a Java Project in eclipse by using the 'from existing source' option then it should work as it did before. To be more precise File > New Java Project. In the Contents section select 'Create project from existing source' and then select your existing project folder. The wizard will take care of the rest.

MySQL Workbench - Connect to a Localhost

enter image description here

I think you want to config your database server firstly after the installation, as shown in picture, you can reconfigure MySql server

Positioning <div> element at center of screen

Now, is more easy with HTML 5 and CSS 3:

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body > div {
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                display: flex;
                justify-content: space-around;
                align-items: center;
                flex-wrap: wrap;
            }
        </style>
    </head>
    <body>
        <div>
            <div>TODO write content</div>
        </div>
    </body>
</html>

iOS 7 - Status bar overlaps the view

My status bar and navigation bar overlap after return from landscape view of YTPlayer. Here is my solution after trying @comonitos' version but not work on my iOS 8

- (void)fixNavigationBarPosition {
    if (self.navigationController) {
        CGRect frame = self.navigationController.navigationBar.frame;
        if (frame.origin.y != 20.f) {
            frame.origin.y = 20.f;
            self.navigationController.navigationBar.frame = frame;
        }
    }
}

Just call this function whenever you want to fix the position of navigation bar. I called on YTPlayerViewDelegate's playerView:didChangeToState:

- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
    switch (state) {
        case kYTPlayerStatePaused:
        case kYTPlayerStateEnded:
            [self fixNavigationBarPosition];
            break;
        default:
    }
}

set date in input type date

Update: I'm doing this with date.toISOString().substr(0, 10). Gives the same result as the accepted answer and has good support.

CSS disable hover effect

  .buttonDisabled{
     background-color: unset !important;
    color: unset !important;
}

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

How to check whether a string is Base64 encoded or not

Try this using a previously mentioned regex:

String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
    System.out.println("it's a Base64");
}

...We can also make a simple validation like, if it has spaces it cannot be Base64:

String myString = "Hello World";
 if(myString.contains(" ")){
   System.out.println("Not B64");
 }else{
    System.out.println("Could be B64 encoded, since it has no spaces");
 }

Invoke JSF managed bean action on page load

JSF 1.0 / 1.1

Just put the desired logic in the constructor of the request scoped bean associated with the JSF page.

public Bean() {
    // Do your stuff here.
}

JSF 1.2 / 2.x

Use @PostConstruct annotated method on a request or view scoped bean. It will be executed after construction and initialization/setting of all managed properties and injected dependencies.

@PostConstruct
public void init() {
    // Do your stuff here.
}

This is strongly recommended over constructor in case you're using a bean management framework which uses proxies, such as CDI, because the constructor may not be called at the times you'd expect it.

JSF 2.0 / 2.1

Alternatively, use <f:event type="preRenderView"> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:event type="preRenderView" listener="#{bean.onload}" />
</f:metadata>
public void onload() { 
    // Do your stuff here.
}

JSF 2.2+

Alternatively, use <f:viewAction> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
public void onload() { 
    // Do your stuff here.
}

Note that this can return a String navigation case if necessary. It will be interpreted as a redirect (so you do not need a ?faces-redirect=true here).

public String onload() { 
    // Do your stuff here.
    // ...
    return "some.xhtml";
}

See also:

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

CSS set li indent

to indent a ul dropdown menu, use

/* Main Level */
ul{
  margin-left:10px;
}

/* Second Level */
ul ul{
  margin-left:15px;
}

/* Third Level */
ul ul ul{
  margin-left:20px;
}

/* and so on... */

You can indent the lis and (if applicable) the as (or whatever content elements you have) as well , each with differing effects. You could also use padding-left instead of margin-left, again depending on the effect you want.

Update

By default, many browsers use padding-left to set the initial indentation. If you want to get rid of that, set padding-left: 0px;

Still, both margin-left and padding-left settings impact the indentation of lists in different ways. Specifically: margin-left impacts the indentation on the outside of the element's border, whereas padding-left affects the spacing on the inside of the element's border. (Learn more about the CSS box model here)

Setting padding-left: 0; leaves the li's bullet icons hanging over the edge of the element's border (at least in Chrome), which may or may not be what you want.

Examples of padding-left vs margin-left and how they can work together on ul: https://jsfiddle.net/daCrosby/bb7kj8cr/1/

PowerShell Script to Find and Replace for all Files with a Specific Extension

I found comment of @Artyom useful but unfortunately he has not posted an answer.

This is the short version, in my opinion best version, of the accepted answer;

ls *.config -rec | %{$f=$_; (gc $f.PSPath) | %{$_ -replace "Dev", "Demo"} | sc $f.PSPath}

Replace last occurrence of character in string

No need for jQuery nor regex assuming the character you want to replace exists in the string

Replace last char in a string

str = str.substring(0,str.length-2)+otherchar

Replace last underscore in a string

var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)

or use one of the regular expressions from the other answers

_x000D_
_x000D_
var str1 = "Replace the full stop with a questionmark."_x000D_
var str2 = "Replace last _ with another char other than the underscore _ near the end"_x000D_
_x000D_
// Replace last char in a string_x000D_
_x000D_
console.log(_x000D_
  str1.substring(0,str1.length-2)+"?"_x000D_
)  _x000D_
// alternative syntax_x000D_
console.log(_x000D_
  str1.slice(0,-1)+"?"_x000D_
)_x000D_
_x000D_
// Replace last underscore in a string _x000D_
_x000D_
var pos = str2.lastIndexOf('_'), otherchar = "|";_x000D_
console.log(_x000D_
  str2.substring(0,pos) + otherchar + str2.substring(pos+1)_x000D_
)_x000D_
// alternative syntax_x000D_
_x000D_
console.log(_x000D_
  str2.slice(0,pos) + otherchar + str2.slice(pos+1)_x000D_
)
_x000D_
_x000D_
_x000D_

openCV video saving in python

As an example :

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out_corner = cv2.VideoWriter('img_corner_1.avi',fourcc, 20.0, (640, 480))

At that place, have to define X,Y as width and height

But, when you create an image (a blank image for instance) you have to define Y,X as height and width :

    img_corner = np.zeros((480, 640, 3), np.uint8)

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8" and then let your API method consume JSON. Like this:

var basicInfo = JSON.stringify({
    firstName: playerProfile.firstName(),
    lastName: playerProfile.lastName(),
    gender: playerProfile.gender(),
    address: playerProfile.address(),
    country: playerProfile.country(),
    bio: playerProfile.bio()
});

$.ajax({
    url: "http://localhost:8080/social/profile/update",
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: basicInfo,
    success: function(data) {
        // ...
    }
});


@RequestMapping(
    value = "/profile/update",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> UpdateUserProfile(
    @RequestBody User usersNewDetails,
    HttpServletRequest request,
    HttpServletResponse response
) {
    // ...
}

I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.

Note: the default content type for ajax is "application/x-www-form-urlencoded".

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

How to know user has clicked "X" or the "Close" button?

I've done something like this.

private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        if ((sender as Form).ActiveControl is Button)
        {
            //CloseButton
        }
        else
        {
            //The X has been clicked
        }
    }

How to print Two-Dimensional Array like table

You could write a method to print a 2d array like this:

//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
    for(int r=0; r<grid.length; r++) {
       for(int c=0; c<grid[r].length; c++)
           System.out.print(grid[r][c] + " ");
       System.out.println();
    }
}

What is the difference between screenX/Y, clientX/Y and pageX/Y?

clientX/Y refers to relative screen coordinates, for instance if your web-page is long enough then clientX/Y gives clicked point's coordinates location in terms of its actual pixel position while ScreenX/Y gives the ordinates in reference to start of page.

Delete directory with files in it?

I do not remember from where I copied this function, but it looks like it is not listed and it is working for me

function rm_rf($path) {
    if (@is_dir($path) && is_writable($path)) {
        $dp = opendir($path);
        while ($ent = readdir($dp)) {
            if ($ent == '.' || $ent == '..') {
                continue;
            }
            $file = $path . DIRECTORY_SEPARATOR . $ent;
            if (@is_dir($file)) {
                rm_rf($file);
            } elseif (is_writable($file)) {
                unlink($file);
            } else {
                echo $file . "is not writable and cannot be removed. Please fix the permission or select a new path.\n";
            }
        }
        closedir($dp);
        return rmdir($path);
    } else {
        return @unlink($path);
    }
}

How to make program go back to the top of the code instead of closing

Use an infinite loop:

while True:
    print('Hello world!')

This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:

def start():
    print ("Welcome to the converter toolkit made by Alan.")

    while True:
        op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

        if op == "1":
            f1 = input ("Please enter your fahrenheit temperature: ")
            f1 = int(f1)

            a1 = (f1 - 32) / 1.8
            a1 = str(a1)

            print (a1+" celsius") 

        elif op == "2":
            m1 = input ("Please input your the amount of meters you wish to convert: ")
            m1 = int(m1)
            m2 = (m1 * 100)

            m2 = str(m2)
            print (m2+" m")

        if op == "3":
            mb1 = input ("Please input the amount of megabytes you want to convert")
            mb1 = int(mb1)
            mb2 = (mb1 / 1024)
            mb3 = (mb2 / 1024)

            mb3 = str(mb3)

            print (mb3+" GB")

        else:
            print ("Sorry, that was an invalid command!")

If you were to add an option to quit as well, that could be:

if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

for example.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

This works to me:

php artisan config:clear
php artisan cache:clear
php artisan config:cache

Thanks.

Error parsing yaml file: mapping values are not allowed here

Incorrect:

people:
  empId: 123
  empName: John
    empDept: IT

Correct:

people:
  emp:
    id: 123
    name: John
    dept: IT

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

How to filter object array based on attributes?

I prefer the Underscore framework. It suggests many useful operations with objects. Your task:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 &
    num_of_beds >=2 & 
    num_of_baths >= 2.5);

can be overwriten like:

var newArray = _.filter (homes, function(home) {
    return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;
});

Hope it will be useful for you!

Reset all changes after last commit in git

First, reset any changes

This will undo any changes you've made to tracked files and restore deleted files:

git reset HEAD --hard

Second, remove new files

This will delete any new files that were added since the last commit:

git clean -fd

Files that are not tracked due to .gitignore are preserved; they will not be removed

Warning: using -x instead of -fd would delete ignored files. You probably don't want to do this.

Display number always with 2 decimal places in <input>

Simply use the number pipe like so :

{{ numberValue | number : '.2-2'}}

The pipe above works as follows :

  • Show at-least 1 integer digit before decimal point, set by default
  • Show not less 2 integer digits after the decimal point
  • Show not more than 2 integer digits after the decimal point

Change tab bar tint color on iOS 7

In "Attributes Inspector" of your Tab Bar Controller within Interface Builder make sure your Bottom Bar is set to Opaque Tab Bar:

Choose Opaque

Now goto your AppDelegate.m file. Find:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

And then add this code between the curly braces to change the colors of both the tab bar buttons and the tab bar background:

///----------------SET TAB BAR COLOR------------------------//

//--------------FOR TAB BAR BUTTON COLOR---------------//
[[UITabBar appearance] setTintColor:[UIColor greenColor]];

//-------------FOR TAB BAR BACKGROUND COLOR------------//
[[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];

What is the meaning of the prefix N in T-SQL statements and when should I use it?

Let me tell you an annoying thing that happened with the N' prefix - I wasn't able to fix it for two days.

My database collation is SQL_Latin1_General_CP1_CI_AS.

It has a table with a column called MyCol1. It is an Nvarchar

This query fails to match Exact Value That Exists.

SELECT TOP 1 * FROM myTable1 WHERE  MyCol1 = 'ESKI'  

// 0 result

using prefix N'' fixes it

SELECT TOP 1 * FROM myTable1 WHERE  MyCol1 = N'ESKI'  

// 1 result - found!!!!

Why? Because latin1_general doesn't have big dotted I that's why it fails I suppose.

Comparing arrays in C#

For .NET 4.0 and higher, you can compare elements in array or tuples using the StructuralComparisons type:

object[] a1 = { "string", 123, true };
object[] a2 = { "string", 123, true };
        
Console.WriteLine (a1 == a2);        // False (because arrays is reference types)
Console.WriteLine (a1.Equals (a2));  // False (because arrays is reference types)
        
IStructuralEquatable se1 = a1;
//Next returns True
Console.WriteLine (se1.Equals (a2, StructuralComparisons.StructuralEqualityComparer)); 

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Java: Detect duplicates in ArrayList?

Simply put: 1) make sure all items are comparable 2) sort the array 2) iterate over the array and find duplicates

Upload files with HTTPWebrequest (multipart/form-data)

This method work for upload multiple image simultaneously

        var flagResult = new viewModel();
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = method;
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();


        string path = @filePath;
        System.IO.DirectoryInfo folderInfo = new DirectoryInfo(path);

        foreach (FileInfo file in folderInfo.GetFiles())
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
        }

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try
        {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
            var result = reader2.ReadToEnd();
            var cList = JsonConvert.DeserializeObject<HttpViewModel>(result);
            if (cList.message=="images uploaded!")
            {
                flagResult.success = true;
            }

        }
        catch (Exception ex)
        {
            //log.Error("Error uploading file", ex);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
        return flagResult;
    }

Java ResultSet how to check if there are any results

you could always do the next up front, and just do a post loop check

if (!resultSet.next() ) {
    System.out.println("no data");
} else {

    do {
     //statement(s)
    } while (resultSet.next());
}

unable to set private key file: './cert.pem' type PEM

I had the same issue, eventually I found a solution that works without splitting the file, by following Petter Ivarrson's answer

My problem was when converting .p12 certificate to .pem. I used:

openssl pkcs12 -in cert.p12 -out cert.pem

This converts and exports all certificates (CA + CLIENT) together with a private key into one file.

The problem was when I tried to verify if the hashes of certificate and key are matching by running:

// Get certificate HASH
openssl x509 -noout -modulus -in cert.pem | openssl md5

// Get private key HASH
openssl rsa -noout -modulus -in cert.pem | openssl md5

This displayed different hashes and that was the reason CURL failed. See here: https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/

I guess that was because all certificates are inside a file (CA + CLIENT) and CURL takes CA certificate instead of CLIENT one. Because CA is first in the list.

So the solution was to export only CLIENT certificate together with private key:

openssl pkcs12 -in cert.p12 -out cert.pem -clcerts
``

Now when I re-run the verification:
```sh
openssl x509 -noout -modulus -in cert.pem | openssl md5
openssl rsa -noout -modulus -in cert.pem | openssl md5

HASHES MATCHED !!!

So I was able to make a curl request by running

curl -ivk --cert ./cert.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

without problems!!!

That being said... I think the best solution is to split the certificates into separate file and use them separately like Petter Ivarsson wrote:

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite.com

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

How to let PHP to create subdomain automatically for each user?

We setup wildcard DNS like they explained above. So the a record is *.yourname.com

Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.

We use the following code:

$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);

This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.

This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).

We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

What's the -practical- difference between a Bare and non-Bare repository?

A bare repository has benefits in

  • reduced disk usage
  • less problems related to remote push (since no working tree is there to get out of synch or have conflicting changes)

How Do I Convert an Integer to a String in Excel VBA?

In my case, the function CString was not found. But adding an empty string to the value works, too.

Dim Test As Integer, Test2 As Variant
Test = 10
Test2 = Test & ""
//Test2 is now "10" not 10

JavaScript Number Split into individual digits

This also works:

_x000D_
_x000D_
var number = 12354987;_x000D_
console.log(String(number).split('').map(Number));
_x000D_
_x000D_
_x000D_

grep without showing path/file:line

No need to find. If you are just looking for a pattern within a specific directory, this should suffice:

grep -hn FOO /your/path/*.bar

Where -h is the parameter to hide the filename, as from man grep:

-h, --no-filename

Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.

Note that you were using

-H, --with-filename

Print the file name for each match. This is the default when there is more than one file to search.

I ran into a merge conflict. How can I abort the merge?

If you end up with merge conflict and doesn't have anything to commit, but still a merge error is being displayed. After applying all the below mentioned commands,

git reset --hard HEAD
git pull --strategy=theirs remote_branch
git fetch origin
git reset --hard origin

Please remove

.git\index.lock

File [cut paste to some other location in case of recovery] and then enter any of below command depending on which version you want.

git reset --hard HEAD
git reset --hard origin

Hope that helps!!!

Shortest way to check for null and assign another value if not

Starting with C# 8.0, you can use the ??= operator to replace the code of the form

if (variable is null)
{
    variable = expression;
}

with the following code:

variable ??= expression;

More information is here

Android canvas draw rectangle

Create a new class MyView, Which extends View. Override the onDraw(Canvas canvas) method to draw rectangle on Canvas.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

 Paint paint;
 Path path;

 public MyView(Context context) {
  super(context);
  init();
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  init();
 }

 private void init(){
  paint = new Paint();
  paint.setColor(Color.BLUE);
  paint.setStrokeWidth(10);
  paint.setStyle(Paint.Style.STROKE);

 }

 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);

  canvas.drawRect(30, 50, 200, 350, paint);
  canvas.drawRect(100, 100, 300, 400, paint);
  //drawRect(left, top, right, bottom, paint)

 }

}

Then Move your Java activity to setContentView() using our custom View, MyView.Call this way.

    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(new MyView(this));
  }

For more details you can visit here

http://developer.android.com/reference/android/graphics/Canvas.html

Casting to string in JavaScript

They do behave differently when the value is null.

  • null.toString() throws an error - Cannot call method 'toString' of null
  • String(null) returns - "null"
  • null + "" also returns - "null"

Very similar behaviour happens if value is undefined (see jbabey's answer).

Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.

How to parse an RSS feed using JavaScript?

I was so exasperated by many misleading articles and answers that I wrote my own RSS reader: https://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how-to-create-a-rss-reader-in-javascript/

You can use AJAX requests to fetch the RSS files but it will work if and only if you use a CORS proxy. I'll try to write my own CORS proxy to give you a more robust solution. In the meantime, it works, I deployed it on my server under Debian Linux.

My solution doesn't use JQuery, I use only plain Javascript standard APIs with no third party libraries and it's supposed to work even with Microsoft Internet Explorer 11.

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Delete last commit in bitbucket

As others have said, usually you want to use hg backout or git revert. However, sometimes you really want to get rid of a commit.

First, you'll want to go to your repository's settings. Click on the Strip commits link.

Strip commits link in bitbucket settings

Enter the changeset ID for the changeset you want to destroy, and click Preview strip. That will let you see what kind of damage you're about to do before you do it. Then just click Confirm and your commit is no longer history. Make sure you tell all your collaborators what you've done, so they don't accidentally push the offending commit back.

How to check the gradle version in Android Studio?

Image shown below. I'm only typing this because of a 30 character minimum imposed by Stackoverflow.

enter image description here

jQuery validation plugin: accept only alphabetical characters?

to allow letters ans spaces

jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");

$('#yourform').validate({
        rules: {
            name_field: {
                lettersonly: true
            }
        }
    });

Convert HH:MM:SS string to seconds only in javascript

You can do this dynamically - in case you encounter not only: HH:mm:ss, but also, mm:ss, or even ss alone.

var str = '12:99:07';
var times = str.split(":");
times.reverse();
var x = times.length, y = 0, z;
for (var i = 0; i < x; i++) {
    z = times[i] * Math.pow(60, i);
    y += z;
}
console.log(y);

Using FileUtils in eclipse

Open the project's properties---> Java Build Path ---> Libraries tab ---> Add External Jars

will allow you to add jars.

You need to download commonsIO from here.

Update MySQL using HTML Form and PHP

First of all use mysqli_connect($dbhost,$dbuser,$dbpass,$dbname)

Second - put mysqli_ everywhere instead of mysql_

Third - use this $sql = "UPDATE anstalld SET mandag = '.$mandag.', tisdag = '.$tisdag.', onsdag = '.$onsdag.', torsdag = '.$torsdag.', fredag = '.$fredag.' WHERE namn = '.$namn.'";
$retval = mysqli_query( $conn, $sql ); //execute your query

if Your data is being updated in your database but not in your table its because when you will click on update button, the request is made to the same file. It first selects the data from the database when it is not updated prints it in the table and then update it according to the flow. If you have to update it as you click on update button then put this section

<?php
if(isset($_POST['update']))
{

$namn = $_POST['namnid'];
$mandag = $_POST['mandagid'];
$tisdag = $_POST['tisdagid'];
$onsdag = $_POST['onsdagid'];
$torsdag = $_POST['torsdagid'];
$fredag = $_POST['fredagid'];

$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";

}


?>`

after connecting with database.