Programs & Examples On #Pixel shading

Linq with group by having count

Below solution may help you.

var unmanagedDownloadcountwithfilter = from count in unmanagedDownloadCount.Where(d =>d.downloaddate >= startDate && d.downloaddate <= endDate)
group count by count.unmanagedassetregistryid into grouped
where grouped.Count() > request.Download
select new
{
   UnmanagedAssetRegistryID = grouped.Key,
   Count = grouped.Count()
};

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

error: Unable to find vcvarsall.bat

I spent almost 2 days figuring out how to fix this problem in my python 3.4 64 bit version: Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32

Solution 1, hard: (before reading this, read first Solution 2 below) Finally, this is what helped me:

  1. install Visual C++ 2010 Express
  2. install Microsoft Windows SDK v7.1 for Windows 7
  3. create manually file vcvars64.bat in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 which contains CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64 or other path depending on where you have yours installed
  4. (this seems to be optional) install Microsoft Visual Studio 2010 Service Pack 1 together with Microsoft Visual C++ 2010 Service Pack 1 Compiler Update for the Windows SDK 7.1
  5. after that I tried to pip install numpy but received the following error:

    File "numpy\core\setup.py", line 686, in get_mathlib_info
    raise RuntimeError("Broken toolchain: cannot link a simple C program")
    RuntimeError: Broken toolchain: cannot link a simple C program
    

    I changed mfinfo to None in C:\Python34\Lib\distutils\msvc9compiler.py per this https://stackoverflow.com/a/23099820/4383472

  6. finally after pip install numpy command my avast antivirus tried to interfere into the installation process, but i quickly disabled it

It took very long - several minutes for numpy to compile, I even thought that there was an error, but finally everything was ok.

Solution 2, easy: (I know this approach has already been mentioned in a highly voted answer, but let me repeat since it really is easier) After going through all of this work I understood that the best way for me is just to use already precompiled binaries from http://www.lfd.uci.edu/~gohlke/pythonlibs/ in future. There is very small chance that I will ever need some package (or a version of a package) which this site doesn't contain. The installation process is also much quicker this way. For example, to install numpy:

  1. donwload numpy-1.9.2+mkl-cp34-none-win_amd64.whl (if you have Python 3.4 64-bit) from that site
  2. in command prompt or powershell install it with pip pip install numpy-1.9.2+mkl-cp34-none-win_amd64.whl (or full path to the file depending how command prompt is opened)

How do I configure Notepad++ to use spaces instead of tabs?

I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default] ? Replace by space:

NotePad++ Preferences

NotePad++ Tab Settings

How to set the JSTL variable value in javascript?

This variable can be set using value="${val1}" inside c:set if you have used jquery in your system.

add scroll bar to table body

This is because you are adding your <tbody> tag before <td> in table you cannot print any data without <td>.

So for that you have to make a <div> say #header with position: fixed;

 header
 {
      position: fixed;
 }

make another <div> which will act as <tbody>

tbody
{
    overflow:scroll;
}

Now your header is fixed and the body will scroll. And the header will remain there.

How to open up a form from another form in VB.NET?

You can also use showdialog

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                      Handles Button3.Click

     dim mydialogbox as new aboutbox1
     aboutbox1.showdialog()

End Sub

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.4</version>

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

How to Set Active Tab in jQuery Ui

Simple jQuery solution - find the <a> element where href="x" and click it:

$('a[href="#tabs-2"]').click();

Retrieve column names from java.sql.ResultSet

If you want to use spring jdbctemplate and don't want to deal with connection staff, you can use following:

jdbcTemplate.query("select * from books", new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            ResultSetMetaData rsmd = resultSet.getMetaData();
            for (int i = 1; i <= rsmd.getColumnCount(); i++ ) {
                String name = rsmd.getColumnName(i);
                // Do stuff with name
            }
        }
    });

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

How to calculate the median of an array?

I faced a similar problem yesterday. I wrote a method with Java generics in order to calculate the median value of every collection of Numbers; you can apply my method to collections of Doubles, Integers, Floats and returns a double. Please consider that my method creates another collection in order to not alter the original one. I provide also a test, have fun. ;-)

public static <T extends Number & Comparable<T>> double median(Collection<T> numbers){
    if(numbers.isEmpty()){
        throw new IllegalArgumentException("Cannot compute median on empty collection of numbers");
    }
    List<T> numbersList = new ArrayList<>(numbers);
    Collections.sort(numbersList);
    int middle = numbersList.size()/2;
    if(numbersList.size() % 2 == 0){
        return 0.5 * (numbersList.get(middle).doubleValue() + numbersList.get(middle-1).doubleValue());
    } else {
        return numbersList.get(middle).doubleValue();
    }

}

JUnit test code snippet:

/**
 * Test of median method, of class Utils.
 */
@Test
public void testMedian() {
    System.out.println("median");
    Double expResult = 3.0;
    Double result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,13.0));
    assertEquals(expResult, result);
    expResult = 3.5;
    result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,4.0,13.0));
    assertEquals(expResult, result);
}

Usage example (consider the class name is Utils):

List<Integer> intValues = ... //omitted init
Set<Float> floatValues = ... //omitted init
.....
double intListMedian = Utils.median(intValues);
double floatSetMedian = Utils.median(floatValues);

Note: my method works on collections, you can convert arrays of numbers to list of numbers as pointed here

How can I use UserDefaults in Swift?

I saved NSDictionary normally and able to get it correctly.

 dictForaddress = placemark.addressDictionary! as NSDictionary
        let userDefaults = UserDefaults.standard
        userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)

// For getting data from NSDictionary.

let userDefaults = UserDefaults.standard
    let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary

Regex for not empty and not whitespace

/^[\s]*$/ matches empty strings and strings containing whitespaces only

'POCO' definition

I may be wrong about this.. but anyways, I think POCO is Plain Old Class CLR Object and it comes from POJO plain old Java Object. A POCO is a class that holds data and has no behaviours.

Here is an example written in C#:

class Fruit 
{
    public Fruit() { }

    public Fruit(string name, double weight, int quantity) 
    {
        Name = name;
        Weight = weight;
        Quantity = quantity;
    }

    public string Name { get; set; }
    public double Weight { get; set; }
    public int Quantity { get; set; }

    public override string ToString() 
    {
        return $"{Name.ToUpper()} ({Weight}oz): {Quantity}";
    }
}

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Extend the DOM Element, Handle the Error, and Degrade Gracefully

Below I use the prototype function to wrap the native DOM play function, grab its promise, and then degrade to a play button if the browser throws an exception. This extension addresses the shortcoming of the browser and is plug-n-play in any page with knowledge of the target element(s).

// JavaScript
// Wrap the native DOM audio element play function and handle any autoplay errors
Audio.prototype.play = (function(play) {
return function () {
  var audio = this,
      args = arguments,
      promise = play.apply(audio, args);
  if (promise !== undefined) {
    promise.catch(_ => {
      // Autoplay was prevented. This is optional, but add a button to start playing.
      var el = document.createElement("button");
      el.innerHTML = "Play";
      el.addEventListener("click", function(){play.apply(audio, args);});
      this.parentNode.insertBefore(el, this.nextSibling)
    });
  }
};
})(Audio.prototype.play);

// Try automatically playing our audio via script. This would normally trigger and error.
document.getElementById('MyAudioElement').play()

<!-- HTML -->
<audio id="MyAudioElement" autoplay>
  <source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
  <source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

Daemon Threads Explanation

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:

  1. Connect to the mail server and ask how many unread messages you have.
  2. Signal the GUI with the updated count.
  3. Sleep for a little while.

When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

In my case, setting the 'Gradle version' same as the 'Android Plugin version' under File->Project Structure->Project fixed the issue for me.

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

How to convert numpy arrays to standard TensorFlow format?

You can use tf.pack (tf.stack in TensorFlow 1.0.0) method for this purpose. Here is how to pack a random image of type numpy.ndarray into a Tensor:

import numpy as np
import tensorflow as tf
random_image = np.random.randint(0,256, (300,400,3))
random_image_tensor = tf.pack(random_image)
tf.InteractiveSession()
evaluated_tensor = random_image_tensor.eval()

UPDATE: to convert a Python object to a Tensor you can use tf.convert_to_tensor function.

python JSON only get keys in first level

Just do a simple .keys()

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

If you need a sorted list:

keylist = dct.keys()
keylist.sort()

How to parse JSON data with jQuery / JavaScript?

Setting dataType:'json' will parse JSON for you:

$.ajax({
  type: 'GET',
  url: 'http://example/functions.php',
  data: {get_param: 'value'},
  dataType: 'json',
  success: function (data) {
    var names = data
    $('#cand').html(data);
  }
});

Or else you can use parseJSON:

var parsedJson = $.parseJSON(jsonToBeParsed);

Then you can iterate the following:

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

...by using $().each:

var json = $.parseJSON(j);
$(json).each(function (i, val) {
  $.each(val, function (k, v) {
    console.log(k + " : " + v);
  });
}); 

JSFiddle

How to read response headers in angularjs?

Use the headers variable in success and error callbacks

From documentation.

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  })
  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

If you are on the same domain, you should be able to retrieve the response headers back. If cross-domain, you will need to add Access-Control-Expose-Headers header on the server.

Access-Control-Expose-Headers: content-type, cache, ...

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

I faced a similar issue while copying a sheet to another workbook. I prefer to avoid using 'activesheet' though as it has caused me issues in the past. Hence I wrote a function to perform this inline with my needs. I add it here for those who arrive via google as I did:

The main issue here is that copying a visible sheet to the last index position results in Excel repositioning the sheet to the end of the visible sheets. Hence copying the sheet to the position after the last visible sheet sorts this issue. Even if you are copying hidden sheets.

Function Copy_WS_to_NewWB(WB As Workbook, WS As Worksheet) As Worksheet
    'Creates a copy of the specified worksheet in the specified workbook
    '   Accomodates the fact that there may be hidden sheets in the workbook
    
    Dim WSInd As Integer: WSInd = 1
    Dim CWS As Worksheet
    
    'Determine the index of the last visible worksheet
    For Each CWS In WB.Worksheets
        If CWS.Visible Then If CWS.Index > WSInd Then WSInd = CWS.Index
    Next CWS
    
    WS.Copy after:=WB.Worksheets(WSInd)
    Set Copy_WS_to_NewWB = WB.Worksheets(WSInd + 1)

End Function

To use this function for the original question (ie in the same workbook) could be done with something like...

Set test = Copy_WS_to_NewWB(Workbooks(1), Workbooks(1).Worksheets(1))
test.name = "test sheet name"

EDIT 04/11/2020 from –user3598756 Adding a slight refactoring of the above code

Function CopySheetToWorkBook(targetWb As Workbook, shToBeCopied As Worksheet, copiedSh As Worksheet) As Boolean
    'Creates a copy of the specified worksheet in the specified workbook
    '   Accomodates the fact that there may be hidden sheets in the workbook

    Dim lastVisibleShIndex As Long
    Dim iSh As Long

    On Error GoTo SafeExit
    
    With targetWb
        'Determine the index of the last visible worksheet
        For iSh = .Sheets.Count To 1 Step -1
            If .Sheets(iSh).Visible Then
                lastVisibleShIndex = iSh
                Exit For
            End If
        Next
    
        shToBeCopied.Copy after:=.Sheets(lastVisibleShIndex)
        Set copiedSh = .Sheets(lastVisibleShIndex + 1)
    End With
    
    CopySheetToWorkBook = True
    Exit Function
    
SafeExit:
    
End Function

other than using different (more descriptive?) variable names, the refactoring manily deals with:

  1. turning the Function type into a `Boolean while including returned (copied) worksheet within function parameters list this, to let the calling Sub hande possible errors, like

     Dim WB as Workbook: Set WB = ThisWorkbook ' as an example
     Dim sh as Worksheet: Set sh = ActiveSheet ' as an example
     Dim copiedSh as Worksheet
     If CopySheetToWorkBook(WB, sh, copiedSh) Then
         ' go on with your copiedSh sheet
     Else
         Msgbox "Error while trying to copy '" & sh.Name & "'" & vbcrlf & err.Description
     End If
    
  2. having the For - Next loop stepping from last sheet index backwards and exiting at first visible sheet occurence, since we're after the "last" visible one

Uncaught TypeError: Cannot set property 'onclick' of null

"blue_box" is null -- are you positive whatever it is with "id='blue'" exists when this is being run?

try console.log(document.getElementById("blue")) in chrome or FF with firebug. Your script might be running before the 'blue' element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload).

Easily measure elapsed time

In answer to OP's three specific questions.

"What I don't understand is why the values in the before and after are the same?"

The first question and sample code shows that time() has a resolution of 1 second, so the answer has to be that the two functions execute in less than 1 second. But occasionally it will (apparently illogically) inform 1 second if the two timer marks straddle a one second boundary.

The next example uses gettimeofday() which fills this struct

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

and the second question asks: "How do I read a result of **time taken = 0 26339? Does that mean 26,339 nanoseconds = 26.3 msec?"

My second answer is the time taken is 0 seconds and 26339 microseconds, that is 0.026339 seconds, which bears out the first example executing in less than 1 second.

The third question asks: "What about **time taken = 4 45025, does that mean 4 seconds and 25 msec?"

My third answer is the time taken is 4 seconds and 45025 microseconds, that is 4.045025 seconds, which shows that OP has altered the tasks performed by the two functions which he previously timed.

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The solution for me is to install this VB6 patch. I'm on Server2008 (32-bit).

http://www.microsoft.com/en-us/download/details.aspx?id=10019

It makes me sad that we're still talking about this in 2014... but here it is. :)


From puetzk's comment: These are outdated: you want to be using Microsoft Visual Basic 6.0 Service Pack 6 Cumulative Update (kb957924).

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

base64 encoded images in email signatures

The image should be embedded in the message as an attachment like this:

--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png

base64 data

--boundary

And, the HTML part would reference the image like this:

<img src="cid:0123456789">

In some clients, src="sig.png" will work too.

You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.

Clients shouldn't block this image either as it isn't remote.

Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):

From 
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"

This is a message with multiple parts in MIME format.

--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

test

-- 
[Picture of a Christmas Tree]

--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"

--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <p>test</p>
        <p class="sig">-- <br><img src="cid:0123456789"></p>
    </body>
</html>

--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64

R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7

--related_boundary--

--alternative_boundary--

You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.

Can "git pull --all" update all my local branches?

The script from @larsmans, a bit improved:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git rebase "origin/$branch" || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git rebase "origin/$CURRENT" || exit 1

This, after it finishes, leaves working copy checked out from the same branch as it was before the script was called.

The git pull version:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git pull || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git pull || exit 1

Difference between java.lang.RuntimeException and java.lang.Exception

  1. User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.

  2. User-defined Exception can be Custom Checked Exception, if it is extending to Exception class

  3. User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.

  4. Define a class and make it a child to Exception or Run time Exception

Getting a directory name from a filename

There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH (260) characters.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

what is the multicast doing on 224.0.0.251?

I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone

How to initialize a nested struct?

You can define a struct and create its object in another struct like i have done below:

package main

import "fmt"

type Address struct {
    streetNumber int
    streetName   string
    zipCode      int
}

type Person struct {
    name    string
    age     int
    address Address
}

func main() {
    var p Person
    p.name = "Vipin"
    p.age = 30
    p.address = Address{
        streetName:   "Krishna Pura",
        streetNumber: 14,
        zipCode:      475110,
    }
    fmt.Println("Name: ", p.name)
    fmt.Println("Age: ", p.age)
    fmt.Println("StreetName: ", p.address.streetName)
    fmt.Println("StreeNumber: ", p.address.streetNumber)
}

Hope it helped you :)

Altering a column to be nullable

In PostgresQL it is:

ALTER TABLE tableName ALTER COLUMN columnName DROP NOT NULL;

Oracle SQL Query for listing all Schemas in a DB

Using sqlplus

sqlplus / as sysdba

run:

SELECT * 
FROM dba_users

Should you only want the usernames do the following:

SELECT username 
FROM dba_users

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.

When clicking Button1 on the UserControl, i'll fire Button1_Click which triggers UserControl_ButtonClick on the form:

User control:

[Browsable(true)] [Category("Action")] 
[Description("Invoked when user clicks button")]
public event EventHandler ButtonClick;

protected void Button1_Click(object sender, EventArgs e)
{
    //bubble the event up to the parent
    if (this.ButtonClick!= null)
        this.ButtonClick(this, e);               
}

Form:

UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);

protected void UserControl_ButtonClick(object sender, EventArgs e)
{
    //handle the event 
}

Notes:

  • Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e); you can use ButtonClick?.Invoke(this, e);, which does essentially the same, but is shorter.

  • The Browsable attribute makes the event visible in Visual Studio's designer (events view), Category shows it in the "Action" category, and Description provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.

NVIDIA NVML Driver/library version mismatch

This also happened to me on Ubuntu 16.04 using the nvidia-348 package (latest nvidia version on Ubuntu 16.04).

However I could resolve the problem by installing nvidia-390 through the Proprietary GPU Drivers PPA.

So a solution to the described problem on Ubuntu 16.04 is doing this:

  • sudo add-apt-repository ppa:graphics-drivers/ppa
  • sudo apt-get update
  • sudo apt-get install nvidia-390

Note: This guide assumes a clean Ubuntu install. If you have previous drivers installed a reboot migh be needed to reload all the kernel modules.

Git Ignores and Maven targets

The .gitignore file in the root directory does apply to all subdirectories. Mine looks like this:

.classpath
.project
.settings/
target/

This is in a multi-module maven project. All the submodules are imported as individual eclipse projects using m2eclipse. I have no further .gitignore files. Indeed, if you look in the gitignore man page:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory

So this should work for you.

A failure occurred while executing com.android.build.gradle.internal.tasks

Working on android studio: 3.6.3 and gradle version:

classpath 'com.android.tools.build:gradle:3.6.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"

Adding this line in

gradle.properties file

org.gradle.jvmargs=-Xmx512m

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Make sure that each Application Pool in IIS, under Advanced Settings has Enable 32 bit Applications set to True

IIS screenshot

How to add/update an attribute to an HTML element using JavaScript?

What do you want to do with the attribute? Is it an html attribute or something of your own?

Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

How to call another controller Action From a controller in Mvc

If anyone is looking at how to do this in .net core I accomplished it by adding the controller in startup

services.AddTransient<MyControllerIwantToInject>();

Then Injecting it into the other controller

public class controllerBeingInjectedInto : ControllerBase
{
    private readonly MyControllerIwantToInject _myControllerIwantToInject

     public controllerBeingInjectedInto(MyControllerIwantToInject myControllerIwantToInject)
{
       _myControllerIwantToInject = myControllerIwantToInject;
      }

Then just call it like so _myControllerIwantToInject.MyMethodINeed();

Angular ForEach in Angular4/Typescript?

you can try typescript's For :

selectChildren(data , $event){
   let parentChecked : boolean = data.checked;
   for(let o of this.hierarchicalData){
      for(let child of o){
         child.checked = parentChecked;
      }
   }
}

Java - sending HTTP parameters via POST method easily

Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:

import java.io.*;
import java.net.*;
import java.util.*;

class Test {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.net/new-message.php");
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("name", "Freddie the Fish");
        params.put("email", "[email protected]");
        params.put("reply_to_thread", 10394);
        params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)
            System.out.print((char)c);
    }
}

If you want the result as a String instead of directly printed out do:

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0;)
            sb.append((char)c);
        String response = sb.toString();

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

Limit text length to n lines using CSS

Working Cross-browser Solution

This problem has been plaguing us all for years.

To help in all cases, I have laid out the CSS only approach, and a jQuery approach in case the css caveats are a problem.

Here's a CSS only solution I came up with that works in all circumstances, with a few minor caveats.

The basics are simple, it hides the overflow of the span, and sets the max height based on the line height as suggested by Eugene Xa.

Then there is a pseudo class after the containing div that places the ellipsis nicely.

Caveats

This solution will always place the ellipsis, regardless if there is need for it.

If the last line ends with an ending sentence, you will end up with four dots....

You will need to be happy with justified text alignment.

The ellipsis will be to the right of the text, which can look sloppy.

Code + Snippet

jsfiddle

_x000D_
_x000D_
.text {_x000D_
  position: relative;_x000D_
  font-size: 14px;_x000D_
  color: black;_x000D_
  width: 250px; /* Could be anything you like. */_x000D_
}_x000D_
_x000D_
.text-concat {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  word-wrap: break-word;_x000D_
  overflow: hidden;_x000D_
  max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */_x000D_
  line-height: 1.2em;_x000D_
  text-align:justify;_x000D_
}_x000D_
_x000D_
.text.ellipsis::after {_x000D_
  content: "...";_x000D_
  position: absolute;_x000D_
  right: -12px; _x000D_
  bottom: 4px;_x000D_
}_x000D_
_x000D_
/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
_x000D_
<div class="text ellipsis">_x000D_
  <span class="text-concat">_x000D_
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in._x000D_
_x000D_
Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri._x000D_
  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery Approach

In my opinion this is the best solution, but not everyone can use JS. Basically, the jQuery will check any .text element, and if there are more chars than the preset max var, it will cut the rest off and add an ellipsis.

There are no caveats to this approach, however this code example is meant only to demonstrate the basic idea - I wouldn't use this in production without improving on it for a two reasons:

1) It will rewrite the inner html of .text elems. whether needed or not. 2) It does no test to check that the inner html has no nested elems - so you are relying a lot on the author to use the .text correctly.

Edited

Thanks for the catch @markzzz

Code & Snippet

jsfiddle

_x000D_
_x000D_
setTimeout(function()_x000D_
{_x000D_
 var max = 200;_x000D_
  var tot, str;_x000D_
  $('.text').each(function() {_x000D_
   str = String($(this).html());_x000D_
   tot = str.length;_x000D_
    str = (tot <= max)_x000D_
     ? str_x000D_
      : str.substring(0,(max + 1))+"...";_x000D_
    $(this).html(str);_x000D_
  });_x000D_
},500); // Delayed for example only.
_x000D_
.text {_x000D_
  position: relative;_x000D_
  font-size: 14px;_x000D_
  color: black;_x000D_
  font-family: sans-serif;_x000D_
  width: 250px; /* Could be anything you like. */_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p class="text">_x000D_
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young._x000D_
</p>_x000D_
_x000D_
<p class="text">_x000D_
Old men tend to forget what thought was like in their youth;_x000D_
</p>_x000D_
 <!-- Working Cross-browser Solution_x000D_
_x000D_
This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->
_x000D_
_x000D_
_x000D_

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

Jenkins / Hudson environment variables

Couldn't you just add it as an environment variable in Jenkins settings:

Manage Jenkins -> Global properties > Environment variables: And then click "Add" to add a property PATH and its value to what you need.

Method with a bool return

private bool CheckAll()
{
    if ( ....)
    {
        return true;
    }

    return false;
}

When the if-condition is false the method doesn't know what value should be returned (you probably get an error like "not all paths return a value").

As CQQL pointed out if you mean to return true when your if-condition is true you could have simply written:

private bool CheckAll()
{
    return (your_condition);
}

If you have side effects, and you want to handle them before you return, the first (long) version would be required.

"git pull" or "git merge" between master and development branches

If you are not sharing develop branch with anybody, then I would just rebase it every time master updated, that way you will not have merge commits all over your history once you will merge develop back into master. Workflow in this case would be as follows:

> git clone git://<remote_repo_path>/ <local_repo>
> cd <local_repo>
> git checkout -b develop
....do a lot of work on develop
....do all the commits
> git pull origin master
> git rebase master develop

Above steps will ensure that your develop branch will be always on top of the latest changes from the master branch. Once you are done with develop branch and it's rebased to the latest changes on master you can just merge it back:

> git checkout -b master
> git merge develop
> git branch -d develop

How to take off line numbers in Vi?

If you are talking about show line number command in vi/vim

you could use

set nu

in commandline mode to turn on and

set nonu

will turn off the line number display or

set nu!

to toggle off display of line numbers

Converting Integer to String with comma for thousands

This is a way that also able you to replace default separator with any characters:

val myNumber = NumberFormat.getNumberInstance(Locale.US)
   .format(123456789)
   .replace(",", "?")

jQuery if statement, syntax

To add to what the others are saying, A and B can be function calls as well that return boolean values. If A returns false then B would never be called.

if (A() && B()) {
    // if A() returns false then B() is never called...
}

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

How do I integrate Ajax with Django applications?

When we use Django:

Server ===> Client(Browser)   
      Send a page

When you click button and send the form,
----------------------------
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      Send a page after doing sth with these data
----------------------------

If you want to keep old data, you can do it without Ajax. (Page will be refreshed)

Server ===> Client(Browser)   
      Send a page
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      1. Send a page after doing sth with data
      2. Insert data into form and make it like before. 
      After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.

Or you can do with Ajax (Page will be not refreshed)

--------------------------
<Initialization> 
Server ===> Client(Browser) [from URL1]    
      Give a page                      
--------------------------  
<Communication>
Server <=== Client(Browser)     
      Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2] 
      Give a data struct(such as JSON)
---------------------------------

If you use Ajax, you must do these:

  1. Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
  2. Use Ajax to communicate with server using URL2. And then server send client a data struct.

Django is different from Ajax. The reason for this is as follows:

  • The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct.
  • Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.

In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.

If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.

(My English is not good)

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Java 8 Streams: multiple filters vs. complex condition

This is the result of the 6 different combinations of the sample test shared by @Hank D It's evident that predicate of form u -> exp1 && exp2 is highly performant in all the cases.

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=3372, min=31, average=33.720000, max=47}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9150, min=85, average=91.500000, max=118}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9046, min=81, average=90.460000, max=150}

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8336, min=77, average=83.360000, max=189}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9094, min=84, average=90.940000, max=176}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10501, min=99, average=105.010000, max=136}

two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=11117, min=98, average=111.170000, max=238}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8346, min=77, average=83.460000, max=113}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9089, min=81, average=90.890000, max=137}

two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10434, min=98, average=104.340000, max=132}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9113, min=81, average=91.130000, max=179}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8258, min=77, average=82.580000, max=100}

one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9131, min=81, average=91.310000, max=139}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10265, min=97, average=102.650000, max=131}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8442, min=77, average=84.420000, max=156}

one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8553, min=81, average=85.530000, max=125}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8219, min=77, average=82.190000, max=142}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10305, min=97, average=103.050000, max=132}

Functional programming vs Object Oriented programming

When do you choose functional programming over object oriented?

When you anticipate a different kind of software evolution:

  • Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things. This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.

  • Functional languages are good when you have a fixed set of things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.

When evolution goes the wrong way, you have problems:

  • Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.

  • Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem". Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.

What are the typical problem definitions where functional programming is a better choice?

Functional languages excel at manipulating symbolic data in tree form. A favorite example is compilers, where source and intermediate languages change seldom (mostly the same things), but compiler writers are always adding new translations and code improvements or optimizations (new operations on things). Compilation and translation more generally are "killer apps" for functional languages.

How can I convert string to double in C++?

See C++ FAQ Lite How do I convert a std::string to a number?

See C++ Super-FAQ How do I convert a std::string to a number?

Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.

 // the requested function
 #include <sstream>
 double string_to_double( const std::string& s )
 {
   std::istringstream i(s);
   double x;
   if (!(i >> x))
     return 0;
   return x;
 } 

 // some tests
 #include <cassert>
 int main( int, char** )
 {
    // simple case:
    assert( 0.5 == string_to_double( "0.5"    ) );

    // blank space:
    assert( 0.5 == string_to_double( "0.5 "   ) );
    assert( 0.5 == string_to_double( " 0.5"   ) );

    // trailing non digit characters:
    assert( 0.5 == string_to_double( "0.5a"   ) );

    // note that with your requirements you can't distinguish
    // all the the allowed string representation of zero from
    // the non numerical strings:
    assert( 0 == string_to_double( "0"       ) );
    assert( 0 == string_to_double( "0."      ) );
    assert( 0 == string_to_double( "0.0"     ) );
    assert( 0 == string_to_double( "0.00"    ) );
    assert( 0 == string_to_double( "0.0e0"   ) );
    assert( 0 == string_to_double( "0.0e-0"  ) );
    assert( 0 == string_to_double( "0.0e+0"  ) );
    assert( 0 == string_to_double( "+0"      ) );
    assert( 0 == string_to_double( "+0."     ) );
    assert( 0 == string_to_double( "+0.0"    ) );
    assert( 0 == string_to_double( "+0.00"   ) );
    assert( 0 == string_to_double( "+0.0e0"  ) );
    assert( 0 == string_to_double( "+0.0e-0" ) );
    assert( 0 == string_to_double( "+0.0e+0" ) );
    assert( 0 == string_to_double( "-0"      ) );
    assert( 0 == string_to_double( "-0."     ) );
    assert( 0 == string_to_double( "-0.0"    ) );
    assert( 0 == string_to_double( "-0.00"   ) );
    assert( 0 == string_to_double( "-0.0e0"  ) );
    assert( 0 == string_to_double( "-0.0e-0" ) );
    assert( 0 == string_to_double( "-0.0e+0" ) );
    assert( 0 == string_to_double( "foobar"  ) );
    return 0;
 }

Min and max value of input in angular4 application

If you are looking to validate length use minLength and maxLength instead.

indexOf Case Sensitive?

I've just looked at the source. It compares chars so it is case sensitive.

Difference between staticmethod and classmethod

A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() during compilation (which happens prior to any code execution when you run a script).

For the sake of code readability I'd avoid @staticmethod unless your method will be used for loads of work, where the nanoseconds count.

Python Prime number checker

The two main problems with your code are:

  1. After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
  2. You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.

A couple pretty significant inefficiencies:

  1. You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
  2. You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.

console.log showing contents of array object

It's simple to print an object to console in Javascript. Just use the following syntax:

console.log( object );

or

console.log('object: %O', object );

A relatively unknown method is following which prints an object or array to the console as table:

console.table( object );

I think it is important to say that this kind of logging statement only works inside a browser environment. I used this with Google Chrome. You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'. Select tab 'Console'.

Java 8 lambda Void argument

Just for reference which functional interface can be used for method reference in cases method throws and/or returns a value.

void notReturnsNotThrows() {};
void notReturnsThrows() throws Exception {}
String returnsNotThrows() { return ""; }
String returnsThrows() throws Exception { return ""; }

{
    Runnable r1 = this::notReturnsNotThrows; //ok
    Runnable r2 = this::notReturnsThrows; //error
    Runnable r3 = this::returnsNotThrows; //ok
    Runnable r4 = this::returnsThrows; //error

    Callable c1 = this::notReturnsNotThrows; //error
    Callable c2 = this::notReturnsThrows; //error
    Callable c3 = this::returnsNotThrows; //ok
    Callable c4 = this::returnsThrows; //ok

}


interface VoidCallableExtendsCallable extends Callable<Void> {
    @Override
    Void call() throws Exception;
}

interface VoidCallable {
    void call() throws Exception;
}

{
    VoidCallableExtendsCallable vcec1 = this::notReturnsNotThrows; //error
    VoidCallableExtendsCallable vcec2 = this::notReturnsThrows; //error
    VoidCallableExtendsCallable vcec3 = this::returnsNotThrows; //error
    VoidCallableExtendsCallable vcec4 = this::returnsThrows; //error

    VoidCallable vc1 = this::notReturnsNotThrows; //ok
    VoidCallable vc2 = this::notReturnsThrows; //ok
    VoidCallable vc3 = this::returnsNotThrows; //ok
    VoidCallable vc4 = this::returnsThrows; //ok
}

Convert/cast an stdClass object to another class

To move all existing properties of a stdClass to a new object of a specified class name:

/**
 * recast stdClass object to an object with type
 *
 * @param string $className
 * @param stdClass $object
 * @throws InvalidArgumentException
 * @return mixed new, typed object
 */
function recast($className, stdClass &$object)
{
    if (!class_exists($className))
        throw new InvalidArgumentException(sprintf('Inexistant class %s.', $className));

    $new = new $className();

    foreach($object as $property => &$value)
    {
        $new->$property = &$value;
        unset($object->$property);
    }
    unset($value);
    $object = (unset) $object;
    return $new;
}

Usage:

$array = array('h','n');

$obj=new stdClass;
$obj->action='auth';
$obj->params= &$array;
$obj->authKey=md5('i');

class RestQuery{
    public $action;
    public $params=array();
    public $authKey='';
}

$restQuery = recast('RestQuery', $obj);

var_dump($restQuery, $obj);

Output:

object(RestQuery)#2 (3) {
  ["action"]=>
  string(4) "auth"
  ["params"]=>
  &array(2) {
    [0]=>
    string(1) "h"
    [1]=>
    string(1) "n"
  }
  ["authKey"]=>
  string(32) "865c0c0b4ab0e063e5caa3387c1a8741"
}
NULL

This is limited because of the new operator as it is unknown which parameters it would need. For your case probably fitting.

Date Comparison using Java

You are probably looking for:

!toDate.before(currentDate)

before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.

JavaFX and OpenJDK

JavaFX is part of OpenJDK

The JavaFX project itself is open source and is part of the OpenJDK project.

Update Dec 2019

For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).

The open source code repository for JavaFX is at https://github.com/openjdk/jfx.

At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).

The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main

If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.

For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).


Older information which may become outdated over time

Building JavaFX from the OpenJDK repository

You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.

Update: Using a JavaFX distribution pre-built from OpenJDK sources

As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:

(currently this only works for Java 8 as far as I know).

Differences between Open JDK and Oracle JDK with respect to JavaFX

The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.

Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.

  1. The ON2 VP6 video codec, which is owned by Google and Google has not open sourced.
  2. The Oracle WebStart/Browser Embedded application deployment technology.

This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.

Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).

The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.

It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.

Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).

Update Dec, 2019:

An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.

Who needs to create Linux OpenJDK Distributions which include JavaFX

It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.

Update, Dec 2019:

Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.

If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.

Advice on Deployment for Substantial Applications

I advise using Java's self-contained application deployment mode.

A description of this deployment mode is:

Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.

You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.

As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).

Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.

Update, April 2018: Information on Oracle's current policy towards future developments

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

The normal usage of static is to access the function directly with out any object creation. Same as in java main we could not create any object for that class to invoke the main method. It will execute automatically. If we want to execute manually we can call by using main() inside the class and ClassName.main from outside the class.

How to Display Selected Item in Bootstrap Button Dropdown Title

This one works on more than one dropdown in the same page. Furthermore, I added caret on selected item:

    $(".dropdown-menu").on('click', 'li a', function(){
        $(this).parent().parent().siblings(".btn:first-child").html($(this).text()+' <span class="caret"></span>');
        $(this).parent().parent().siblings(".btn:first-child").val($(this).text());
    });

Android Studio - Importing external Library/Jar

"simple solution is here"

1 .Create a folder named libs under the app directory for that matter any directory within the project..

2 .Copy Paste your Library to libs folder

3.You simply copy the JAR to your libs/ directory and then from inside Android Studio, right click the Jar that shows up under libs/ > Add As Library..

Peace!

How to get all of the immediate subdirectories in Python

def get_folders_in_directories_recursively(directory, index=0):
    folder_list = list()
    parent_directory = directory

    for path, subdirs, _ in os.walk(directory):
        if not index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)
        elif path[len(parent_directory):].count('/') + 1 == index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)

    return folder_list

The following function can be called as:

get_folders_in_directories_recursively(directory, index=1) -> gives the list of folders in first level

get_folders_in_directories_recursively(directory) -> gives all the sub folders

Formula px to dp, dp to px android

DisplayMetrics displayMetrics = contaxt.getResources()
            .getDisplayMetrics();

    int densityDpi = (int) (displayMetrics.density * 160f);
    int ratio = (densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    int px;
    if (ratio == 0) {
        px = dp;
    } else {
        px = Math.round(dp * ratio);

    }

How to bundle vendor scripts separately and require them as needed with Webpack?

Also not sure if I fully understand your case, but here is config snippet to create separate vendor chunks for each of your bundles:

entry: {
  bundle1: './build/bundles/bundle1.js',
  bundle2: './build/bundles/bundle2.js',
  'vendor-bundle1': [
    'react',
    'react-router'
  ],
  'vendor-bundle2': [
    'react',
    'react-router',
    'flummox',
    'immutable'
  ]
},

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle1',
    chunks: ['bundle1'],
    filename: 'vendor-bundle1.js',
    minChunks: Infinity
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle2',
    chunks: ['bundle2'],
    filename: 'vendor-bundle2-whatever.js',
    minChunks: Infinity
  }),
]

And link to CommonsChunkPlugin docs: http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

"ImportError: No module named" when trying to run Python script

The main reason is the sys.paths of Python and IPython are different.

Please refer to lucypark link, the solution works in my case. It happen when install opencv by

conda install opencv

And got import error in iPython, There are three steps to solve this issue:

import cv2
ImportError: ...

1. Check path in Python and iPython with following command

import sys
sys.path

You will find different result from Python and Jupyter. Second step, just use sys.path.append to fix the missed path by try-and-error.

2. Temporary solution

In iPython:

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

the ImportError:.. issue solved

3. Permanent solution

Create an iPython profile and set initial append:

In bash shell:

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

In vi, append to the file:

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

DONE

Creating a blurring overlay view

In case this helps anyone, here is a swift extension I created based on the answer by Jordan H. It is written in Swift 5 and can be used from Objective C.

extension UIView {

    @objc func blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) {
        if !UIAccessibility.isReduceTransparencyEnabled {
            self.backgroundColor = .clear

            let blurEffect = UIBlurEffect(style: style)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            //always fill the view
            blurEffectView.frame = self.self.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

            self.insertSubview(blurEffectView, at: 0)
        } else {
            self.backgroundColor = fallbackColor
        }
    }

}

NOTE: If you want to blur the background of an UILabel without affecting the text, you should create a container UIView, add the UILabel to the container UIView as a subview, set the UILabel's backgroundColor to UIColor.clear, and then call blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) on the container UIView. Here's a quick example of this written in Swift 5:

let frame = CGRect(x: 50, y: 200, width: 200, height: 50)
let containerView = UIView(frame: frame)
let label = UILabel(frame: frame)
label.text = "Some Text"
label.backgroundColor = UIColor.clear
containerView.addSubview(label)
containerView.blurBackground(style: .dark, fallbackColor: UIColor.black)

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Simply install Win64 OpenSSL v1.0.2a or Win32 OpenSSL v1.0.2a, you can download these from http://slproweb.com/products/Win32OpenSSL.html. Works out of the box, no configuration needed.

Difference between rake db:migrate db:reset and db:schema:load

Rails 5

db:create - Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:create:all - Creates the database for all environments.

db:drop - Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:drop:all - Drops the database for all environments.

db:migrate - Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.

db:migrate:redo - Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.

db:migrate:up - Runs the up for the given migration VERSION.

db:migrate:down - Runs the down for the given migration VERSION.

db:migrate:status - Displays the current migration status.

db:migrate:rollback - Rolls back the last migration.

db:version - Prints the current schema version.

db:forward - Pushes the schema to the next version.

db:seed - Runs the db/seeds.rb file.

db:schema:load Recreates the database from the schema.rb file. Deletes existing data.

db:schema:dump Dumps the current environment’s schema to db/schema.rb.

db:structure:load - Recreates the database from the structure.sql file.

db:structure:dump - Dumps the current environment’s schema to db/structure.sql. (You can specify another file with SCHEMA=db/my_structure.sql)

db:setup Runs db:create, db:schema:load and db:seed.

db:reset Runs db:drop and db:setup. db:migrate:reset - Runs db:drop, db:create and db:migrate.

db:test:prepare - Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)

db:test:clone - Recreate the test database from the current environment’s database schema.

db:test:clone_structure - Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.

db:environment:set - Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)

db:check_protected_environments - Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

SET STATISTICS TIME ON

SELECT * 

FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;

SET STATISTICS TIME OFF;

And see the message tab it will look like this:

SQL Server Execution Times:

   CPU time = 0 ms,  elapsed time = 10 ms.

(778 row(s) affected)

SQL Server parse and compile time: 

   CPU time = 0 ms, elapsed time = 0 ms.

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

How do I activate C++ 11 in CMake?

I think just these two lines are enough.

set(CMAKE_CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

Checkout old commit and make it a new commit

git cherry-pick C

where C is the commit hash for C. This applies the old commit on top of the newest one.

How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

For example,

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

World mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

Why use def main()?

Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.

Why does NULL = NULL evaluate to false in SQL server

To quote the Christmas analogy again:

In SQL, NULL basically means "closed box" (unknown). So, the result of comparing two closed boxes will also be unknown (null).

I understand, for a developer, this is counter-intuitive, because in programming languages, often NULL rather means "empty box" (known). And comparing two empty boxes will naturally yield true / equal.

This is why JavaScript for example distinguishes between null and undefined.

How to replace space with comma using sed?

I just confirmed that:

cat file.txt | sed "s/\s/,/g"

successfully replaces spaces with commas in Cygwin terminals (mintty 2.9.0). None of the other samples worked for me.

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

Split string on the first white space occurrence

Most of the answers above search by space, not whitespace. @georg's answer is good. I have a slightly different version.

s.trim().split(/\s(.*)/).splice(0,2)

I'm not sure how to tell which is most efficient as the regexp in mine is a lot simpler, but it has the extra splace.

(@georg's for reference is s.split(/(?<=^\S+)\s/))

The question doesn't specify how to handle no whitespace or all whitespace, leading or trailing whitespace or an empty string, and our results differ subtly in those cases.

I'm writing this for a parser that needs to consume the next word, so I prefer my definition, though @georg's may be better for other use cases.

input.        mine              @georg
'aaa bbb'     ['aaa','bbb']     ['aaa','bbb']
'aaa bbb ccc' ['aaa','bbb ccc'] ['aaa','bbb ccc']
'aaa '        [ 'aaa' ]         [ 'aaa', '' ]
' '           [ '' ]            [ ' ' ]
''            ['']              ['']
' aaa'        ['aaa']           [' aaa']

How to link to apps on the app store

For summer 2015 onwards ...

-(IBAction)clickedUpdate
{
    NSString *simple = @"itms-apps://itunes.apple.com/app/id1234567890";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:simple]];
}

replace 'id1234567890' with 'id' and 'your ten digit number'

  1. This works perfectly on all devices.

  2. It does go straight to the app store, no redirects.

  3. Is OK for all national stores.

  4. It's true you should move to using loadProductWithParameters, but if the purpose of the link is to update the app you are actually inside of: it's possibly better to use this "old-fashioned" approach.

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Escaping a forward slash in a regular expression

For java, you don't need to.

eg: "^(.*)/\\*LOG:(\\d+)\\*/(.*)$" ==> ^(.*)/\*LOG:(\d+)\*/(.*)$

If you put \ in front of /. IDE will tell you "Redundant Character Escape "\/" in ReGex"

Creating a 3D sphere in Opengl using Visual C++

I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:

inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
    int curRow = r * sectors;
    int nextRow = (r+1) * sectors;

    indices.push_back(curRow + s);
    indices.push_back(nextRow + s);
    indices.push_back(nextRow + (s+1));

    indices.push_back(curRow + s);
    indices.push_back(nextRow + (s+1));
    indices.push_back(curRow + (s+1));
}

void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
             float radius, unsigned int rings, unsigned int sectors)
{
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);

    for(int r = 0; r < rings; ++r) {
        for(int s = 0; s < sectors; ++s) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

            texcoords.push_back(vec2(s*S, r*R));
            vertices.push_back(vec3(x,y,z) * radius);
            push_indices(indices, sectors, r, s);
        }
    }
}

Filtering a pyspark dataframe using isin by exclusion

Also could be like this

df.filter(col('bar').isin(['a','b']) == False).show()

Calling a javascript function in another js file

// module.js
export function hello() {
  return "Hello";
}

// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";

reference from https://hype.codes/how-include-js-file-another-js-file

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

Remove CSS class from element with JavaScript (no jQuery)

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

Add a column to a table, if it does not already exist

When checking for a column in another database, you can simply include the database name:

IF NOT EXISTS (
  SELECT * 
  FROM   DatabaseName.sys.columns 
  WHERE  object_id = OBJECT_ID(N'[DatabaseName].[dbo].[TableName]') 
         AND name = 'ColumnName'
)

How to make PyCharm always show line numbers

Using Search bar

  1. Press 2 times Shift
  2. Paste /editor /appearance/ and then
  3. Click on Show line numbers toggle button

For Windows and Linux

File | Settings | Editor | General | Appearance 

For macOS

IntelliJ IDEA | Preferences | Editor | General | Appearance 

Using shortcut

Ctrl+Alt+S

Then

Editor > General > Appearance

Click on Show line numbers toggle button.


Pycharm Official Doc (Appearance)

Open directory dialog

The best way to achieve what you want is to create your own wpf based control , or use a one that was made by other people
why ? because there will be a noticeable performance impact when using the winforms dialog in a wpf application (for some reason)
i recommend this project
https://opendialog.codeplex.com/
or Nuget :

PM> Install-Package OpenDialog

it's very MVVM friendly and it isn't wraping the winforms dialog

Is there a "null coalescing" operator in JavaScript?

beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript. 1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

in such case, the type of your variable is actually Object. test it.

window.alert(typeof myEmptyValue); // prints Object
  1. Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:

    if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }
    // alerts
    

if such case, the type of your variable is 'undefined'.

notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).

Get position/offset of element relative to a parent container?

in pure js just use offsetLeft and offsetTop properties.
Example fiddle: http://jsfiddle.net/WKZ8P/

_x000D_
_x000D_
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p   { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
    <span>paragraph</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

String MinLength and MaxLength validation don't work (asp.net mvc)

    [StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
    [Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
    public string Password { get; set; }

Save resource like this

"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"

Set time to 00:00:00

As Java8 add new Date functions, we can do this easily.


    // If you have instant, then:
    Instant instant1 = Instant.now();
    Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
    System.out.println(day1); //2019-01-14T00:00:00Z

    // If you have Date, then:
    Date date = new Date();
    Instant instant2 = date.toInstant();
    Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
    System.out.println(day2); //2019-01-14T00:00:00Z

    // If you have LocalDateTime, then:
    LocalDateTime dateTime = LocalDateTime.now();
    LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
    System.out.println(day3); //2019-01-14T00:00
    String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    System.out.println(format);//2019-01-14T00:00:00


Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

Usage of $broadcast(), $emit() And $on() in AngularJS

  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.

react-router go back a page how do you configure history?

For react-router v2.x this has changed. Here's what I'm doing for ES6:

import React from 'react';
import FontAwesome from 'react-fontawesome';
import { Router, RouterContext, Link, browserHistory } from 'react-router';

export default class Header extends React.Component {

  render() {
    return (
      <div id="header">
        <div className="header-left">
          {
            this.props.hasBackButton &&
            <FontAwesome name="angle-left" className="back-button" onClick={this.context.router.goBack} />
          }
        </div>
        <div>{this.props.title}</div>
      </div>
    )
  }
}

Header.contextTypes = {
  router: React.PropTypes.object
};

Header.defaultProps = {
  hasBackButton: true
};

Header.propTypes = {
  title: React.PropTypes.string
};

Given an array of numbers, return array of products of all other numbers (no division)

Here is a C implementation
O(n) time complexity.
INPUT

#include<stdio.h>
int main()
{
    int x;
    printf("Enter The Size of Array : ");
    scanf("%d",&x);
    int array[x-1],i ;
    printf("Enter The Value of Array : \n");
      for( i = 0 ; i <= x-1 ; i++)
      {
          printf("Array[%d] = ",i);
          scanf("%d",&array[i]);
      }
    int left[x-1] , right[x-1];
    left[0] = 1 ;
    right[x-1] = 1 ;
      for( i = 1 ; i <= x-1 ; i++)
      {
          left[i] = left[i-1] * array[i-1];
      }
    printf("\nThis is Multiplication of array[i-1] and left[i-1]\n");
      for( i = 0 ; i <= x-1 ; i++)
      {
        printf("Array[%d] = %d , Left[%d] = %d\n",i,array[i],i,left[i]);
      }
      for( i = x-2 ; i >= 0 ; i--)
      {
          right[i] = right[i+1] * array[i+1];
      }
   printf("\nThis is Multiplication of array[i+1] and right[i+1]\n");
      for( i = 0 ; i <= x-1 ; i++)
      {
        printf("Array[%d] = %d , Right[%d] = %d\n",i,array[i],i,right[i]);
      }
    printf("\nThis is Multiplication of Right[i] * Left[i]\n");
      for( i = 0 ; i <= x-1 ; i++)
      {
          printf("Right[%d] * left[%d] = %d * %d = %d\n",i,i,right[i],left[i],right[i]*left[i]);
      }
    return 0 ;
}


OUTPUT

    Enter The Size of Array : 5
    Enter The Value of Array :
    Array[0] = 1
    Array[1] = 2
    Array[2] = 3
    Array[3] = 4
    Array[4] = 5

    This is Multiplication of array[i-1] and left[i-1]
    Array[0] = 1 , Left[0] = 1
    Array[1] = 2 , Left[1] = 1
    Array[2] = 3 , Left[2] = 2
    Array[3] = 4 , Left[3] = 6
    Array[4] = 5 , Left[4] = 24

    This is Multiplication of array[i+1] and right[i+1]
    Array[0] = 1 , Right[0] = 120
    Array[1] = 2 , Right[1] = 60
    Array[2] = 3 , Right[2] = 20
    Array[3] = 4 , Right[3] = 5
    Array[4] = 5 , Right[4] = 1

    This is Multiplication of Right[i] * Left[i]
    Right[0] * left[0] = 120 * 1 = 120
    Right[1] * left[1] = 60 * 1 = 60
    Right[2] * left[2] = 20 * 2 = 40
    Right[3] * left[3] = 5 * 6 = 30
    Right[4] * left[4] = 1 * 24 = 24

    Process returned 0 (0x0)   execution time : 6.548 s
    Press any key to continue.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

How do I add 1 day to an NSDate?

You can use NSDate's method - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds where seconds would be 60 * 60 * 24 = 86400

Virtual member call in a constructor

I would just add an Initialize() method to the base class and then call that from derived constructors. That method will call any virtual/abstract methods/properties AFTER all of the constructors have been executed :)

Clear data in MySQL table with PHP?

TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

we can use for truncate

TRUNCATE TABLE tablename

we can use for delete

DELETE FROM tablename

we can also give conditions as below

DELETE FROM tablename WHERE id='xyz'

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

Aren't Python strings immutable? Then why does a + " " + b work?

You can make a numpy array immutable and use the first element:

numpyarrayname[0] = "write once"

then:

numpyarrayname.setflags(write=False)

or

numpyarrayname.flags.writeable = False

Wait for async task to finish

This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.

Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.

function f(input, callback) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) { callback(result) };

}

The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.

Iterating Over Dictionary Key Values Corresponding to List in Python

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

require 'date'

current_time = DateTime.now

current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"

current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

I use that construction whenever I don't want to add complexity to the problem. It's just a list, no need to say what kind of List it is, as it doesn't matter to the problem. I often use Collection for most of my solutions, as, in the end, most of the times, for the rest of the software, what really matters is the content it holds, and I don't want to add new objects to the Collection.

Futhermore, you use that construction when you think that you may want to change the implemenation of list you are using. Let's say you were using the construction with an ArrayList, and your problem wasn't thread safe. Now, you want to make it thread safe, and for part of your solution, you change to use a Vector, for example. As for the other uses of that list won't matter if it's a AraryList or a Vector, just a List, no new modifications will be needed.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:

const cors = require('cors');

const userRouter = require('./routers/user');

expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);

Populating a data frame in R in a loop

I had a case in where I was needing to use a data frame within a for loop function. In this case, it was the "efficient", however, keep in mind that the database was small and the iterations in the loop were very simple. But maybe the code could be useful for some one with similar conditions.

The for loop purpose was to use the raster extract function along five locations (i.e. 5 Tokio, New York, Sau Paulo, Seul & Mexico city) and each location had their respective raster grids. I had a spatial point database with more than 1000 observations allocated within the 5 different locations and I was needing to extract information from 10 different raster grids (two grids per location). Also, for the subsequent analysis, I was not only needing the raster values but also the unique ID for each observations.

After preparing the spatial data, which included the following tasks:

  1. Import points shapefile with the readOGR function (rgdap package)
  2. Import raster files with the raster function (raster package)
  3. Stack grids from the same location into one file, with the function stack (raster package)

Here the for loop code with the use of a data frame:

1. Add stacked rasters per location into a list

raslist <- list(LOC1,LOC2,LOC3,LOC4,LOC5)

2. Create an empty dataframe, this will be the output file

TB <- data.frame(VAR1=double(),VAR2=double(),ID=character())

3. Set up for loop function

L1 <- seq(1,5,1) # the location ID is a numeric variable with values from 1 to 5 

for (i in 1:length(L1)) {
  dat=subset(points,LOCATION==i) # select corresponding points for location [i] 
  t=data.frame(extract(raslist[[i]],dat),dat$ID) # run extract function with points & raster stack for location [i]
  names(t)=c("VAR1","VAR2","ID") 
  TB=rbind(TB,t)
}

Adobe Reader Command Line Reference

You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)

The FAQ notes that the use of the command line switches is unsupported.

To open a file it's:

AcroRd32.exe <filename>

The following switches are available:

  • /n - Launch a new instance of Reader even if one is already open
  • /s - Don't show the splash screen
  • /o - Don't show the open file dialog
  • /h - Open as a minimized window
  • /p <filename> - Open and go straight to the print dialog
  • /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

Android Fastboot devices not returning device

If you got nothing when inputted fastboot devices, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-'). Then you can see you devices via fastboot devices and continue to flash your devices.

note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.

Disable/Enable Submit Button until all forms have been filled

<form name="theform">
    <input type="text" />
    <input type="text" />`enter code here`
    <input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>

<script type="text/javascript" language="javascript">

    let txt = document.querySelectorAll('[type="text"]');
    for (let i = 0; i < txt.length; i++) {
        txt[i].oninput = () => {
            if (!(txt[0].value == '') && !(txt[1].value == '')) {
                submitbutton.removeAttribute('disabled')
            }
        }
    }
</script>

Sort hash by key, return hash in Ruby

Sort hash by key, return hash in Ruby

With destructuring and Hash#sort

hash.sort { |(ak, _), (bk, _)| ak <=> bk }.to_h

Enumerable#sort_by

hash.sort_by { |k, v| k }.to_h

Hash#sort with default behaviour

h = { "b" => 2, "c" => 1, "a" => 3  }
h.sort         # e.g. ["a", 20] <=> ["b", 30]
hash.sort.to_h #=> { "a" => 3, "b" => 2, "c" => 1 }

Note: < Ruby 2.1

array = [["key", "value"]] 
hash  = Hash[array]
hash #=> {"key"=>"value"}

Note: > Ruby 2.1

[["key", "value"]].to_h #=> {"key"=>"value"}

Generate JSON string from NSDictionary in iOS

public func jsonPrint(_ o: NSObject, spacing: String = "", after: String = "", before: String = "") {
    let newSpacing = spacing + "    "
    if o.isArray() {
        print(before + "[")
        if let a = o as? Array<NSObject> {
            for object in a {
                jsonPrint(object, spacing: newSpacing, after: object == a.last! ? "" : ",", before: newSpacing)
            }
        }
        print(spacing + "]" + after)
    } else {
        if o.isDictionary() {
            print(before + "{")
            if let a = o as? Dictionary<NSObject, NSObject> {
                for (key, val) in a {
                    jsonPrint(val, spacing: newSpacing, after: ",", before: newSpacing + key.description + " = ")
                }
            }
            print(spacing + "}" + after)
        } else {
            print(before + o.description + after)
        }
    }
}

This one is pretty close to original Objective-C print style

How to convert int to NSString?

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

What is Ruby's double-colon `::`?

Adding to previous answers, it is valid Ruby to use :: to access instance methods. All the following are valid:

MyClass::new::instance_method
MyClass::new.instance_method
MyClass.new::instance_method
MyClass.new.instance_method

As per best practices I believe only the last one is recommended.

Property 'value' does not exist on type 'EventTarget'

I believe it must work but any ways I'm not able to identify. Other approach can be,

<textarea (keyup)="emitWordCount(myModel)" [(ngModel)]="myModel"></textarea>


export class TextEditorComponent {
   @Output() countUpdate = new EventEmitter<number>();

   emitWordCount(model) {
       this.countUpdate.emit(
         (model.match(/\S+/g) || []).length);
       }
}

HttpClient does not exist in .net 4.0: what can I do?

Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here

However, the text is very confusion and contradicts itself.

This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.

But underneath it states that these are the supported platforms.

Supported Platforms:

  • .NET Framework 4

  • Windows 8

  • Windows Phone 8.1

  • Windows Phone Silverlight 7.5

  • Silverlight 4

  • Portable Class Libraries

Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.

Extending from two classes

As everyone else has said. No, you can't. However even though people have said many times over the years that you should use multiple interfaces they haven't really gone into how. Hopefully this will help.

Say you have class Foo and class Bar that you both want to try extending into a class FooBar. Of course, as you said, you can't do:

public class FooBar extends Foo, Bar

People have gone into the reasons for this to some extent already. Instead, write interfaces for both Foo and Bar covering all of their public methods. E.g.

public interface FooInterface {

    public void methodA();

    public int methodB();

    //...
} 

public interface BarInterface {

    public int methodC(int i);

    //...
}

And now make Foo and Bar implement the relative interfaces:

public class Foo implements FooInterface { /*...*/ }

public class Bar implements BarInterface { /*...*/ }

Now, with class FooBar, you can implement both FooInterface and BarInterface while keeping a Foo and Bar object and just passing the methods straight through:

public class FooBar implements FooInterface, BarInterface {

    Foo myFoo;
    Bar myBar;

    // You can have the FooBar constructor require the arguments for both
    //  the Foo and the Bar constructors
    public FooBar(int x, int y, int z){
        myFoo = new Foo(x);
        myBar = new Bar(y, z);
    }

    // Or have the Foo and Bar objects passed right in
    public FooBar(Foo newFoo, Bar newBar){
        myFoo = newFoo;
        myBar = newBar;
    }

    public void methodA(){
        myFoo.methodA();
    }

    public int methodB(){
        return myFoo.methodB();
    }

    public int methodC(int i){
        return myBar.methodC(i);
    }

    //...

}

The bonus for this method, is that the FooBar object fits the moulds of both FooInterface and BarInterface. That means this is perfectly fine:

FooInterface testFoo;
testFoo = new FooBar(a, b, c);
testFoo = new Foo(a);

BarInterface testBar;
testBar = new FooBar(a, b, c);
testBar = new Bar(b, c);

Hope this clarifies how to use interfaces instead of multiple extensions. Even if I am a few years late.

Java: using switch statement with enum under subclass

Write someMethod() in this way:

public void someMethod() {

    SomeClass.AnotherClass.MyEnum enumExample = SomeClass.AnotherClass.MyEnum.VALUE_A;

    switch (enumExample) {
    case VALUE_A:
        break;
    }

}

In switch statement you must use the constant name only.

Mvn install or Mvn package

mvn install is the option that is most often used.
mvn package is seldom used, only if you're debugging some issue with the maven build process.

See: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

Note that mvn package will only create a jar file.
mvn install will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.

I usually do a mvn clean install; this deletes the target directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

Ran into the exact same problem as OP and found that leaving the "MySQL Server Port" empty in the MySQL Workbench connection solves the issue.

Run function in script from command line (Node JS)

Sometimes you want to run a function via CLI, sometimes you want to require it from another module. Here's how to do both.

// file to run
const runMe = () => {}
if (require.main === module) {
  runMe()
} 
module.exports = runMe

Trigger event when user scroll to specific element - with jQuery

You could use this for all devices,

$(document).on('scroll', function() {
    if( $(this).scrollTop() >= $('#target_element').position().top ){
        do_something();
    }
});

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

Using filesystem in node.js with async / await

This is the TypeScript version to the question. It is usable after Node 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

On linux SUSE or RedHat, how do I load Python 2.7

RHEL 6.2 using (had Python 2.6, i need Python 2.7.3) So:

$ sudo sh -c 'wget -qO- http://people.redhat.com/bkabrda/scl_python27.repo >> /etc/yum.repos.d/scl.repo'

$ yum search python27
Loaded plugins: amazon-id, rhui-lb, security
scl_python27                                                                                                                                      | 2.9 kB     00:00     
scl_python27/primary_db                                                                                                                           |  38 kB     00:00     
========================================================================= N/S Matched: python27 =========================================================================
python27.i686 : Package that installs python27
python27.x86_64 : Package that installs python27
python27-expat-debuginfo.i686 : Debug information for package python27-expat
python27-expat-debuginfo.x86_64 : Debug information for package python27-expat
python27-python-coverage-debuginfo.i686 : Debug information for package python27-python-coverage
python27-python-coverage-debuginfo.x86_64 : Debug information for package python27-python-coverage
python27-python-debuginfo.i686 : Debug information for package python27-python
python27-python-debuginfo.x86_64 : Debug information for package python27-python
python27-python-markupsafe-debuginfo.i686 : Debug information for package python27-python-markupsafe
python27-python-markupsafe-debuginfo.x86_64 : Debug information for package python27-python-markupsafe
python27-python-simplejson-debuginfo.i686 : Debug information for package python27-python-simplejson
python27-python-simplejson-debuginfo.x86_64 : Debug information for package python27-python-simplejson
python27-python-sqlalchemy-debuginfo.i686 : Debug information for package python27-python-sqlalchemy
python27-python-sqlalchemy-debuginfo.x86_64 : Debug information for package python27-python-sqlalchemy
python27-runtime.i686 : Package that handles python27 Software Collection.
python27-runtime.x86_64 : Package that handles python27 Software Collection.
python27-babel.noarch : Tools for internationalizing Python applications
python27-build.i686 : Package shipping basic build configuration
python27-build.x86_64 : Package shipping basic build configuration
python27-expat.i686 : An XML parser library
python27-expat.x86_64 : An XML parser library
python27-expat-devel.i686 : Libraries and header files to develop applications using expat
python27-expat-devel.x86_64 : Libraries and header files to develop applications using expat
python27-expat-static.i686 : expat XML parser static library
python27-expat-static.x86_64 : expat XML parser static library
python27-python.i686 : An interpreted, interactive, object-oriented programming language
python27-python.x86_64 : An interpreted, interactive, object-oriented programming language
python27-python-babel.noarch : Library for internationalizing Python applications
python27-python-coverage.i686 : Code coverage testing module for Python
python27-python-coverage.x86_64 : Code coverage testing module for Python
python27-python-debug.i686 : Debug version of the Python runtime
python27-python-debug.x86_64 : Debug version of the Python runtime
python27-python-devel.i686 : The libraries and header files needed for Python development
python27-python-devel.x86_64 : The libraries and header files needed for Python development
python27-python-docutils.noarch : System for processing plaintext documentation
python27-python-jinja2.noarch : General purpose template engine
python27-python-libs.i686 : Runtime libraries for Python
python27-python-libs.x86_64 : Runtime libraries for Python
python27-python-markupsafe.i686 : Implements a XML/HTML/XHTML Markup safe string for Python
python27-python-markupsafe.x86_64 : Implements a XML/HTML/XHTML Markup safe string for Python
python27-python-nose.noarch : Discovery-based unittest extension for Python
python27-python-nose-docs.noarch : Nose Documentation
python27-python-pygments.noarch : Syntax highlighting engine written in Python
python27-python-setuptools.noarch : Easily build and distribute Python packages
python27-python-simplejson.i686 : Simple, fast, extensible JSON encoder/decoder for Python
python27-python-simplejson.x86_64 : Simple, fast, extensible JSON encoder/decoder for Python
python27-python-sphinx.noarch : Python documentation generator
python27-python-sphinx-doc.noarch : Documentation for python-sphinx
python27-python-sqlalchemy.i686 : Modular and flexible ORM library for python
python27-python-sqlalchemy.x86_64 : Modular and flexible ORM library for python
python27-python-test.i686 : The test modules from the main python package
python27-python-test.x86_64 : The test modules from the main python package
python27-python-tools.i686 : A collection of development tools included with Python
python27-python-tools.x86_64 : A collection of development tools included with Python
python27-python-virtualenv.noarch : Tool to create isolated Python environments
python27-python-werkzeug.noarch : The Swiss Army knife of Python web development
python27-python-werkzeug-doc.noarch : Documentation for python-werkzeug
python27-tkinter.i686 : A graphical user interface for the Python scripting language
python27-tkinter.x86_64 : A graphical user interface for the Python scripting language

  Name and summary matches only, use "search all" for everything.

EDIT:

CentOS 6.x: http://dev.centos.org/centos/6/SCL/x86_64/python27/

$ sudo sh -c 'wget -qO- http://dev.centos.org/centos/6/SCL/scl.repo >> /etc/yum.repos.d/scl.repo'
$ scl enable python27 'python --version'
python 2.7.5
$ scl enable python27 bash
$ python --version
Python 2.7.5

Best way to add Gradle support to IntelliJ Project

Just as a future reference, if you already have a Maven project all you need to do is doing a gradle init in your project directory which will generates build.gradle and other dependencies, then do a gradle build in the same directory.

Simple If/Else Razor Syntax

Just use this for the closing tag:

  @:</tr>

And leave your if/else as is.

Seems like the if statement doesn't wanna' work.

It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

bash script use cut command at variable and store result at another variable

The awk solution is what I would use, but if you want to understand your problems with bash, here is a revised version of your script.

#!/bin/bash -vx

##config file with ip addresses like 10.10.10.1:80
file=config.txt

while read line ; do
  ##this line is not correct, should strip :port and store to ip var
  ip=$( echo "$line" |cut -d\: -f1 )
  ping $ip
done < ${file}

You could write your top line as

for line in $(cat $file) ; do ...

(but not recommended).

You needed command substitution $( ... ) to get the value assigned to $ip

reading lines from a file is usually considered more efficient with the while read line ... done < ${file} pattern.

I hope this helps.

jQuery add image inside of div tag

If we want to change the content of <div> tag whenever the function image()is called, we have to do like this:

Javascript

function image() {
    var img = document.createElement("IMG");
    img.src = "/images/img1.gif";
    $('#image').html(img); 
}

HTML

<div id="image"></div>
<div><a href="javascript:image();">First Image</a></div>

how to update spyder on anaconda

To expand on juanpa.arrivillaga's comment:

If you want to update Spyder in the root environment, then conda update spyder works for me.

If you want to update Spyder for a virtual environment you have created (e.g., for a different version of Python), then conda update -n $ENV_NAME spyder where $ENV_NAME is your environment name.

EDIT: In case conda update spyder isn't working, this post indicates you might need to run conda update anaconda before updating spyder. Also note that you can specify an exact spyder version if you want.

How do I download code using SVN/Tortoise from Google Code?

If you are behind a firewall you will have to configure the Tortoise client to connect to it. Right click somewhere in your window, select "TortoiseSVN", select "settings", and then select "network" on the left side of the panel. Fill out all the required fields. Good luck.

I'm getting Key error in python

For example, if this is a number :

ouloulou={
    1:US,
    2:BR,
    3:FR
    }
ouloulou[1]()

It's work perfectly, but if you use for example :

ouloulou[input("select 1 2 or 3"]()

it's doesn't work, because your input return string '1'. So you need to use int()

ouloulou[int(input("select 1 2 or 3"))]()

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Can't ping a local VM from the host

Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1

Convert float to std::string in C++

This tutorial gives a simple, yet elegant, solution, which i transcribe:

#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline std::string stringify(double x)
{
  std::ostringstream o;
  if (!(o << x))
    throw BadConversion("stringify(double)");
  return o.str();
}
...
std::string my_val = stringify(val);

How do you use MySQL's source command to import large files in windows

On windows: Use explorer to navigate to the folder with the .sql file. Type cmd in the top address bar. Cmd will open. Type:

"C:\path\to\mysql.exe" -u "your_username" -p "your password" < "name_of_your_sql_file.sql"

Wait a bit and the sql file will have been executed on your database. Confirmed to work with MariaDB in feb 2018.

Removing path and extension from filename in PowerShell

The command below will store in a variable all the file in your folder, matchting the extension ".txt":

$allfiles=Get-ChildItem -Path C:\temp\*" -Include *.txt
foreach ($file in $allfiles) {
    Write-Host $file
    Write-Host $file.name
    Write-Host $file.basename
}

$file gives the file with path, name and extension: c:\temp\myfile.txt

$file.name gives file name & extension: myfile.txt

$file.basename gives only filename: myfile

Rotating x axis labels in R for barplot

In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:

...    arguments to be passed to/from other methods. For the default method these can 
       include further arguments (such as axes, asp and main) and graphical 
       parameters (see par) which are passed to plot.window(), title() and axis.

In the documentation of graphical parameters (documentation of par) we can see:

las
    numeric in {0,1,2,3}; the style of axis labels.

    0:
      always parallel to the axis [default],

    1:
      always horizontal,

    2:
      always perpendicular to the axis,

    3:
      always vertical.

    Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.

That is why passing las=2 is the right answer.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I had the same problem. This is related to hibernate. I changed the database from dev to production in hibernate.cfg.xml but there were catalog attribute in other hbm.xml files with the old database name and it was causing the issue.

Instead of telling incorrect database name, it showed Permission denied error.

So make sure to change the database name everywhere or just remove the catalog attribute

How to make button look like a link?

You can't style buttons as links reliably throughout browsers. I've tried it, but there's always some weird padding, margin or font issues in some browser. Either live with letting the button look like a button, or use onClick and preventDefault on a link.

make: Nothing to be done for `all'

That is not an error; the make command in unix works based on the timestamps. I.e let's say if you have made certain changes to factorial.cpp and compile using make then make shows the information that only the cc -o factorial.cpp command is executed. Next time if you execute the same command i.e make without making any changes to any file with .cpp extension the compiler says that the output file is up to date. The compiler gives this information until we make certain changes to any file.cpp.

The advantage of the makefile is that it reduces the recompiling time by compiling the only files that are modified and by using the object (.o) files of the unmodified files directly.

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

I created a more comprehensive and cleaner version that some people might find useful for remembering which name corresponds to which value. I used Chrome Dev Tool's color code and labels are organized symmetrically to pick up analogies faster:

enter image description here

  • Note 1: clientLeft also includes the width of the vertical scroll bar if the direction of the text is set to right-to-left (since the bar is displayed to the left in that case)

  • Note 2: the outermost line represents the closest positioned parent (an element whose position property is set to a value different than static or initial). Thus, if the direct container isn’t a positioned element, then the line doesn’t represent the first container in the hierarchy but another element higher in the hierarchy. If no positioned parent is found, the browser will take the html or body element as reference


Hope somebody finds it useful, just my 2 cents ;)

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

Well no, from an iOS developer prospective, there are two links that I know of that will open the Maps app on the iPhone

On iOS 5 and lower: http://maps.apple.com?q=xxxx

On iOS 6 and up: http://maps.google.com?q=xxxx

And that's only on Safari. Chrome will direct you to Google Maps webpage.

Other than that you'll need to use a URL scheme that basically beats the purpose because no android will know that protocol.

You might want to know, Why Safari opens the Maps app and Chrome directs me to a webpage?

Well, because safari is the build in browser made by apple and can detect the URL above. Chrome is "just another app" and must comply to the iOS Ecosystem. Therefor the only way for it to communicate with other apps is by using URL schemes.

How to select data from 30 days?

For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )

Get user input from textarea

Tested with Angular2 RC2

I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps

textarea-component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'textarea-comp',
  template: `
      <textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
      <p><button (click)="pushMe()">pushMeToLog</button></p>
  `
})

  export class TextAreaComponent {
    str: string;

  pushMe() {
      console.log( "TextAreaComponent::str: " + this.str);
  }
}

How to run certain task every day at a particular time using ScheduledExecutorService?

Why to complicate a situation if you can just write like it? (yes -> low cohesion, hardcoded -> but it is a example and unfortunately with imperative way). For additional info read code example at below ;))

package timer.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.*;

public class TestKitTimerWithExecuterService {

    private static final Logger log = LoggerFactory.getLogger(TestKitTimerWithExecuterService.class);

    private static final ScheduledExecutorService executorService 
= Executors.newSingleThreadScheduledExecutor();// equal to => newScheduledThreadPool(1)/ Executor service with one Thread

    private static ScheduledFuture<?> future; // why? because scheduleAtFixedRate will return you it and you can act how you like ;)



    public static void main(String args[]){

        log.info("main thread start");

        Runnable task = () -> log.info("******** Task running ********");

        LocalDateTime now = LocalDateTime.now();

        LocalDateTime whenToStart = LocalDate.now().atTime(20, 11); // hour, minute

        Duration duration = Duration.between(now, whenToStart);

        log.info("WhenToStart : {}, Now : {}, Duration/difference in second : {}",whenToStart, now, duration.getSeconds());

        future = executorService.scheduleAtFixedRate(task
                , duration.getSeconds()    //  difference in second - when to start a job
                ,2                         // period
                , TimeUnit.SECONDS);

        try {
            TimeUnit.MINUTES.sleep(2);  // DanDig imitation of reality
            cancelExecutor();    // after canceling Executor it will never run your job again
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("main thread end");
    }




    public static void cancelExecutor(){

        future.cancel(true);
        executorService.shutdown();

        log.info("Executor service goes to shut down");
    }

}

How to install SignTool.exe for Windows 10

As per the comments in the question... On Windows 10 Signtool.exe and other SDK tools have been moved into "%programfiles(x86)%\Windows Kits\".

Typical path to signtool on Windows 10.

  • 32 bit = "c:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe"
  • 64 bit = "c:\Program Files (x86)\Windows Kits\10\bin\x64\signtool.exe"

Tools for SDK 8.0 and 8.1 also reside in the "Windows Kits" folder.

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

I haven't tested every single one of these answers but you don't need to use complicated functions to accomplish this. It's so much easier than that! My code below will work in any office VBA application (Word, Access, Excel, Outlook, etc.) and is very simple. Hope this helps:

''Dimension 2 Arrays
Dim InnerArray(1 To 3) As Variant ''The inner is for storing each column value of the current row
Dim OuterArray() As Variant ''The outer is for storing each row in
Dim i As Byte

    i = 1
    Do While i <= 5

        ''Enlarging our outer array to store a/another row
        ReDim Preserve OuterArray(1 To i)

        ''Loading the current row column data in
        InnerArray(1) = "My First Column in Row " & i
        InnerArray(2) = "My Second Column in Row " & i
        InnerArray(3) = "My Third Column in Row " & i

        ''Loading the entire row into our array
        OuterArray(i) = InnerArray

        i = i + 1
    Loop

    ''Example print out of the array to the Intermediate Window
    Debug.Print OuterArray(1)(1)
    Debug.Print OuterArray(1)(2)
    Debug.Print OuterArray(2)(1)
    Debug.Print OuterArray(2)(2)

How to view unallocated free space on a hard disk through terminal

when you cut you disk in partitions by fdisk you may be careful so as not to left gaps with free space. So command automatically align partitions and you'll get some gaps between parts. There are many articles in net why need to do so. The reason is that it gives solution with less errors. That was many years ago. Now I don't know is there errors occurs if you do all without any gaps. But first. You may do so if you don't allow alignment you sen begin of the next part=end previous+1. But is first part begins always with 2048 sector. So call expert part you may shift it to 0. But strongly recomended to do so if you plan to boot from this disk. If only for data you'll gain 1 Mb additional disk space. This is an MBR space. If you plan to install OS on this disk you don't use GPT partition type. Also it's more suitable not all OS see GPT parts of disks. But some see them. If you don't sure it use msdos. While format the block size is 4096 bytes(logical) physical one is 512 bytes. I don't do so but you may set block size=512 too. There was many discussion about that. It's lead to disk errors. But you'll give some free disk space too especially when you have many small size files. You disk will fill more compactly. And if you give already partitioned disk with filled them with data and maybe installed OS you maybe want to do so, it was very problems to do. But is possible for Linux. For Windows no... You must save backup and mbr too, write UUID every part then use fdisk and format as setting right UUID and LABEL for every part restore mbr with dd command and if you don't do any wrong all will be work as before but without any gaps.

Why have header files and .cpp files?

C++ compilation

A compilation in C++ is done in 2 major phases:

  1. The first is the compilation of "source" text files into binary "object" files: The CPP file is the compiled file and is compiled without any knowledge about the other CPP files (or even libraries), unless fed to it through raw declaration or header inclusion. The CPP file is usually compiled into a .OBJ or a .O "object" file.

  2. The second is the linking together of all the "object" files, and thus, the creation of the final binary file (either a library or an executable).

Where does the HPP fit in all this process?

A poor lonesome CPP file...

The compilation of each CPP file is independent from all other CPP files, which means that if A.CPP needs a symbol defined in B.CPP, like:

// A.CPP
void doSomething()
{
   doSomethingElse(); // Defined in B.CPP
}

// B.CPP
void doSomethingElse()
{
   // Etc.
}

It won't compile because A.CPP has no way to know "doSomethingElse" exists... Unless there is a declaration in A.CPP, like:

// A.CPP
void doSomethingElse() ; // From B.CPP

void doSomething()
{
   doSomethingElse() ; // Defined in B.CPP
}

Then, if you have C.CPP which uses the same symbol, you then copy/paste the declaration...

COPY/PASTE ALERT!

Yes, there is a problem. Copy/pastes are dangerous, and difficult to maintain. Which means that it would be cool if we had some way to NOT copy/paste, and still declare the symbol... How can we do it? By the include of some text file, which is commonly suffixed by .h, .hxx, .h++ or, my preferred for C++ files, .hpp:

// B.HPP (here, we decided to declare every symbol defined in B.CPP)
void doSomethingElse() ;

// A.CPP
#include "B.HPP"

void doSomething()
{
   doSomethingElse() ; // Defined in B.CPP
}

// B.CPP
#include "B.HPP"

void doSomethingElse()
{
   // Etc.
}

// C.CPP
#include "B.HPP"

void doSomethingAgain()
{
   doSomethingElse() ; // Defined in B.CPP
}

How does include work?

Including a file will, in essence, parse and then copy-paste its content in the CPP file.

For example, in the following code, with the A.HPP header:

// A.HPP
void someFunction();
void someOtherFunction();

... the source B.CPP:

// B.CPP
#include "A.HPP"

void doSomething()
{
   // Etc.
}

... will become after inclusion:

// B.CPP
void someFunction();
void someOtherFunction();

void doSomething()
{
   // Etc.
}

One small thing - why include B.HPP in B.CPP?

In the current case, this is not needed, and B.HPP has the doSomethingElse function declaration, and B.CPP has the doSomethingElse function definition (which is, by itself a declaration). But in a more general case, where B.HPP is used for declarations (and inline code), there could be no corresponding definition (for example, enums, plain structs, etc.), so the include could be needed if B.CPP uses those declaration from B.HPP. All in all, it is "good taste" for a source to include by default its header.

Conclusion

The header file is thus necessary, because the C++ compiler is unable to search for symbol declarations alone, and thus, you must help it by including those declarations.

One last word: You should put header guards around the content of your HPP files, to be sure multiple inclusions won't break anything, but all in all, I believe the main reason for existence of HPP files is explained above.

#ifndef B_HPP_
#define B_HPP_

// The declarations in the B.hpp file

#endif // B_HPP_

or even simpler (although not standard)

#pragma once

// The declarations in the B.hpp file

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Delete all objects in a list

tl;dr;

mylist.clear()  # Added in Python 3.3
del mylist[:]

are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn't work.


cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. a refers to the same object that c[0] references. When you loop over c (for i in c:), at some point i also refers to that same object. the del keyword removes a single reference, so:

for i in c:
   del i

creates a reference to an object in c and then deletes that reference -- but the object still has other references (one stored in c for example) so it will persist.

In the same way:

def kill(self):
    del self

only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:

mylist = list(range(10000))
mylist[:] = []
print(mylist)

Apparently you can also delete the slice to remove objects in place:

del mylist[:]  #This will implicitly call the `__delslice__` or `__delitem__` method.

This will remove all the references from mylist and also remove the references from anything that refers to mylist. Compared that to simply deleting the list -- e.g.

mylist = list(range(10000))
b = mylist
del mylist
#here we didn't get all the references to the objects we created ...
print(b) #[0, 1, 2, 3, 4, ...]

Finally, more recent python revisions have added a clear method which does the same thing that del mylist[:] does.

mylist = [1, 2, 3]
mylist.clear()
print(mylist)

Parsing JSON from URL

Here is a easy method.

First parse the JSON from url -

public String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);

    try {

        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) {

            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            inputStream.close();

        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }
    return stringBuilder.toString();
}

Then place a task and then read the desired value from JSON -

private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        return readJSONFeed(urls[0]);
    }

    protected void onPostExecute(String result) {

        JSONObject json;
        try {
            json = new JSONObject(result);

        ////CREATE A JSON OBJECT////

        JSONObject data = json.getJSONObject("JSON OBJECT NAME");

        ////GET A STRING////

        String title = data.getString("");

        //Similarly you can get other types of data
        //Replace String to the desired data type like int or boolean etc.

        } catch (JSONException e1) {
            e1.printStackTrace();

        }

        //GETTINGS DATA FROM JSON ARRAY//

        try {

            JSONObject jsonObject = new JSONObject(result);
            JSONArray postalCodesItems = new JSONArray(
                    jsonObject.getString("postalCodes"));

                JSONObject postalCodesItem = postalCodesItems
                        .getJSONObject(1);

        } catch (Exception e) {
            Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
        }
    }
}

You can then place a task like this -

new ReadPlacesFeedTask()
    .execute("JSON URL");

Phone mask with jQuery and Masked Input Plugin

With jquery.mask.js

http://jsfiddle.net/brynner/f9kd0aes/

HTML

<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">

JS

// Function
function phoneMask(e){
    var s=e.val();
    var s=s.replace(/[_\W]+/g,'');
    var n=s.length;
    if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
    $(e).mask(m);
}

// Type
$('body').on('keyup','.phone',function(){   
    phoneMask($(this));
});

// On load
$('.phone').keyup();

Only jQuery

http://jsfiddle.net/brynner/6vbrqe6z/

HTML

<p class="phone">85999998888</p>
<p class="phone">8599998888</p>

jQuery

$('.phone').text(function(i, text) {
    var n = (text.length)-6;
    if(n==4){var p=n;}else{var p=5;}
    var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
    var text = text.replace(regex, "($1) $2-$3");
    return text;
});

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

From MSDN:

The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.

There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:

  1. Stop the WPF Font Cache 4.0 service.
  2. Delete all of the WPFFontCache_v0400* files. In Windows XP, you'll find them in your C:\Documents and Settings\LocalService\Local Settings\Application Data\ folder.
  3. Start the service again.

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

You need only one line before the declaration of the class Animal for correct polymorphic serialization/deserialization:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public abstract class Animal {
   ...
}

This line means: add a meta-property on serialization or read a meta-property on deserialization (include = JsonTypeInfo.As.PROPERTY) called "@class" (property = "@class") that holds the fully-qualified Java class name (use = JsonTypeInfo.Id.CLASS).

So, if you create a JSON directly (without serialization) remember to add the meta-property "@class" with the desired class name for correct deserialization.

More information here

Global variables in c#.net

Use a public static class and access it from anywhere.

public static class MyGlobals {
    public const string Prefix = "ID_"; // cannot change
    public static int Total = 5; // can change because not const
}

used like so, from master page or anywhere:

string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();

You don't need to make an instance of the class; in fact you can't because it's static. new Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because const is implicitly static by nature.

The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)

You can make as many static classes as you like and name them whatever you want.


Sometimes programmers like to group their constants by using nested static classes. For example,

public static class Globals {
    public static class DbProcedures {
        public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
        public const string Sp_Get_Names = "dbo.[Get_First_Names]";
    }
    public static class Commands {
        public const string Go = "go";
        public const string SubmitPage = "submit_now";
    }
}

and access them like so:

MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

WebService Client Generation Error with JDK8

I was also getting similar type of error in Eclipse during testing a webservice program on glassfish 4.0 web server: java.lang.AssertionError: org.xml.sax.SAXParseException; systemId: bundle://158.0:1/com/sun/tools/xjc/reader/xmlschema/bindinfo/binding.xsd; lineNumber: 52; columnNumber: 88; schema_reference: Failed to read schema document 'xjc.xsd', because 'bundle' access is not allowed due to restriction set by the accessExternalSchema property.

I have added javax.xml.accessExternalSchema = All in jaxp.properties, but doesnot work for me.

However I found a solution here below which work for me: For GlassFish Server, I need to modify the domain.xml of the GlassFish, path :<path>/glassfish/domains/domain1 or domain2/config/domain.xml) and add, <jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options>under the <java-config> tag

....

<java-config> ... <jvm-options>-Djavax.xml.accessExternalSchema=all</jvm-options> </java-config> ...and then restart the GlassFish server

How to get first item from a java.util.Set?

tl;dr

Call SortedSet::first

Move elements, and call first().

new TreeSet<String>( 
    pContext.getParent().getPropertyValue( … )   // Transfer elements from your `Set` to this new `TreeSet`, an implementation of the `SortedSet` interface. 
)
.first()

Set Has No Order

As others have said, a Set by definition has no order. Therefore asking for the “first” element has no meaning.

Some implementations of Set have an order such as the order in which items were added. That unofficial order may be available via the Iterator. But that order is accidental and not guaranteed. If you are lucky, the implementation backing your Set may indeed be a SortedSet.

CAVEAT: If order is critical, do not rely on such behavior. If reliability is not critical, such undocumented behavior might be handy. If given a Set you have no other viable alternative, so trying this may be better than nothing.

Object firstElement = mySet.iterator().next();

To directly address the Question… No, not really any shorter way to get first element from iterator while handling the possible case of an empty Set. However, I would prefer an if test for isEmpty rather than the Question’s for loop.

if ( ! mySet.isEmpty() ) {
    Object firstElement = mySet.iterator().next();
)

Use SortedSet

If you care about maintaining a sort order in a Set, use a SortedSet implementation. Such implementations include:

Use LinkedHashSet For Insertion-Order

If all you need is to remember elements in the order they were added to the Set use a LinkedHashSet.

To quote the doc, this class…

maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order).

Get child Node of another Node, given node name

You should read it recursively, some time ago I had the same question and solve with this code:

public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
    for (int i = 0; i < nl.getLength(); i++) {
        proccessMenuNode(nl.item(i), menubar);
    }
}

public void proccessMenuNode(Node n, Container parent) {
    if(!n.getNodeName().equals("menu"))
        return;
    Element element = (Element) n;
    String type = element.getAttribute("type");
    String name = element.getAttribute("name");
    if (type.equals("menu")) {
        NodeList nl = element.getChildNodes();
        JMenu menu = new JMenu(name);

        for (int i = 0; i < nl.getLength(); i++)
            proccessMenuNode(nl.item(i), menu);

        parent.add(menu);
    } else if (type.equals("item")) {
        JMenuItem item = new JMenuItem(name);
        parent.add(item);
    }
}

Probably you can adapt it for your case.

Count multiple columns with group by in one query

SELECT COUNT(col1 OR col2) FROM [table_name] GROUP BY col1,col2;

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

Check out Hex.encodeHexString from Apache Commons Codec.

import org.apache.commons.codec.binary.Hex;

String hex = Hex.encodeHexString(bytes);

How to compare files from two different branches?

The best way to do it is by using git diff in the following way: git diff <source_branch> <target_branch> -- file_path

It will check the difference between files in those branches. Take a look at this article for more information about git commands and how they work.

How to Delete Session Cookie?

Deleting a jQuery cookie:

$(function() {
    var COOKIE_NAME = 'test_cookie';
    var options = { path: '/', expires: 10 };
    $.cookie(COOKIE_NAME, 'test', options); // sets the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns test
    $.cookie(COOKIE_NAME, null, options);   // deletes the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns null
});

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Try to do all the steps specified in the link below and before that upgrade VirtualBox to 4.2 by following the instructions in VirtualBox 4.2.0 Released With Support For Drag'n'drop From Host To Linux Guests, More. Then upgrade Genymotion to the latest version.

Go to the desktop and run Genymotion. Select a virtual device with Android version 4.2 and then drag and drop the two files Genymotion-ARM-Translation_v1.1.zip first. Then Genymotion will show progress and after this it will promt a dialog. Then click OK and it will ask to reboot the device. Restart ADB. Do the same steps for the second file, gapps-jb-20130812-signed.zip and restart ADB.

I hope this will resolve the issue. Check this link - it explains it clearer.

Understanding implicit in Scala

Why and when you should mark the request parameter as implicit:

Some methods that you will make use of in the body of your action have an implicit parameter list like, for example, Form.scala defines a method:

def bindFromRequest()(implicit request: play.api.mvc.Request[_]): Form[T] = { ... }

You don't necessarily notice this as you would just call myForm.bindFromRequest() You don't have to provide the implicit arguments explicitly. No, you leave the compiler to look for any valid candidate object to pass in every time it comes across a method call that requires an instance of the request. Since you do have a request available, all you need to do is to mark it as implicit.

You explicitly mark it as available for implicit use.

You hint the compiler that it's "OK" to use the request object sent in by the Play framework (that we gave the name "request" but could have used just "r" or "req") wherever required, "on the sly".

myForm.bindFromRequest()

see it? it's not there, but it is there!

It just happens without your having to slot it in manually in every place it's needed (but you can pass it explicitly, if you so wish, no matter if it's marked implicit or not):

myForm.bindFromRequest()(request)

Without marking it as implicit, you would have to do the above. Marking it as implicit you don't have to.

When should you mark the request as implicit? You only really need to if you are making use of methods that declare an implicit parameter list expecting an instance of the Request. But to keep it simple, you could just get into the habit of marking the request implicit always. That way you can just write beautiful terse code.

Database development mistakes made by application developers

Poor Performance Caused by Correlated Subqueries

Most of the time you want to avoid correlated subqueries. A subquery is correlated if, within the subquery, there is a reference to a column from the outer query. When this happens, the subquery is executed at least once for every row returned and could be executed more times if other conditions are applied after the condition containing the correlated subquery is applied.

Forgive the contrived example and the Oracle syntax, but let's say you wanted to find all the employees that have been hired in any of your stores since the last time the store did less than $10,000 of sales in a day.

select e.first_name, e.last_name
from employee e
where e.start_date > 
        (select max(ds.transaction_date)
         from daily_sales ds
         where ds.store_id = e.store_id and
               ds.total < 10000)

The subquery in this example is correlated to the outer query by the store_id and would be executed for every employee in your system. One way that this query could be optimized is to move the subquery to an inline-view.

select e.first_name, e.last_name
from employee e,
     (select ds.store_id,
             max(s.transaction_date) transaction_date
      from daily_sales ds
      where ds.total < 10000
      group by s.store_id) dsx
where e.store_id = dsx.store_id and
      e.start_date > dsx.transaction_date

In this example, the query in the from clause is now an inline-view (again some Oracle specific syntax) and is only executed once. Depending on your data model, this query will probably execute much faster. It would perform better than the first query as the number of employees grew. The first query could actually perform better if there were few employees and many stores (and perhaps many of stores had no employees) and the daily_sales table was indexed on store_id. This is not a likely scenario but shows how a correlated query could possibly perform better than an alternative.

I've seen junior developers correlate subqueries many times and it usually has had a severe impact on performance. However, when removing a correlated subquery be sure to look at the explain plan before and after to make sure you are not making the performance worse.

How to get the Android device's primary e-mail address

Use this method:

 public String getUserEmail() {
    AccountManager manager = AccountManager.get(App.getInstance());
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<>();
    for (Account account : accounts) {
        possibleEmails.add(account.name);
    }
    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        return possibleEmails.get(0);
    }
    return "";
}

Note that this requires the GET_ACCOUNTS permission:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Then:

editTextEmailAddress.setText(getUserEmail());

React - How to pass HTML tags in props?

We can do the same thing in such a way.

const Child = () => {
  return (
     write your whole HTML here.
  )
}

now you want to send this HTML inside another component which name is Parent component.

Calling :-

<Parent child={<child/>} >
</Parent> 

Use Of Child:-

 const Parent = (props) => {
   const { child } = props; 
   return (
       {child}
    )
}

this work perfect for me.

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

Increasing the maximum post size

I had been facing similar problem in downloading big files this works fine for me now:

safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On

Hope this helps.

SQL Not Like Statement not working

If WPP.COMMENT contains NULL, the condition will not match.

This query:

SELECT  1
WHERE   NULL NOT LIKE '%test%'

will return nothing.

On a NULL column, both LIKE and NOT LIKE against any search string will return NULL.

Could you please post relevant values of a row which in your opinion should be returned but it isn't?

Sorting an array in C?

In your particular case the fastest sort is probably the one described in this answer. It is exactly optimized for an array of 6 ints and uses sorting networks. It is 20 times (measured on x86) faster than library qsort. Sorting networks are optimal for sort of fixed length arrays. As they are a fixed sequence of instructions they can even be implemented easily by hardware.

Generally speaking there is many sorting algorithms optimized for some specialized case. The general purpose algorithms like heap sort or quick sort are optimized for in place sorting of an array of items. They yield a complexity of O(n.log(n)), n being the number of items to sort.

The library function qsort() is very well coded and efficient in terms of complexity, but uses a call to some comparizon function provided by user, and this call has a quite high cost.

For sorting very large amount of datas algorithms have also to take care of swapping of data to and from disk, this is the kind of sorts implemented in databases and your best bet if you have such needs is to put datas in some database and use the built in sort.

How do I center floated elements?

Removing floats, and using inline-block may fix your problems:

 .pagination a {
-    display: block;
+    display: inline-block;
     width: 30px;
     height: 30px;
-    float: left;
     margin-left: 3px;
     background: url(/images/structure/pagination-button.png);
 }

(remove the lines starting with - and add the lines starting with +.)

_x000D_
_x000D_
.pagination {_x000D_
  text-align: center;_x000D_
}_x000D_
.pagination a {_x000D_
  + display: inline-block;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  margin-left: 3px;_x000D_
  background: url(/images/structure/pagination-button.png);_x000D_
}_x000D_
.pagination a.last {_x000D_
  width: 90px;_x000D_
  background: url(/images/structure/pagination-button-last.png);_x000D_
}_x000D_
.pagination a.first {_x000D_
  width: 60px;_x000D_
  background: url(/images/structure/pagination-button-first.png);_x000D_
}
_x000D_
<div class='pagination'>_x000D_
  <a class='first' href='#'>First</a>_x000D_
  <a href='#'>1</a>_x000D_
  <a href='#'>2</a>_x000D_
  <a href='#'>3</a>_x000D_
  <a class='last' href='#'>Last</a>_x000D_
</div>_x000D_
<!-- end: .pagination -->
_x000D_
_x000D_
_x000D_

inline-block works cross-browser, even on IE6 as long as the element is originally an inline element.

Quote from quirksmode:

An inline block is placed inline (ie. on the same line as adjacent content), but it behaves as a block.

this often can effectively replace floats:

The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.” ( http://www.quirksmode.org/css/display.html#inlineblock ).

From the W3C spec:

[inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.