Programs & Examples On #Nsdateformatter

Class that creates string representations of NSDate (and NSCalendarDate) objects, and convert textual representations of dates and times into NSDate objects.

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

    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"Your Date Format"];

set the format to return is....

yyyy-MM-dd return 2015-12-17 date

yyyy-MMM-dd return 2015-Dec-17 date

yy-MM-dd return 15-12-17 date

dd-MM-yy return 17-12-15 date

dd-MM-yyyy return 17-12-2015 date

yyyy-MMM-dd HH:mm:ss return 2015-Dec-17 08:07:13 date and time

yyyy-MMM-dd HH:mm return 2015-Dec-17 08:07 date and time

For more Details Data and Time Format for Click Now.

Thank you.....

Get current NSDate in timestamp format

use [[NSDate date] timeIntervalSince1970]

Convert NSDate to String in iOS Swift

You can use this extension:

extension Date {

    func toString(withFormat format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        let myString = formatter.string(from: self)
        let yourDate = formatter.date(from: myString)
        formatter.dateFormat = format

        return formatter.string(from: yourDate!)
    }
}

And use it in your view controller like this (replace <"yyyy"> with your format):

yourString = yourDate.toString(withFormat: "yyyy")

Xcode swift am/pm time to 24 hour format

let calendar = Calendar.current
let hours    = calendar.component(.hour, from: Date())
let minutes  = calendar.component(.minute, from: Date())
let seconds  = calendar.component(.second, from: Date())

Convert string to date in Swift

Swift 5. To see IF A DATE HAS PASSED:

let expiryDate = "2020-01-10" // Jan 10 2020

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

if Date() < dateFormatter.date(from: expiryDate) ?? Date() {
    print("Not Yet expiryDate")
} else {
    print("expiryDate has passed")
}

How to convert string to date to string in Swift iOS?

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

Swift 3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateFormatter.date(from: dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

The printed result is: Dateobj: 10-22-2015

Date Format in Swift

You have to declare 2 different NSDateFormatters, the first to convert the string to a NSDate and the second to print the date in your format.
Try this code:

let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))

Swift 3 and higher:

From Swift 3 NSDate class has been changed to Date and NSDateFormatter to DateFormatter.

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

Swift - iOS - Dates and times in different format

extension String {

    func convertDatetring_TopreferredFormat(currentFormat: String, toFormat : String) ->  String {
        let dateFormator = DateFormatter()
        dateFormator.dateFormat = currentFormat
        let resultDate = dateFormator.date(from: self)
        dateFormator.dateFormat = toFormat
        return dateFormator.string(from: resultDate!)
    }

}

Call from your view controller file as below.

"your_date_string".convertDatetring_TopreferredFormat(currentFormat: "yyyy-MM-dd HH:mm:ss.s", toFormat: "dd-MMM-yyyy h:mm a")

Get protocol, domain, and port from URL

None of these answers seem to completely address the question, which calls for an arbitrary url, not specifically the url of the current page.

Method 1: Use the URL API (caveat: no IE11 support)

You can use the URL API (not supported by IE11, but available everywhere else).

This also makes it easy to access search params. Another bonus: it can be used in a Web Worker since it doesn't depend on the DOM.

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

Method 2 (old way): Use the browser's built-in parser in the DOM

Use this if you need this to work on older browsers as well.

//  Create an anchor element (note: no need to append this element to the document)
const url = document.createElement('a');
//  Set href to any path
url.setAttribute('href', 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');

That's it!

The browser's built-in parser has already done its job. Now you can just grab the parts you need (note that this works for both methods above):

//  Get any piece of the url you're interested in
url.hostname;  //  'example.com'
url.port;      //  12345
url.search;    //  '?startIndex=1&pageSize=10'
url.pathname;  //  '/blog/foo/bar'
url.protocol;  //  'http:'

Bonus: Search params

Chances are you'll probably want to break apart the search url params as well, since '?startIndex=1&pageSize=10' isn't too useable on its own.

If you used Method 1 (URL API) above, you simply use the searchParams getters:

url.searchParams.get('startIndex');  // '1'

Or to get all parameters:

function searchParamsToObj(searchParams) {
  const paramsMap = Array
    .from(url.searchParams)
    .reduce((params, [key, val]) => params.set(key, val), new Map());
  return Object.fromEntries(paramsMap);
}
searchParamsToObj(url.searchParams);
// -> { startIndex: '1', pageSize: '10' }

If you used Method 2 (the old way), you can use something like this:

// Simple object output (note: does NOT preserve duplicate keys).
var params = url.search.substr(1); // remove '?' prefix
params
    .split('&')
    .reduce((accum, keyval) => {
        const [key, val] = keyval.split('=');
        accum[key] = val;
        return accum;
    }, {});
// -> { startIndex: '1', pageSize: '10' }

SCRIPT438: Object doesn't support property or method IE

In my case I had code like this:

function.call(context, arg);

I got error message under IE

TypeError: Object doesn't support property or method 'error'

In the body of 'function' I had "console.error" and it turns that console object is undefined when your console is closed. I have fixed this by checking if console and console.error are defined

How to find the width of a div using vanilla JavaScript?

The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.

function getStyleInfo() {
    setTimeout(function() {
        const style = window.getComputedStyle(document.getElementById('__root__'));
        if (style.height == 'auto') {
            getStyleInfo();
        }
        // IF we got here we can do actual business logic staff
        console.log(style.height, style.width);
    }, 100);
};

window.onload=function() { getStyleInfo(); };

If you use just

window.onload=function() {
    var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}

you can get auto values for width and height because browsers does not render till full load is performed.

Convert JS object to JSON string

If you're using AngularJS, the 'json' filter should do it:

<span>{{someObject | json}}</span>

How can I wrap or break long text/word in a fixed width span?

Like this

DEMO

  li span{
    display:block;
    width:50px;
    word-break:break-all;
}

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

In python, what is the difference between random.uniform() and random.random()?

Apart from what is being mentioned above, .uniform() can also be used for generating multiple random numbers that too with the desired shape which is not possible with .random()

np.random.seed(99)
np.random.random()

#generates 0.6722785586307918

while the following code

np.random.seed(99)
np.random.uniform(0.0, 1.0, size = (5,2))

#generates this 
array([[0.67227856, 0.4880784 ],
       [0.82549517, 0.03144639],
       [0.80804996, 0.56561742],
       [0.2976225 , 0.04669572],
       [0.9906274 , 0.00682573]])

This can't be done with random(...), and if you're generating the random(...) numbers for ML related things, most of the time, you'll end up using .uniform(...)

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

You can use the following maven dependency in your pom file. Otherwise, you can download the following two jars from net and add it to your build path.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.4</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.4</version>
</dependency>

This is copied from my working project. First make sure it is working in your project. Then you can change the versions to use any other(versions) compatible jars.

For AggCat, you can refer the POM file of the sample java application.

https://github.com/IntuitDeveloperRelations/IPP_Sample_Code/blob/master/CustomerAccountData/Java/AggCatSampleApplication/pom.xml

Thanks

How to group by month from Date field using sql

Use the DATEPART function to extract the month from the date.

So you would do something like this:

SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)

client denied by server configuration

in my case,

i'm using macOS Mojave (Apache/2.4.34). There was an issue in virtual host settings at /etc/apache2/extra/httpd-vhosts.conf file. after adding the required directory tag my problem was gone.

Require all granted

Hope the full virtual host setup structure will save you.

<VirtualHost *:80>
    DocumentRoot "/Users/vagabond/Sites/MainProjectFolderName/public/"
    ServerName project.loc

    <Directory /Users/vagabond/Sites/MainProjectFolderName/public/>
        Require all granted
    </Directory>

    ErrorLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-error_log"
    CustomLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-access_log" common
</VirtualHost>

all you've to do replace the MainProjectFolderName with your exact ProjectFolderName.

jQuery - getting custom attribute from selected option

Try This Example:

$("#location").change(function(){

    var tag = $("option[value="+$(this).val()+"]", this).attr('mytag');

    $('#setMyTag').val(tag); 

});

form serialize javascript (no framework)

For modern browsers only

If you target browsers that support the URLSearchParams API (most recent browsers) and FormData(formElement) constructor (most recent browsers), use this:

new URLSearchParams(new FormData(formElement)).toString()

Everywhere except IE

For browsers that support URLSearchParams but not the FormData(formElement) constructor, use this FormData polyfill and this code (works everywhere except IE):

new URLSearchParams(Array.from(new FormData(formElement))).toString()

Example

_x000D_
_x000D_
var form = document.querySelector('form');
var out = document.querySelector('output');

function updateResult() {
  try {
    out.textContent = new URLSearchParams(Array.from(new FormData(form)));
    out.className = '';
  } catch (e) {
    out.textContent = e;
    out.className = 'error';
  }
}

updateResult();
form.addEventListener('input', updateResult);
_x000D_
body { font-family: Arial, sans-serif; display: flex; flex-wrap: wrap; }
input[type="text"] { margin-left: 6px; max-width: 30px; }
label + label { margin-left: 10px; }
output { font-family: monospace; }
.error { color: #c00; }
div { margin-right: 30px; }
_x000D_
<!-- FormData polyfill for older browsers -->
<script src="https://unpkg.com/[email protected]/formdata.min.js"></script>
<div>
  <h3>Form</h3>
  <form id="form">
    <label>x:<input type="text" name="x" value="1"></label>
    <label>y:<input type="text" name="y" value="2"></label>
    <label>
    z:
    <select name="z">
      <option value="a" selected>a</option>
      <option value="b" selected>b</option>
    </select>
  </label>
  </form>
</div>
<div>
  <h3>Query string</h3>
  <output for="form"></output>
</div>
_x000D_
_x000D_
_x000D_

Compatible with IE 10

For even older browsers (e.g. IE 10), use the FormData polyfill, an Array.from polyfill if necessary and this code:

Array.from(
  new FormData(formElement),
  e => e.map(encodeURIComponent).join('=')
).join('&')

Get Current Session Value in JavaScript?

i tested this method and it worked for me. hope its useful.

assuming that you have a file named index.php
and when the user logs in, you store the username in a php session; ex. $_SESSION['username'];

you can do something like this in you index.php file

<script type='text/javascript'>
  var userName = "<?php echo $_SESSION['username'] ?>"; //dont forget to place the PHP code block inside the quotation 
</script>

now you can access the variable userId in another script block placed in the index.php file, or even in a .js file linked to the index.php

ex. in the index.js file

$(document).ready(function(){
    alert(userId);   
})

it could be very useful, since it enables us to use the username and other user data stoerd as cookies in ajax queries, for updating database tables and such.

if you dont want to use a javascript variable to contain the info, you can use an input with "type='hidden';

ex. in your index.php file, write:

<?php echo "<input type='hidden' id='username' value='".$_SESSION['username']."'/>";
?>

however, this way the user can see the hidden input if they ask the browser to show the source code of the page. in the source view, the hidden input is visible with its content. you may find that undesireble.

How to make a vertical line in HTML

I needed an inline vertical line, so I tricked a button into becoming a line.

<button type="button" class="v_line">l</button>

.v_line {
         width: 0px;
         padding: .5em .5px;
         background-color: black;
         margin: 0px; 4px;
        }

Pass mouse events through absolutely-positioned element

If you know the elements that need mouse events, and if your overlay is transparent, you can just set the z-index of them to something higher than the overlay. All events should of course work in that case on all browsers.

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

top nav bar blocking top content of the page

Adding a padding like that is not enough if you're using responsive bootstrap. In this case when you resize your window you'll get a gap between top of the page and navbar. A proper solution looks like this:

body {
  padding-top: 60px;
}
@media (max-width: 979px) {
  body {
    padding-top: 0px;
  }
}

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Rendering HTML in a WebView with custom CSS

You could use WebView.loadDataWithBaseURL

htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + htmlData;
// lets assume we have /assets/style.css file
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

And only after that WebView will be able to find and use css-files from the assets directory.

ps And, yes, if you load your html-file form the assets folder, you don't need to specify a base url.

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

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

import datetime, calendar

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

Node.js - get raw request body using Express

I got a solution that plays nice with bodyParser, using the verify callback in bodyParser. In this code, I am using it to get a sha1 of the content and also getting the raw body.

app.use(bodyParser.json({
    verify: function(req, res, buf, encoding) {

        // sha1 content
        var hash = crypto.createHash('sha1');
        hash.update(buf);
        req.hasha = hash.digest('hex');
        console.log("hash", req.hasha);

        // get rawBody        
        req.rawBody = buf.toString();
        console.log("rawBody", req.rawBody);

    }
}));

I am new in Node.js and express.js (started yesterday, literally!) so I'd like to hear comments on this solution.

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

Why is document.body null in my javascript?

document.body is not yet available when your code runs.

What you can do instead:

var docBody=document.getElementsByTagName("body")[0];
docBody.appendChild(mySpan);

Export to CSV via PHP

Just for the record, concatenation is waaaaaay faster (I mean it) than fputcsv or even implode; And the file size is smaller:

// The data from Eternal Oblivion is an object, always
$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);

// ----- fputcsv (slow)
// The code of @Alain Tiemblo is the best implementation
ob_start();
$csv = fopen("php://output", 'w');
fputcsv($csv, array_keys(reset($values)));
foreach ($values as $row) {
    fputcsv($csv, $row);
}
fclose($csv);
return ob_get_clean();

// ----- implode (slow, but file size is smaller)
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
foreach ($values as $row) {
    $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
}
return $csv;
// ----- concatenation (fast, file size is smaller)
// We can use one implode for the headers =D
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
$i = 1;
// This is less flexible, but we have more control over the formatting
foreach ($values as $row) {
    $csv .= '"' . $row['id'] . '",';
    $csv .= '"' . $row['name'] . '",';
    $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
    $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
    $csv .= PHP_EOL;
}
return $csv;

This is the conclusion of the optimization of several reports, from ten to thousands rows. The three examples worked fine under 1000 rows, but fails when the data was bigger.

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

Hiding a button in Javascript

visibility=hidden

is very useful, but it will still take up space on the page. You can also use

display=none

because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")

How do I make WRAP_CONTENT work on a RecyclerView

Simply put your RecyclerView inside a NestedScrollView. Works perfectly

<android.support.v4.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="25dp">
                <android.support.v7.widget.RecyclerView
                    android:id="@+id/kliste"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </android.support.v4.widget.NestedScrollView>

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

function to remove duplicate characters in a string

I have written a piece of code to solve the problem. I have checked with certain values, got the required output.

Note: It's time consuming.

static void removeDuplicate(String s) {

    char s1[] = s.toCharArray();

    Arrays.sort(s1);                    //Sorting is performed, a to z
                //Since adjacent values are compared

    int myLength = s1.length;           //Length of the character array is stored here

    int i = 0;                          //i refers to the position of original char array
    int j = 0;          //j refers to the position of char array after skipping the duplicate values 

    while(i != myLength-1 ){

        if(s1[i]!=s1[i+1]){     //Compares two adjacent characters, if they are not the same
            s1[j] = s1[i];      //if not same, then, first adjacent character is stored in s[j]
            s1[j+1] = s1[i+1];  //Second adjacent character is stored in s[j+1]
            j++;                //j is incremented to move to next location
        }

        i++;                    //i is incremented
    }

    //the length of s is i. i>j

    String s4 = new String (s1);        //Char Array to String

    //s4[0] to s4[j+1] contains the length characters after removing the duplicate
    //s4[j+2] to s4[i] contains the last set of characters of the original char array

    System.out.println(s4.substring(0, j+1));

}

Feel free to run my code with your inputs. Thanks.

Android - border for button

Android Official Solution

Since Android Design Support v28 was introduced, it's easy to create a bordered button using MaterialButton. This class supplies updated Material styles for the button in the constructor. Using app:strokeColor and app:strokeWidth you can create a custom border as following:


1. When you use androidx:

build.gradle

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
}

• Bordered Button:

<com.google.android.material.button.MaterialButton
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="MATERIAL BUTTON"
    android:textSize="15sp"
    app:strokeColor="@color/green"
    app:strokeWidth="2dp" />

• Unfilled Bordered Button:

<com.google.android.material.button.MaterialButton
    style="@style/Widget.AppCompat.Button.Borderless"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="UNFILLED MATERIAL BUTTON"
    android:textColor="@color/green"
    android:textSize="15sp"
    app:backgroundTint="@android:color/transparent"
    app:cornerRadius="8dp"
    app:rippleColor="#33AAAAAA"
    app:strokeColor="@color/green"
    app:strokeWidth="2dp" />



2. When you use appcompat:

build.gradle

dependencies {
    implementation 'com.android.support:design:28.0.0'
}

style.xml

Ensure your application theme inherits from Theme.MaterialComponents instead of Theme.AppCompat.

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

• Bordered Button:

<android.support.design.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="MATERIAL BUTTON"
    android:textSize="15sp"
    app:strokeColor="@color/green"
    app:strokeWidth="2dp" />

• Unfilled Bordered Button:

<android.support.design.button.MaterialButton
    style="@style/Widget.AppCompat.Button.Borderless"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="UNFILLED MATERIAL BUTTON"
    android:textColor="@color/green"
    android:textSize="15sp"
    app:backgroundTint="@android:color/transparent"
    app:cornerRadius="8dp"
    app:rippleColor="#33AAAAAA"
    app:strokeColor="@color/green"
    app:strokeWidth="2dp" />



Visual Result

enter image description here

mysql said: Cannot connect: invalid settings. xampp

I made changes to the config file for Laravel and completely forgot the changes. After applying everything from this thread, I had no success.

I simply overwrote the config.inc file from another xampp installation and it worked fine.

delete all record from table in mysql

truncate tableName

That is what you are looking for.

Truncate will delete all records in the table, emptying it.

Create a day-of-week column in a Pandas dataframe using Python

Just in case if .dt doesn't work for you. Trying .DatetimeIndex might help. Hope the code and our test result here help you fix it. Regards,

import pandas as pd
import datetime

df = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03'],'Number':[1,2,3]})

df['Day'] = pd.DatetimeIndex(df['Date']).day_name() # week day name
df.head()

enter image description here

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Select All as default value for Multivalue parameter

It works better

CREATE TABLE [dbo].[T_Status](
   [Status] [nvarchar](20) NULL
) ON [PRIMARY]

GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO

DECLARE @GetStatus nvarchar(20) = null
--DECLARE @GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE  [Status] = CASE WHEN (isnull(@GetStatus, '')='') THEN [Status]
ELSE @GetStatus END

how to stop a running script in Matlab

Since you mentioned Task Manager, I'll guess you're using Windows. Assuming you're running your script within the editor, if you aren't opposed to quitting the editor at the same time as quitting the running program, the keyboard shortcut to end a process is:

Alt + F4

(By which I mean press the 'Alt' and 'F4' keys on your keyboard simultaneously.)

Alternatively, as mentioned in other answers,

Ctrl + C

should also work, but will not quit the editor.

Using setImageDrawable dynamically to set image in an ImageView

I personally prefer to use the method setImageResource() like this.

ImageView myImageView = (ImageView)findViewById(R.id.myImage);
myImageView.setImageResource(R.drawable.icon);

Add vertical whitespace using Twitter Bootstrap?

I know this is old, but I came here searching for the same thing, I found that Bootstrap has the help-block, very handy for these situations:

<div class="help-block"></div>

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I think to troubleshoot your problem you should try the following:

  1. Check whether the MySQL service is running (Control Panel --> services)
  2. Use a MySQL client like SQLYOG to check whether you are able to connect to MYSQL Server with the username and password you are using in your code.
  3. Just try a sample php program, which fetches the data from table Ex. http://www.anyexample.com/programming/php/php_mysql_example__display_table_as_html.xml

AngularJS - Animate ng-view transitions

Check this code:

Javascript:

app.config( ["$routeProvider"], function($routeProvider){
    $routeProvider.when("/part1", {"templateUrl" : "part1"});
    $routeProvider.when("/part2", {"templateUrl" : "part2"});
    $routeProvider.otherwise({"redirectTo":"/part1"});
  }]
);

function HomeFragmentController($scope) {
    $scope.$on("$routeChangeSuccess", function (scope, next, current) {
        $scope.transitionState = "active"
    });
}

CSS:

.fragmentWrapper {
    overflow: hidden;
}

.fragment {
    position: relative;
    -moz-transition-property: left;
    -o-transition-property: left;
    -webkit-transition-property: left;
    transition-property: left;
    -moz-transition-duration: 0.1s;
    -o-transition-duration: 0.1s;
    -webkit-transition-duration: 0.1s;
    transition-duration: 0.1s
}

.fragment:not(.active) {
    left: 540px;
}

.fragment.active {
    left: 0px;
}

Main page HTML:

<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>

Partials HTML example:

<div id="part1" class="fragment {{transitionState}}">
</div>

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

Problems with Android Fragment back stack

I know it's a old quetion but i got the same problem and fix it like this:

First, Add Fragment1 to BackStack with a name (e.g "Frag1"):

frag = new Fragment1();

transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.addToBackStack("Frag1");
transaction.commit();

And then, Whenever you want to go back to Fragment1 (even after adding 10 fragments above it), just call popBackStackImmediate with the name:

getSupportFragmentManager().popBackStackImmediate("Frag1", 0);

Hope it will help someone :)

How to extract year and month from date in PostgreSQL without using to_char() function?

Use the date_trunc method to truncate off the day (or whatever else you want, e.g., week, year, day, etc..)

Example of grouping sales from orders by month:

select
  SUM(amount) as sales,
  date_trunc('month', created_at) as date
from orders
group by date
order by date DESC;

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

See here for variations: https://en.cppreference.com/w/cpp/language/range-for

How to detect if URL has changed after hash in JavaScript

I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url

I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url

// on-url-change.js v1 (manual verification)
let onUrlChangeCallbacks = [];
let onUrlChangeTimestamp = new Date() * 1;
function onUrlChange(callback){
    onUrlChangeCallbacks.push(callback);
};
onUrlChangeAutorun();
function onUrlChangeAutorun(){
    let oldURL = window.location.href;
    setInterval(function(){
        let newURL = window.location.href;
        if(oldURL !== newURL){
            let event = {
                oldURL: oldURL,
                newURL: newURL,
                type: 'urlchange',
                timestamp: new Date() * 1 - onUrlChangeTimestamp
            };
            oldURL = newURL;
            for(let i = 0; i < onUrlChangeCallbacks.length; i++){
                onUrlChangeCallbacks[i](event);
            };
        };
    }, 25);
};

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.

Best way to check if a Data Table has a null value in it

You can loop throw the rows and columns, checking for nulls, keeping track of whether there's a null with a bool, then check it after looping through the table and handle it.

//your DataTable, replace with table get code
DataTable table = new DataTable();
bool tableHasNull = false;

foreach (DataRow row in table.Rows)
{
    foreach (DataColumn col in table.Columns)
    {
        //test for null here
        if (row[col] == DBNull.Value)
        {
            tableHasNull = true;
        }
    }
}

if (tableHasNull)
{
    //handle null in table
}

You can also come out of the foreach loop with a break statement e.g.

//test for null here
if (row[col] == DBNull.Value)
{
    tableHasNull = true;
    break;
}

To save looping through the rest of the table.

How to stop event bubbling on checkbox click

When using jQuery you do not need to call a stop function separate.

You can just return false in the event handler

This will stop the event and cancel bubbling..

Also see event.preventDefault() vs. return false

From the jQuery docs:

These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?

If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.

Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.

How to display hexadecimal numbers in C?

Your code has no problem. It does print the way you want. Alternatively, you can do this:

printf("%04x",a);

Python object.__repr__(self) should be an expression?

I think the confusion over here roots from the english. I mean __repr__(); short for 'representation' of the value I'm guessing, like @S.Lott said

"What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same."

But in some cases they might be different. E.g; coordinate points, you might want c.coordinate to return: 3,5 but c.__repr__ to return Coordinate(3, 5). Hope that makes more sense...

How to stop BackgroundWorker correctly

The problem is caused by the fact that cmbDataSourceExtractor.CancelAsync() is an asynchronous method, the Cancel operation has not yet completed when cmdDataSourceExtractor.RunWorkerAsync(...) exitst. You should wait for cmdDataSourceExtractor to complete before calling RunWorkerAsync again. How to do this is explained in this SO question.

Get a CSS value with JavaScript

You can use getComputedStyle().

var element = document.getElementById('image_1'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');

jsFiddle.

Map with Key as String and Value as List in Groovy

Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

// Java syntax 

Map<String,List> map1  = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1); 
assert map1.get("abc") == list1;

// slightly less Java-esque

def map2  = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2

// typical Groovy

def map3  = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3

How to set default values for Angular 2 component properties?

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component. And the interesting part it will be changed before component will be initialized.

Let's say we have such components with two lifecycle hooks and one property coming from input.

@Component({
  selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {
    console.log('Changed', changes.property.currentValue, changes.property.previousValue);
  }

  ngOnInit() {
    console.log('Init', this.property);
  }

}

Situation 1

Component included in html without defined property value

As result we will see in console: Init default

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

Situation 2

Component included in html with setted property <cmp [property]="'new value'"></cmp>

As result we will see in console:

Changed new value Object {}

Init new value

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

How to use aria-expanded="true" to change a css property

You could use querySelector() with attribute selector '[attribute="value"]', then affect css rule using .style, as you can see in the example below:

_x000D_
_x000D_
document.querySelector('a[aria-expanded="true"]').style.backgroundColor = "#42DCA3";
_x000D_
<ul><li class="active">_x000D_
  <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+ with aria expanded true</span></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+ with aria expanded false</span></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jQuery solution :

If you want to use a jQuery solution you could simply use css() method :

$('a[aria-expanded="true"]').css('background-color','#42DCA3');

Hope this helps.

How can I develop for iPhone using a Windows development machine?

You can install OSX on PC but experience wont be great and it needs lot of work. Alternate is to use a framework/SDK Codename one: which is based on JAVA and can be used to code in WP8, Android, iOS on Windows (eclipse) with all extensive features

Features Overview:

  1. Full Android environment with super fast android simulator
  2. An iPhone/iPad simulator with easy to take iPhone apps to large screen iPad in minutes.
  3. Full support for standard java debugging, profiling for apps on any platform.
  4. Easy themeing / styling – Only a click away

More at Develop Android, iOS iPhone, WP8 apps using Java Disclaimer: This is my review for the product

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

Is it a good practice to use try-except-else in Python?

You should be careful about using the finally block, as it is not the same thing as using an else block in the try, except. The finally block will be run regardless of the outcome of the try except.

In [10]: dict_ = {"a": 1}

In [11]: try:
   ....:     dict_["b"]
   ....: except KeyError:
   ....:     pass
   ....: finally:
   ....:     print "something"
   ....:     
something

As everyone has noted using the else block causes your code to be more readable, and only runs when an exception is not thrown

In [14]: try:
             dict_["b"]
         except KeyError:
             pass
         else:
             print "something"
   ....:

How do I clear the std::queue efficiently?

In C++11 you can clear the queue by doing this:

std::queue<int> queue;
// ...
queue = {};

Disable/turn off inherited CSS3 transitions

Based on W3schools default transition value is: all 0s ease 0s, which should be the cross-browser compatible way of disabling the transition.

Here is a link: https://www.w3schools.com/cssref/css3_pr_transition.asp

AngularJS - How can I do a redirect with a full page load?

Try this

$window.location.href="#page-name";
$window.location.reload();

Windows command to get service status?

Well i see "Nick Kavadias" telling this:

"according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST ..."

If you type in Windows XP this:

NET START /LIST

you will get an error, just type instead

NET START

The /LIST is only for Windows 2000... If you fully read such web you would see the /LIST is only on Windows 2000 section.

Hope this helps!!!

Duplicate line in Visual Studio Code

Update that may help Ubuntu users if they still want to use the ? and ? instead of another set of keys.

I just installed a fresh version of VSCode on Ubuntu 18.04 LTS and I had duplicate commands for Add Cursor Above and Add Cursor Below

Original Keybindings

I just removed the bindings that used Ctrl and added my own with the following

Copy Line Up

Ctrl + Shift + ?

Copy Line Down

Ctrl + Shift + ?

New Keybindings

Rounded corners for <input type='text' /> using border-radius.htc for IE

That won't work in IE<9 though, however, you can make IEs support that using:

CSS3Pie

PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.

Check if an apt-get package is installed and then install it if it's not on Linux

Many things has been told but for me simplest way is:

dpkg -l | grep packagename

How much memory can a 32 bit process access on a 64 bit operating system?

The limit is not 2g or 3gb its 4gb for 32bit.

The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.

Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.

4Gig not 3 not 2 got it?

Get response from PHP file using AJAX

The good practice is to use like this:

$.ajax({
    type: "POST",
    url: "/ajax/request.html",
    data: {action: 'test'},
    dataType:'JSON', 
    success: function(response){
        console.log(response.blablabla);
        // put on console what server sent back...
    }
});

and the php part is:

<?php
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        echo json_encode(array("blablabla"=>$variable));
    }
?>

How do I check if an index exists on a table field in MySQL?

SHOW KEYS FROM  tablename WHERE Key_name='unique key name'

you can find if there exists an unique key in the table

How to capture the android device screen content?

AFAIK, All of the methods currently to capture a screenshot of android use the /dev/graphics/fb0 framebuffer. This includes ddms. It does require root to read from this stream. ddms uses adbd to request the information, so root is not required as adb has the permissions needed to request the data from /dev/graphics/fb0.

The framebuffer contains 2+ "frames" of RGB565 images. If you are able to read the data, you would have to know the screen resolution to know how many bytes are needed to get the image. each pixel is 2 bytes, so if the screen res was 480x800, you would have to read 768,000 bytes for the image, since a 480x800 RGB565 image has 384,000 pixels.

setTimeout / clearTimeout problems

This works well. It's a manager I've made to handle hold events. Has events for hold, and for when you let go.

function onUserHold(element, func, hold, clearfunc) {
    //var holdTime = 0;
    var holdTimeout;

    element.addEventListener('mousedown', function(e) {
        holdTimeout = setTimeout(function() {
            func();
            clearTimeout(holdTimeout);
            holdTime = 0;
        }, hold);
        //alert('UU');
    });

    element.addEventListener('mouseup', clearTime);
    element.addEventListener('mouseout', clearTime);

    function clearTime() {
        clearTimeout(holdTimeout);
        holdTime = 0;
        if(clearfunc) {
            clearfunc();
        }
    }
}

The element parameter is the one which you hold. The func parameter fires when it holds for a number of milliseconds specified by the parameter hold. The clearfunc param is optional and if it is given, it will get fired if the user lets go or leaves the element. You can also do some work-arounds to get the features you want. Enjoy! :)

Can't start hostednetwork

First off, when I went into cmd and typed "netsh wlan show drivers", I had a NO for hosted network support too. Doesn't matter, you can still do it. Just not in cmd.

I think this problem happens because they changed the way hosted networks work in windows 10. Don't use command line.

Just go on your pc to settings>Network>Mobile Hotspot and you should see all the necessary settings there. Turn it on, set up your network.

If it's still not working, go to Control panel>Network and Internet>Network and Sharing Center>Change Adapter Options> and then click on the properties of the network adapter that you want to share. Go to the sharing tab, and share that internet connection, selecting the name of the adapter you want to use to share it with.

Dictionary with list of strings as value

Just create a new array in your dictionary

Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));

Read Numeric Data from a Text File in C++

you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    double data[size of your data];

    std::ifstream input("file.txt");

    for (int i = 0; i < size of your data; i++) {
        input >> data[i];
        std::cout<< data[i]<<std::endl;
        }

}

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

I found it useful (where I wanted to ignore line feeds and not change any files) to ignore them in the .eslintrc using linebreak-style as per this answer: https://stackoverflow.com/a/43008668/1129108

module.exports = {
  extends: 'google',
  quotes: [2, 'single'],
  globals: {
    SwaggerEditor: false
  },
  env: {
    browser: true
  },
  rules:{
    "linebreak-style": 0
  }
};

Cordova app not displaying correctly on iPhone X (Simulator)

There is 3 steps you have to do

for iOs 11 status bar & iPhone X header problems


1. Viewport fit cover

Add viewport-fit=cover to your viewport's meta in <header>

<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0,viewport-fit=cover">

Demo: https://jsfiddle.net/gq5pt509 (index.html)


  1. Add more splash images to your config.xml inside <platform name="ios">

Dont skip this step, this required for getting screen fit for iPhone X work

<splash src="your_path/Default@2x~ipad~anyany.png" />   <!-- 2732x2732 -->
<splash src="your_path/Default@2x~ipad~comany.png" />   <!-- 1278x2732 -->
<splash src="your_path/Default@2x~iphone~anyany.png" /> <!-- 1334x1334 -->
<splash src="your_path/Default@2x~iphone~comany.png" /> <!-- 750x1334  -->
<splash src="your_path/Default@2x~iphone~comcom.png" /> <!-- 1334x750  -->
<splash src="your_path/Default@3x~iphone~anyany.png" /> <!-- 2208x2208 -->
<splash src="your_path/Default@3x~iphone~anycom.png" /> <!-- 2208x1242 -->
<splash src="your_path/Default@3x~iphone~comany.png" /> <!-- 1242x2208 -->

Demo: https://jsfiddle.net/mmy885q4 (config.xml)


  1. Fix your style on CSS

Use safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, or safe-area-inset-bottom

Example: (Use in your case!)

#header {
   position: fixed;
   top: 1.25rem; // iOs 10 or lower
   top: constant(safe-area-inset-top); // iOs 11
   top: env(safe-area-inset-top); // iOs 11+ (feature)

   // or use calc()
   top: calc(constant(safe-area-inset-top) + 1rem);
   top: env(constant(safe-area-inset-top) + 1rem);
  
   // or SCSS calc()
   $nav-height: 1.25rem;
   top: calc(constant(safe-area-inset-top) + #{$nav-height});
   top: calc(env(safe-area-inset-top) + #{$nav-height});
}

Bonus: You can add body class like is-android or is-ios on deviceready

var platformId = window.cordova.platformId;
if (platformId) {
   document.body.classList.add('is-' + platformId);
}

So you can do something like this on CSS

.is-ios #header {
 // Properties
}

jQuery selector to get form by name

For detecting if the form is present, I'm using

if($('form[name="frmSave"]').length > 0) {
    //do something
}

What is the difference between . (dot) and $ (dollar sign)?

Haskell: difference between . (dot) and $ (dollar sign)

What is the difference between the dot (.) and the dollar sign ($)?. As I understand it, they are both syntactic sugar for not needing to use parentheses.

They are not syntactic sugar for not needing to use parentheses - they are functions, - infixed, thus we may call them operators.

Compose, (.), and when to use it.

(.) is the compose function. So

result = (f . g) x

is the same as building a function that passes the result of its argument passed to g on to f.

h = \x -> f (g x)
result = h x

Use (.) when you don't have the arguments available to pass to the functions you wish to compose.

Right associative apply, ($), and when to use it

($) is a right-associative apply function with low binding precedence. So it merely calculates the things to the right of it first. Thus,

result = f $ g x

is the same as this, procedurally (which matters since Haskell is evaluated lazily, it will begin to evaluate f first):

h = f
g_x = g x
result = h g_x

or more concisely:

result = f (g x)

Use ($) when you have all the variables to evaluate before you apply the preceding function to the result.

We can see this by reading the source for each function.

Read the Source

Here's the source for (.):

-- | Function composition.
{-# INLINE (.) #-}
-- Make sure it has TWO args only on the left, so that it inlines
-- when applied to two functions, even if there is no final argument
(.)    :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)

And here's the source for ($):

-- | Application operator.  This operator is redundant, since ordinary
-- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
-- low, right-associative binding precedence, so it sometimes allows
-- parentheses to be omitted; for example:
--
-- >     f $ g $ h x  =  f (g (h x))
--
-- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
-- or @'Data.List.zipWith' ('$') fs xs@.
{-# INLINE ($) #-}
($)                     :: (a -> b) -> a -> b
f $ x                   =  f x

Conclusion

Use composition when you do not need to immediately evaluate the function. Maybe you want to pass the function that results from composition to another function.

Use application when you are supplying all arguments for full evaluation.

So for our example, it would be semantically preferable to do

f $ g x

when we have x (or rather, g's arguments), and do:

f . g

when we don't.

Could not locate Gemfile

Make sure you are in the project directory before running bundle install. For example, after running rails new myproject, you will want to cd myproject before running bundle install.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How to break out of the IF statement

I think I know why people would want this. "Run stuff if all conditions are true, otherwise run other stuff". And the conditions are too complicated to put into one if.

Just use a lambda!

if (new Func<bool>(() =>
{
    if (something1)
    {
        if (something2)
        {
            return true;
        }
    }
    return false;
})())
{
    //do stuff
}

How to test if parameters exist in rails

if params[:one] && params[:two]
 ... do something ...
elsif params[:one]
 ... do something ...
end

Deleting array elements in JavaScript - delete vs splice

If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.

You can do it by building a new array. e.g

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

But I don't think you can modify the key values in the original array, which would be more efficient - it looks like you might have to create a new array.

Note that you don't need to check for the "undefined" entries as they don't actually exist and the for loop doesn't return them. It's an artifact of the array printing that displays them as undefined. They don't appear to exist in memory.

It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?


Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},

How to merge two files line by line in Bash

here's non-paste methods

awk

awk 'BEGIN {OFS=" "}{
  getline line < "file2"
  print $0,line
} ' file1

Bash

exec 6<"file2"
while read -r line
do
    read -r f2line <&6
    echo "${line}${f2line}"
done <"file1"
exec 6<&-

how to use math.pi in java

Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it

Ex:

diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");

Regular expression which matches a pattern, or is an empty string

\b matches a word boundary. I think you can use ^$ for empty string.

What is a Memory Heap?

You probably mean heap memory, not memory heap.

Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.

It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.

how to get selected row value in the KendoUI

If you want to select particular element use below code

var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];

When to use a View instead of a Table?

Oh there are many differences you will need to consider

Views for selection:

  1. Views provide abstraction over tables. You can add/remove fields easily in a view without modifying your underlying schema
  2. Views can model complex joins easily.
  3. Views can hide database-specific stuff from you. E.g. if you need to do some checks using Oracles SYS_CONTEXT function or many other things
  4. You can easily manage your GRANTS directly on views, rather than the actual tables. It's easier to manage if you know a certain user may only access a view.
  5. Views can help you with backwards compatibility. You can change the underlying schema, but the views can hide those facts from a certain client.

Views for insertion/updates:

  1. You can handle security issues with views by using such functionality as Oracle's "WITH CHECK OPTION" clause directly in the view

Drawbacks

  1. You lose information about relations (primary keys, foreign keys)
  2. It's not obvious whether you will be able to insert/update a view, because the view hides its underlying joins from you

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to use PHP to connect to sql server

MS SQL connect to php

  1. Install the drive from microsoft link https://www.microsoft.com/en-us/download/details.aspx?id=20098

  2. After install you will get some files. Store it in your system temp folder

  3. Check your php version , thread or non thread , and window bit - 32 or 64 (Thread or non thread , this is get you by phpinfo() )

  4. According to your system & xampp configration (php version and all ) copy 2 files (php_sqlsrv & php_pdo_sqlsrv) to xampp/php/ext folder .

  5. Add to php.ini file extension=php_sqlsrv_72_ts_x64 (php_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step ) extension=php_pdo_sqlsrv_72_ts_x64 (php_pdo_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step )

  6. Next Php Code

    $serverName ="DESKTOP-me\MSSQLSERVER01"; (servername\instanceName)

    // Since UID and PWD are not specified in the $connectionInfo array, // The connection will be attempted using Windows Authentication.

    $connectionInfo = array("Database"=>"testdb","CharacterSet"=>"UTF-8");

    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    if( $conn ) { //echo "Connection established.
    "; }else{ echo "Connection could not be established.
    "; die( print_r( sqlsrv_errors(), true)); }

    //$sql = "INSERT INTO dbo.master ('name') VALUES ('test')"; $sql = "SELECT * FROM dbo.master"; $stmt = sqlsrv_query( $conn, $sql );

    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) { echo $row['id'].", ".$row['name']."
    "; }

    sqlsrv_free_stmt( $stmt);

Read line by line in bash script

xargs is the most flexible solution for splitting output into command arguments.

It is also very human readable and easy to use due to its simple parameterisation.

Format is xargs -n $NUMLINES mycommand.

For example, to echo each individual line in a file /tmp/tmp.txt you'd do:

cat /tmp/tmp.txt | xargs -n 1 echo

Or to diff each successive pair of files listed as lines in a file of the above name you'd do:

cat /tmp/tmp.txt | xargs -n 2 diff

The -n 2 instructs xargs to consume and pass as separate arguments two lines of what you've piped into it at a time.

You can tailor xargs to split on delimiters besides carriage return/newline.

Use man xargs and google to find out more about the power of this versatile utility.

C++ equivalent of StringBuffer/StringBuilder?

You can use .append() for simply concatenating strings.

std::string s = "string1";
s.append("string2");

I think you might even be able to do:

std::string s = "string1";
s += "string2";

As for the formatting operations of C#'s StringBuilder, I believe snprintf (or sprintf if you want to risk writing buggy code ;-) ) into a character array and convert back to a string is about the only option.

What are XAND and XOR

XOR behaves like Austin explained, as an exclusive OR, either A or B but not both and neither yields false.

There are 16 possible logical operators for two inputs since the truth table consists of 4 combinations there are 16 possible ways to arrange two boolean parameters and the corresponding output.

They all have names according to this wikipedia article

mysqli::query(): Couldn't fetch mysqli

Probably somewhere you have DBconnection->close(); and then some queries try to execute .


Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

How can I get relative path of the folders in my android project?

Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images. I found in search that in JAVA, we can get path from Root to folder which we specify as,

String myStorageFolder= "/images"; // this is folder name in where I want to store files.

String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);

Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,

C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images

How to get href value using jQuery?

You can get current href value by this code:

$(this).attr("href");

To get href value by ID

$("#mylink").attr("href");

How to display div after click the button in Javascript?

<div  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Typical error on Windows because the default user directory is C:\user\<your_user>, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u is a Unicode escape. Any character not numeric after this produces an error.

To solve it, just double the backslashes: C:\\user\\<\your_user>...

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

To the power of in C?

just use pow(a,b),which is exactly 3**4 in python

C++ equivalent of java's instanceof

Depending on what you want to do you could do this:

template<typename Base, typename T>
inline bool instanceof(const T*) {
    return std::is_base_of<Base, T>::value;
}

Use:

if (instanceof<BaseClass>(ptr)) { ... }

However, this purely operates on the types as known by the compiler.

Edit:

This code should work for polymorphic pointers:

template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
    return dynamic_cast<const Base*>(ptr) != nullptr;
}

Example: http://cpp.sh/6qir

bootstrap datepicker setDate format dd/mm/yyyy

Try this

 format: 'DD/MM/YYYY hh:mm A'

As we all know JS is case-sensitive. So this will display

10/05/2016 12:00 AM

In your case is

format: 'DD/MM/YYYY'

Display : 10/05/2016

My bootstrap datetimepicker is based on eonasdan bootstrap-datetimepicker

Get OS-level system information

Add OSHI dependency via maven:

<dependency>
    <groupId>com.github.dblock</groupId>
    <artifactId>oshi-core</artifactId>
    <version>2.2</version>
</dependency>

Get a battery capacity left in percentage:

SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
for (PowerSource pSource : hal.getPowerSources()) {
    System.out.println(String.format("%n %s @ %.1f%%", pSource.getName(), pSource.getRemainingCapacity() * 100d));
}

Difference between F5, Ctrl + F5 and click on refresh button?

F5 triggers a standard reload.

Ctrl + F5 triggers a forced reload. This causes the browser to re-download the page from the web server, ensuring that it always has the latest copy.

Unlike with F5, a forced reload does not display a cached copy of the page.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

This was totally my bad.

I was using standard node http.request on a part of the code which should be sending requests to only http adresses. Seems like the db had a single https address which was queried with a random interval.

Simply, I was trying to send a http request to https.

How to find foreign key dependencies in SQL Server?

try: sp_help [table_name]

you will get all information about table, including all foreign keys

Char array to hex string C++

Code snippet above provides incorrect byte order in string, so I fixed it a bit.

char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',   'B','C','D','E','F'};

std::string byte_2_str(char* bytes, int size) {
  std::string str;
  for (int i = 0; i < size; ++i) {
    const char ch = bytes[i];
    str.append(&hex[(ch  & 0xF0) >> 4], 1);
    str.append(&hex[ch & 0xF], 1);
  }
  return str;
}

"Could not find a version that satisfies the requirement opencv-python"

Another problem can be that the python version you are using is not yet supported by opencv-python.

E.g. as of right now there is no opencv-python for python 3.8. You would need to downgrade your python to 3.7.5 for now.

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

You have to load the missing php3 (Python3) modules from the package manager. If you have Ubuntu I recommend the Synaptic Package Manager:

sudo apt-get install synaptic

There you can simply search for the missing modules. search for ctypes and install all the packages. Then go to your Python dir and do

./configure
make install.

This should solve your problem.

how to initialize a char array?

Absent a really good reason to do otherwise, I'd probably use:

std::vector<char> msg(65546, '\0');

Error: unable to verify the first certificate in nodejs

This actually solved it for me, from https://www.npmjs.com/package/ssl-root-cas

// INCORRECT (but might still work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('cert.pem', 'ascii') // a PEM containing ONLY the SERVER certificate
});

// CORRECT (should always work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('fullchain.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
});

Delete files older than 3 months old in a directory using .NET

An SSIS type of example .. (if this helps anyone)

          public void Main()
          {
                 // TODO: Add your code here
        // Author: Allan F 10th May 2019

        //first part of process .. put any files of last Qtr (or older) in Archive area 
        //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 31March2019 will be archived

        //string SourceFileFolder = "\\\\adlsaasf11\\users$\\aford05\\Downloads\\stage\\";
        string SourceFilesFolder = (string)Dts.Variables["SourceFilesFolder"].Value;
        string ArchiveFolder = (string)Dts.Variables["ArchiveFolder"].Value;
        string FilePattern = (string)Dts.Variables["FilePattern"].Value;
        string[] files = Directory.GetFiles(SourceFilesFolder, FilePattern);

        //DateTime date = new DateTime(2019, 2, 15);//commented out line .. just for testing the dates .. 

        DateTime date = DateTime.Now;
        int quarterNumber = (date.Month - 1) / 3 + 1;
        DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber - 1) * 3 + 1, 1);
        DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1);

        DateTime LastDayOfPriorQuarter = firstDayOfQuarter.AddDays(-1);
        int PrevQuarterNumber = (LastDayOfPriorQuarter.Month - 1) / 3 + 1;
        DateTime firstDayOfLastQuarter = new DateTime(LastDayOfPriorQuarter.Year, (PrevQuarterNumber - 1) * 3 + 1, 1);
        DateTime lastDayOfLastQuarter = firstDayOfLastQuarter.AddMonths(3).AddDays(-1);

        //MessageBox.Show("debug pt2: firstDayOfQuarter" + firstDayOfQuarter.ToString("dd/MM/yyyy"));
        //MessageBox.Show("debug pt2: firstDayOfLastQuarter" + firstDayOfLastQuarter.ToString("dd/MM/yyyy"));


        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);

            //MessageBox.Show("debug pt2:" + fi.Name + " " + fi.CreationTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastAccessTime.ToString("dd/MM/yyyy HH:mm") + " " + fi.LastWriteTime.ToString("dd/MM/yyyy HH:mm"));
            if (fi.LastWriteTime < firstDayOfQuarter)
            {

                try
                {

                    FileInfo fi2 = new FileInfo(ArchiveFolder);

                    //Ensure that the target does not exist.
                    //fi2.Delete();

                    //Copy the file.
                    fi.CopyTo(ArchiveFolder + fi.Name);
                    //Console.WriteLine("{0} was copied to {1}.", path, ArchiveFolder);

                    //Delete the old location file.
                    fi.Delete();
                    //Console.WriteLine("{0} was successfully deleted.", ArchiveFolder);

                }
                catch (Exception e)
                {
                    //do nothing
                    //Console.WriteLine("The process failed: {0}", e.ToString());
                }
            }
        }

        //second part of process .. delete any files in Archive area dated earlier than last qtr ..
        //e.g. if today is 10May2019 then last quarter is 1Jan2019 to 31March2019 .. any files earlier than 1Jan2019 will be deleted

        string[] archivefiles = Directory.GetFiles(ArchiveFolder, FilePattern);
        foreach (string archivefile in archivefiles)
        {
            FileInfo fi = new FileInfo(archivefile);
            if (fi.LastWriteTime < firstDayOfLastQuarter )
            {
                try
                {
                    fi.Delete();
                }
                catch (Exception e)
                {
                    //do nothing
                }
            }
        }


                 Dts.TaskResult = (int)ScriptResults.Success;
          }

How to get the MD5 hash of a file in C++?

A rework of impementation by @D'Nabre for C++. Don't forget to compile with -lcrypto at the end: gcc md5.c -o md5 -lcrypto.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

#include <openssl/md5.h>
using namespace std;

unsigned char result[MD5_DIGEST_LENGTH];

// function to print MD5 correctly
void printMD5(unsigned char* md, long size = MD5_DIGEST_LENGTH) {
    for (int i=0; i<size; i++) {
        cout<< hex << setw(2) << setfill('0') << (int) md[i];
    }
}

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

if(argc != 2) {
    cout << "Specify the file..." << endl;
    return 0;
}

ifstream::pos_type fileSize;
char * memBlock;

ifstream file (argv[1], ios::ate);

//check if opened
if (file.is_open() ) { cout<< "Using file\t"<< argv[1]<<endl; }
else {
    cout<< "Unnable to open\t"<< argv[1]<<endl;
    return 0;
}

//get file size & copy file to memory
//~ file.seekg(-1,ios::end); // exludes EOF
fileSize = file.tellg();
cout << "File size \t"<< fileSize << endl;
memBlock = new char[fileSize];
file.seekg(0,ios::beg);
file.read(memBlock, fileSize);
file.close();

//get md5 sum
MD5((unsigned char*) memBlock, fileSize, result);

//~ cout << "MD5_DIGEST_LENGTH = "<< MD5_DIGEST_LENGTH << endl;
printMD5(result);
cout<<endl;

return 0;
}

jquery $('.class').each() how many items?

If you're using chained syntax:

$(".class").each(function() {
    // ...
});

...I don't think there's any (reasonable) way for the code within the each function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index.)

But it's easy enough to make the collection available to the function that you're calling in each. Here's one way to do that:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});

As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach. The arguments that get passed to forEach's callback are the entry being visited (what jQuery gives you as this and as the second argument), the index of that entry, and the array you called it on:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});

That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach.

Or for that matter, give yourself a new tool:

// Loop through the jQuery set calling the callback:
//    loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
    var me = this;
    return this.each(function(index, element) {
        return callback.call(thisArg || element, element, index, me);
    });
};

Usage:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});

How to install numpy on windows using pip install?

Installing extension modules can be an issue with pip. This is why conda exists. conda is an open-source BSD-licensed cross-platform package manager. It can easily install NumPy.

Two options:

  • Install Anaconda here
  • Install Miniconda here and then go to a command-line and type conda install numpy (make sure your PATH includes the location conda was installed to).

How do you automatically set the focus to a textbox when a web page loads?

Use the below code. For me it is working

jQuery("[id$='hfSpecialty_ids']").focus()

ASP.NET Web API : Correct way to return a 401/unauthorised response

To add to an existing answer in ASP.NET Core >= 1.0 you can

return Unauthorized();

return Unauthorized(object value);

To pass info to the client you can do a call like this:

return Unauthorized(new { Ok = false, Code = Constants.INVALID_CREDENTIALS, ...});

On the client besides the 401 response you will have the passed data too. For example on most clients you can await response.json() to get it.

Can I use DIV class and ID together in CSS?

That's HTML, but yes, you can bang pretty much any selectors you like together.

#x.y { }

(And the HTML is fine too)

converting CSV/XLS to JSON?

See if this helps: Back to CSV - Convert CSV text to Objects; via JSON

This is a blog post published in November 2008 that includes C# code to provide a solution.

From the intro on the blog post:

As Json is easier to read and write then Xml. It follows that CSV (comma seperated values) is easier to read and write then Json. CSV also has tools such as Excel and others that make it easy to work with and create. So if you ever want to create a config or data file for your next app, here is some code to convert CSV to JSON to POCO objects

What is the first character in the sort order used by Windows Explorer?

If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:

Behavior of this function, and therefore the results it returns, can change from release to release. ...

Calling a class method raises a TypeError in Python

Every function inside a class, and every class variable must take the self argument as pointed.

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

If class variables are involved:

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

How to add "Maven Managed Dependencies" library in build path eclipse?

If you have removed Maven dependency from Library accidentally. Add below in pom.xml

<build>     
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
</build>

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

How do I get AWS_ACCESS_KEY_ID for Amazon?

To find the AWS_SECRET_ACCESS_KEY Its better to create new create "IAM" user Here is the steps https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.

  1. In the navigation pane, choose Users and then choose Add user.

appending array to FormData and send via AJAX

Based on @YackY answer shorter recursion version:

function createFormData(formData, key, data) {
    if (data === Object(data) || Array.isArray(data)) {
        for (var i in data) {
            createFormData(formData, key + '[' + i + ']', data[i]);
        }
    } else {
        formData.append(key, data);
    }
}

Usage example:

var data = {a: '1', b: 2, c: {d: '3'}};
var formData = new FormData();
createFormData(formData, 'data', data);

Sent data:

data[a]=1&
data[b]=2&
data[c][d]=3

How can I get the browser's scrollbar sizes?

You can determine window scroll bar with document as below using jquery + javascript:

var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );

how to get the one entry from hashmap without iterating

Following your EDIT, here's my suggestion :

If you have only one entry, you might replace the Map by a dual object. Depending on the types, and your preferences:

  • an array (of 2 values, key and value)
  • a simple object with two properties

Populating VBA dynamic arrays

Yes, you're looking for the ReDim statement, which dynamically allocates the required amount of space in the array.

The following statement

Dim MyArray()

declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.

But you can use the ReDim statement to resize the array:

ReDim MyArray(0 To 3)

And if you need to resize the array while preserving its contents, you can use the Preserve keyword along with the ReDim statement:

ReDim Preserve MyArray(0 To 3)

But do note that both ReDim and particularly ReDim Preserve have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.


However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim at all. Just declare the array with explicit dimensions:

Dim MyArray(0 To 3)

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

Even in base Python you can do the computation in generic form

result = sum(x**2 for x in some_vector) ** 0.5

x ** 2 is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).

Using instead x ** 0.5 to take the square root doesn't do the exact same computations as math.sqrt as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.

I often use x ** 0.5 simply because I don't want to add math just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Look at ?par for the various graphics parameters.

In general cex controls size, col controls colour. If you want to control the colour of a label, the par is col.lab, the colour of the axis annotations col.axis, the colour of the main text, col.main etc. The names are quite intuitive, once you know where to begin.

For example

x <- 1:10
y <- 1:10

plot(x , y,xlab="x axis", ylab="y axis",  pch=19, col.axis = 'blue', col.lab = 'red', cex.axis = 1.5, cex.lab = 2)

enter image description here

If you need to change the colour / style of the surrounding box and axis lines, then look at ?axis or ?box, and you will find that you will be using the same parameter names within calls to box and axis.

You have a lot of control to make things however you wish.

eg

plot(x , y,xlab="x axis", ylab="y axis",  pch=19,  cex.lab = 2, axes = F,col.lab = 'red')
box(col = 'lightblue')
axis(1, col = 'blue', col.axis = 'purple', col.ticks = 'darkred', cex.axis = 1.5, font = 2, family = 'serif')
axis(2, col = 'maroon', col.axis = 'pink', col.ticks = 'limegreen', cex.axis = 0.9, font =3, family = 'mono')

enter image description here

Which is seriously ugly, but shows part of what you can control

Absolute vs relative URLs

In general, it is considered best-practice to use relative URLs, so that your website will not be bound to the base URL of where it is currently deployed. For example, it will be able to work on localhost, as well as on your public domain, without modifications.

Where can I find Android source code online?

This eclipse plugin allows for inline source viewing and even stepping inside the Android source code:

http://code.google.com/p/adt-addons/

(edit: specifically the "Android Sources" plugin: http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/)

How to set RelativeLayout layout params in code not in xml?

Something like this..

 RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.widget43);
                // ListView listView = (ListView) findViewById(R.id.ListView01);

                LayoutInflater inflater = (LayoutInflater) this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // View footer = inflater.inflate(R.layout.footer, null);
                View footer = LayoutInflater.from(this).inflate(R.layout.footer,
                        null);
                final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        RelativeLayout.LayoutParams.FILL_PARENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
footer.setLayoutParams(layoutParams);

How do you fix a MySQL "Incorrect key file" error when you can't repair the table?

Change to MyISAM engine and run this command

REPAIR TABLE tbl_name USE_FRM;

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

How can I convert an image into a Base64 string?

Use this code:

byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

Convert web page to image

Not sure if this is what you want but this is what I do sometimes in a pinch when certain websites are not saving right.

I just print them to PDF and I get a PDF file of the 'print output'. There's an Microsoft XPS Document writer under my list of printers as well, but I don't use it.

Hope this helps! =)

How to kill a running SELECT statement

If you want to stop process you can kill it manually from task manager onother side if you want to stop running query in DBMS you can stop as given here for ms sqlserver T-SQL STOP or ABORT command in SQL Server Hope it helps you

Passing references to pointers in C++

Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:

string s;
string* _s = &s;
myfunc(_s);

should compile just fine.

However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.

Could not load type from assembly error

I want to mention additional things and make a conclusion.

Commonly, As Otherones explained, This exception will raise when there is a problem with loading expected type (in an existing assembly) in runtime. More specific, Whenever there is loaded assembly that is stale (and not contains the requiring type). Or when an assembly with different version or build is already loaded that not contains the expected type.

Also, I must mention that It seems Rarely, But It is possible to be runtime limitation or a compiler bug (suppose compiler not negated about something and just compiled problematic code), But runtime throws System.TypeLoadException exception. Yes; this actually occurred for me!

An Example (witch occurred for me)

Consider an struct that defines a nullable field of its own type inside itself. Defining such the filed non-nullable, will take you a compile-time error and prevents you from build (Obviously This behavior has a logical reason). But what about nullable struct filed? Actually, nullable value-types is Nullable<T> at behind. As c# compiler not prevented me from defining in this way, I tried it and the project built. But I get runtime exception System.TypeLoadException: 'Could not load type 'SomeInfo' from assembly ... ', And It seems to be Problem in loading the part of my code (otherwise, we may say: the compiler not-truly performed compilation process at least) for me in my environment:

public struct SomeInfo
{
   public SomeInfo? Parent { get; } 
   
   public string info { get; }
}

My environment specs:

  • Visual Studio 2019 16.4.4
  • Language Version: c# 7.3
  • Project type: netstandard 2.0.3 library
  • Runtime: classic DotNetFramework 4.6.1

(I checked and ensured that the compiled assembly is up to date And actually is newly compiled. Even, I throwed away all bin directory and refreshed the whole project. Even I created a new project in a fresh solution and tested, But such the struct generates the exception.)

It seems to be a runtime limitation (logically or technically) or bug or a same problem else, because Visual Studio not prevents me from compile And Also other newer parts of my codes (excluding this struct) are executing fine. Changing the struct to a class, the compiled assembly contains and executes the type as well.

I have no any idea to explain in-detail why this behavior occurs in my environment, But I faced this situation.

Conclusion

Check the situations:

  • When a same (probably older) assembly already exists in GAC that is overriding the referenced assembly.

  • When re-compilation was need but not performed automatically (therefore the referenced assembly is not updated) and there is needs to perform build manually or fix solution build configuration.

  • When a custom tool or middleware or third-party executable (such as tests runner tool or IIS) loaded an older version of that assembly from cached things and there is need to cleaning somethings up or causing to reset somethings.

  • When an Unappropriated Configuration caused demanding a no longer existing type by a custom tool or middleware or a third-party executable that loads the assembly and there is need to update configuration or cleaning somethings up (such as removing an http handler in web.config file on IIS deployment as @Brian-Moeskau said)

  • When there is a logical or technical problem for runtime to execute the compiled assembly, (for example when compiler was compiled a problematic code that the in-using runtime cannot understand or execute it), as I faced.

How to perform Join between multiple tables in LINQ lambda

take look at this sample code from my project

public static IList<Letter> GetDepartmentLettersLinq(int departmentId)
{
    IEnumerable<Letter> allDepartmentLetters =
        from allLetter in LetterService.GetAllLetters()
        join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup
        from user in usersGroup.DefaultIfEmpty()// here is the tricky part
        join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
        where allDepartment.ID == departmentId
        select allLetter;

    return allDepartmentLetters.ToArray();
}

in this code I joined 3 tables and I spited join condition from where clause

note: the Services classes are just warped(encapsulate) the database operations

What is the difference between String.slice and String.substring?

Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.

Here is his article about this.

css to make bootstrap navbar transparent

Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.

HTML:

<nav class="navbar navbar-default">

CSS:

.navbar-default {
    background-color: transparent;
}

WebDriver: check if an element exists?

Write the following method using Java:

protected boolean isElementPresent(By by){
        try{
            driver.findElement(by);
            return true;
        }
        catch(NoSuchElementException e){
            return false;
        }
    }

Call the above method during assertion.

check the null terminating character in char*

Your '/0' should be '\0' .. you got the slash reversed/leaning the wrong way. Your while should look like:

while (*(forward++)!='\0') 

though the != '\0' part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).

All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t', or newline '\n', and the same for null '\0' so it's easy to remember.

Does svn have a `revert-all` command?

You could do:

svn revert -R .

This will not delete any new file not under version control. But you can easily write a shell script to do that like:

for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done

How to check if object has any properties in JavaScript?

Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

How can I change the version of npm using nvm?

Changing npm versions on linux based OSs isn't a straight forward one command process yet. I have done following to switch back to older version of npm. This should work to get any version of npm working. First install the version of npm you want to use:

sudo npm install -g [email protected]

Remove the sym link in /usr/local/bin/

sudo rm /usr/local/bin/npm

Recreate the sym link using the desired version of npm you have installed

sudo ln -s /usr/bin/[email protected] /usr/local/bin/npm

Which Eclipse version should I use for an Android app?

Eclipse 3.5 for Java Developer is the best option for you and 3.6 version is good but not at all because of compatibility issues.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

What is the difference between Task.Run() and Task.Factory.StartNew()

The Task.Run got introduced in newer .NET framework version and it is recommended.

Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task.

The Task.Factory.StartNew has more options, the Task.Run is a shorthand:

The Run method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the StartNew overloads.

And by shorthand I mean a technical shortcut:

public static Task Run(Action action)
{
    return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
        TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}

Flask-SQLAlchemy how to delete all rows in a single table

DazWorrall's answer is spot on. Here's a variation that might be useful if your code is structured differently than the OP's:

num_rows_deleted = db.session.query(Model).delete()

Also, don't forget that the deletion won't take effect until you commit, as in this snippet:

try:
    num_rows_deleted = db.session.query(Model).delete()
    db.session.commit()
except:
    db.session.rollback()

How to find the path of Flutter SDK

The Flutter SDK path is certainly defined in a place where you can check it or change it, whether you created the project or not. Under Settings > Languages & Frameworks there should be a Flutter section. I found it by using the handy search bar in the Settings menu.

At the top of the Languages & Frameworks > Flutter is the Flutter SDK Path.

This is assuming that Flutter/Dart have already been installed under Plugins.

Error: Java: invalid target release: 11 - IntelliJ IDEA

If building a project through a build system (Maven, Gradle etc..) works but IntelliJ show Invalid target release error, then do the following,

  1. Close IntelliJ

  2. Go to the directory of the project

  3. Delete the .idea/ directory

  4. Start IntelliJ with the project's directory

This will re-create the .idea/ directory and will no longer show the error.

NOTE: Any repository specific IntelliJ settings that you have added would be deleted when the .idea/ directory is deleted and they will be re-created with the defaults.

Use YAML with variables

This is how I was able to configure yaml files to refer to variable.

I have values.yaml where we have root level fields which are used as template variables inside values.yaml

values.yaml

.....  
databaseUserPropName: spring.datasource.username  
databaseUserName: sa  
.....  
secrets:
    type: Opaque  
    name: dbservice-secrets  
    data:  
      - name: "{{ .Values.databaseUserPropName }}"  
        value: "{{ .Values.databaseUserName }}"  
.....

When referencing these values in secret.yaml, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}

secret.yaml

when using inside range i:e iteration

  {{ range .Values.deployments.secrets.data }}
    {{ tpl .name $ }}: "{{ tpl .value $ }}"
  {{ end }}

when directly referring as variable

  {{ tpl .Values.deployments.secrets.data.name . }}
  {{ tpl .Values.deployments.secrets.data.value . }}

$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.

Advantages of std::for_each over for loop

Mostly you'll have to iterate over the whole collection. Therefore I suggest you write your own for_each() variant, taking only 2 parameters. This will allow you to rewrite Terry Mahaffey's example as:

for_each(container, [](int& i) {
    i += 10;
});

I think this is indeed more readable than a for loop. However, this requires the C++0x compiler extensions.

How to put the legend out of the plot

The solution that worked for me when I had huge legend was to use extra empty image layout. In following example I made 4 rows and at the bottom I plot image with offset for legend (bbox_to_anchor) at the top it does not get cut.

f = plt.figure()
ax = f.add_subplot(414)
lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3)
ax.autoscale_view()
plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')

Correct way to convert size in bytes to KB, MB, GB in JavaScript

I am updating @Aliceljm answer here. Since the decimal place matters for 1,2 digit numbers, I am round off the first decimal place and keep the first decimal place. For 3 digit number, I am round off the units place and ignoring the all decimal places.

getMultiplers : function(bytes){
    var unit = 1000 ;
    if (bytes < unit) return bytes ;
    var exp = Math.floor(Math.log(bytes) / Math.log(unit));
    var pre = "kMGTPE".charAt(exp-1);
    var result = bytes / Math.pow(unit, exp);
    if(result/100 < 1)
        return (Math.round( result * 10 ) / 10) +pre;
    else
        return Math.round(result) + pre;
}

Making macOS Installer Packages which are Developer ID ready

There is one very interesting application by Stéphane Sudre which does all of this for you, is scriptable / supports building from the command line, has a super nice GUI and is FREE. Sad thing is: it's called "Packages" which makes it impossible to find in google.

http://s.sudre.free.fr/Software/Packages/about.html

I wished I had known about it before I started handcrafting my own scripts.

Packages application screenshot

Access restriction on class due to restriction on required library rt.jar?

I met the same problem. I found the answer in the website:http://www.17ext.com.
First,delete the JRE System Libraries. Then,import JRE System Libraries again.

I don't know why.However it fixed my problem,hope it can help you.

How using try catch for exception handling is best practice

The better approach is the second one (the one in which you specify the exception type). The advantage of this is that you know that this type of exception can occur in your code. You are handling this type of exception and you can resume. If any other exception came, then that means something is wrong which will help you find bugs in your code. The application will eventually crash, but you will come to know that there is something you missed (bug) which needs to be fixed.

Recommended way of making React component/div draggable

The answer by Jared Forsyth is horribly wrong and outdated. It follows a whole set of antipatterns such as usage of stopPropagation, initializing state from props, usage of jQuery, nested objects in state and has some odd dragging state field. If being rewritten, the solution will be the following, but it still forces virtual DOM reconciliation on every mouse move tick and is not very performant.

UPD. My answer was horribly wrong and outdated. Now the code alleviates issues of slow React component lifecycle by using native event handlers and style updates, uses transform as it doesn't lead to reflows, and throttles DOM changes through requestAnimationFrame. Now it's consistently 60 FPS for me in every browser I tried.

const throttle = (f) => {
    let token = null, lastArgs = null;
    const invoke = () => {
        f(...lastArgs);
        token = null;
    };
    const result = (...args) => {
        lastArgs = args;
        if (!token) {
            token = requestAnimationFrame(invoke);
        }
    };
    result.cancel = () => token && cancelAnimationFrame(token);
    return result;
};

class Draggable extends React.PureComponent {
    _relX = 0;
    _relY = 0;
    _ref = React.createRef();

    _onMouseDown = (event) => {
        if (event.button !== 0) {
            return;
        }
        const {scrollLeft, scrollTop, clientLeft, clientTop} = document.body;
        // Try to avoid calling `getBoundingClientRect` if you know the size
        // of the moving element from the beginning. It forces reflow and is
        // the laggiest part of the code right now. Luckily it's called only
        // once per click.
        const {left, top} = this._ref.current.getBoundingClientRect();
        this._relX = event.pageX - (left + scrollLeft - clientLeft);
        this._relY = event.pageY - (top + scrollTop - clientTop);
        document.addEventListener('mousemove', this._onMouseMove);
        document.addEventListener('mouseup', this._onMouseUp);
        event.preventDefault();
    };

    _onMouseUp = (event) => {
        document.removeEventListener('mousemove', this._onMouseMove);
        document.removeEventListener('mouseup', this._onMouseUp);
        event.preventDefault();
    };

    _onMouseMove = (event) => {
        this.props.onMove(
            event.pageX - this._relX,
            event.pageY - this._relY,
        );
        event.preventDefault();
    };

    _update = throttle(() => {
        const {x, y} = this.props;
        this._ref.current.style.transform = `translate(${x}px, ${y}px)`;
    });

    componentDidMount() {
        this._ref.current.addEventListener('mousedown', this._onMouseDown);
        this._update();
    }

    componentDidUpdate() {
        this._update();
    }

    componentWillUnmount() {
        this._ref.current.removeEventListener('mousedown', this._onMouseDown);
        this._update.cancel();
    }

    render() {
        return (
            <div className="draggable" ref={this._ref}>
                {this.props.children}
            </div>
        );
    }
}

class Test extends React.PureComponent {
    state = {
        x: 100,
        y: 200,
    };

    _move = (x, y) => this.setState({x, y});

    // you can implement grid snapping logic or whatever here
    /*
    _move = (x, y) => this.setState({
        x: ~~((x - 5) / 10) * 10 + 5,
        y: ~~((y - 5) / 10) * 10 + 5,
    });
    */

    render() {
        const {x, y} = this.state;
        return (
            <Draggable x={x} y={y} onMove={this._move}>
                Drag me
            </Draggable>
        );
    }
}

ReactDOM.render(
    <Test />,
    document.getElementById('container'),
);

and a bit of CSS

.draggable {
    /* just to size it to content */
    display: inline-block;
    /* opaque background is important for performance */
    background: white;
    /* avoid selecting text while dragging */
    user-select: none;
}

Example on JSFiddle.

Create an array or List of all dates between two dates

LINQ:

Enumerable.Range(0, 1 + end.Subtract(start).Days)
          .Select(offset => start.AddDays(offset))
          .ToArray(); 

For loop:

var dates = new List<DateTime>();

for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
   dates.Add(dt);
}

EDIT: As for padding values with defaults in a time-series, you could enumerate all the dates in the full date-range, and pick the value for a date directly from the series if it exists, or the default otherwise. For example:

var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date) 
                                               ? timeSeries[date] : defaultValue);

How to delete files recursively from an S3 bucket

With s3cmd package installed on a Linux machine, you can do this

s3cmd rm s3://foo/bar --recursive

Javascript: Extend a Function

With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.

But here's a literal answer:

If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:

// Original code in main.js
var theProperty = init;

function init(){
     doSomething();
}

// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
    function extendsInit() {
        old();
        doSomething();
    }

    return extendsInit;
})(theProperty);

If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:

// In main.js
var MyLibrary = {
    init: function init() {
    }
};

// In extended.js
(function() {
    var oldInit = MyLibrary.init;
    MyLibrary.init = extendedInit;
    function extendedInit() {
        oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
        doSomething();
    }
})();

But there are better ways to do that. Like for instance, providing a means of registering init functions.

// In main.js
var MyLibrary = (function() {
    var initFunctions = [];
    return {
        init: function init() {
            var fns = initFunctions;
            initFunctions = undefined;
            for (var index = 0; index < fns.length; ++index) {
                try { fns[index](); } catch (e) { }
            }
        },
        addInitFunction: function addInitFunction(fn) {
            if (initFunctions) {
                // Init hasn't run yet, remember it
                initFunctions.push(fn);
            } else {
                // `init` has already run, call it almost immediately
                // but *asynchronously* (so the caller never sees the
                // call synchronously)
                setTimeout(fn, 0);
            }
        }
    };
})();

Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:

// In main.js
const MyLibrary = (() => {
    let initFunctions = [];
    return {
        init() {
            const fns = initFunctions;
            initFunctions = undefined;
            for (const fn of fns) {
                try { fn(); } catch (e) { }
            }
        },
        addInitFunction(fn) {
            if (initFunctions) {
                // Init hasn't run yet, remember it
                initFunctions.push(fn);
            } else {
                // `init` has already run, call it almost immediately
                // but *asynchronously* (so the caller never sees the
                // call synchronously)
                setTimeout(fn, 0);
                // Or: `Promise.resolve().then(() => fn());`
                // (Not `.then(fn)` just to avoid passing it an argument)
            }
        }
    };
})();

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

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

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

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

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

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

EDIT

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

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

e.g.

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

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

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

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

Interface defining a constructor signature?

You can't. It's occasionally a pain, but you wouldn't be able to call it using normal techniques anyway.

In a blog post I've suggested static interfaces which would only be usable in generic type constraints - but could be really handy, IMO.

One point about if you could define a constructor within an interface, you'd have trouble deriving classes:

public class Foo : IParameterlessConstructor
{
    public Foo() // As per the interface
    {
    }
}

public class Bar : Foo
{
    // Yikes! We now don't have a parameterless constructor...
    public Bar(int x)
    {
    }
}

How to convert float to varchar in SQL Server

If you use a CLR function, you can convert the float to a string that looks just like the float, without all the extra 0's at the end.

CLR Function

[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
[return: SqlFacet(MaxSize = 50)]
public static SqlString float_to_str(double Value, int TruncAfter)
{
  string rtn1 = Value.ToString("R");
  string rtn2 = Value.ToString("0." + new string('0', TruncAfter));

  if (rtn1.Length < rtn2.Length) { return rtn1; } else { return rtn2; }
}

.

Example

create table #temp (value float)
insert into #temp values (0.73), (0), (0.63921), (-0.70945), (0.28), (0.72000002861023), (3.7), (-0.01), (0.86), (0.55489), (0.439999997615814)

select value,
       dbo.float_to_str(value, 18) as converted,
       case when value = cast(dbo.float_to_str(value, 18) as float) then 1 else 0 end as same
from   #temp

drop table #temp

.

Output

value                  converted                  same
---------------------- -------------------------- -----------
0.73                   0.73                       1
0                      0                          1
0.63921                0.63921                    1
-0.70945               -0.70945                   1
0.28                   0.28                       1
0.72000002861023       0.72000002861023           1
3.7                    3.7                        1
-0.01                  -0.01                      1
0.86                   0.86                       1
0.55489                0.55489                    1
0.439999997615814      0.439999997615814          1

.

Caveat

All converted strings are truncated at 18 decimal places, and there are no trailing zeros. 18 digits of precision is not a problem for us. And, 100% of our FP numbers (close to 100,000 values) look identical as string values as they do in the database as FP numbers.

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

How to export the Html Tables data into PDF using Jspdf

Here is an example I think that will help you

<!DOCTYPE html>
<html>
<head>
<script src="js/min.js"></script>
<script src="js/pdf.js"></script>
<script>
    $(function(){
         var doc = new jsPDF();
    var specialElementHandlers = {
        '#editor': function (element, renderer) {
            return true;
        }
    };

   $('#cmd').click(function () {

        var table = tableToJson($('#StudentInfoListTable').get(0))
        var doc = new jsPDF('p','pt', 'a4', true);
        doc.cellInitialize();
        $.each(table, function (i, row){
            console.debug(row);
            $.each(row, function (j, cell){
                doc.cell(10, 50,120, 50, cell, i);  // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
            })
        })


        doc.save('sample-file.pdf');
    });
    function tableToJson(table) {
    var data = [];

    // first row needs to be headers
    var headers = [];
    for (var i=0; i<table.rows[0].cells.length; i++) {
        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }


    // go through cells
    for (var i=0; i<table.rows.length; i++) {

        var tableRow = table.rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {

            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

        }

        data.push(rowData);
    }       

    return data;
}
});
</script>
</head>
<body>
<div id="table">
<table id="StudentInfoListTable">
                <thead>
                    <tr>    
                        <th>Name</th>
                        <th>Email</th>
                        <th>Track</th>
                        <th>S.S.C Roll</th>
                        <th>S.S.C Division</th>
                        <th>H.S.C Roll</th>
                        <th>H.S.C Division</th>
                        <th>District</th>

                    </tr>
                </thead>
                <tbody>

                        <tr>
                            <td>alimon  </td>
                            <td>Email</td>
                            <td>1</td>
                            <td>2222</td>
                            <td>as</td>
                            <td>3333</td>
                            <td>dd</td>
                            <td>33</td>
                        </tr>               
                </tbody>
            </table>
<button id="cmd">Submit</button>
</body>
</html>

Here the output

enter image description here

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

MySQL stored procedure return value

Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    GET DIAGNOSTICS CONDITION 1
    @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
    SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;

SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;

IF (resta > s.stock_minimo) THEN
    SET valido = 1;
ELSE
    SET valido = -1;
END IF;
SELECT valido;
END

What is time_t ultimately a typedef to?

time_t is of type long int on 64 bit machines, else it is long long int.

You could verify this in these header files:

time.h: /usr/include
types.h and typesizes.h: /usr/include/x86_64-linux-gnu/bits

(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)

1)In time.h

typedef __time_t time_t;

2)In types.h

# define __STD_TYPE     typedef  
__STD_TYPE __TIME_T_TYPE __time_t;  

3)In typesizes.h

#define __TIME_T_TYPE       __SYSCALL_SLONG_TYPE  
#if defined __x86_64__ && defined __ILP32__  
# define __SYSCALL_SLONG_TYPE   __SQUAD_TYPE  
#else
# define __SYSCALL_SLONG_TYPE   __SLONGWORD_TYPE
#endif  

4) Again in types.h

#define __SLONGWORD_TYPE    long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE       __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE       long int  

#if __WORDSIZE == 64
typedef long int __quad_t;  
#else
__extension__ typedef long long int __quad_t;

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

Oracle Convert Seconds to Hours:Minutes:Seconds

Unfortunately not... However, there's a simple trick if it's going to be less than 24 hours.

Oracle assumes that a number added to a date is in days. Convert the number of seconds into days. Add the current day, then use the to_date function to take only the parts your interested in. Assuming you have x seconds:

select to_char(sysdate + (x / ( 60 * 60 * 24 ) ), 'HH24:MI:SS')
  from dual

This won't work if there's more than 24 hours, though you can remove the current data again and get the difference in days, hours, minutes and seconds.

If you want something like: 51:10:05, i.e. 51 hours, 10 minutes and 5 seconds then you're going to have to use trunc.

Once again assuming that you have x seconds...

  • The number of hours is trunc(x / 60 / 60)
  • The number of minutes is trunc((x - ( trunc(x / 60 / 60) * 60 * 60 )) / 60)
  • The number of seconds is therefore the x - hours * 60 * 60 - minutes * 60

Leaving you with:

with hrs as (
  select x, trunc(x / 60 / 60) as h
    from dual
         )
 , mins as (
  select x, h, trunc((x - h * 60 * 60) / 60) as m
    from hrs
         )
select h, m, x - (h * 60 * 60) - (m * 60)
  from mins

I've set up a SQL Fiddle to demonstrate.

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

how to measure running time of algorithms in python

The module timeit is useful for this and is included in the standard Python distribution.

Example:

import timeit
timeit.Timer('for i in xrange(10): oct(i)').timeit()

npm throws error without sudo

Other answers are suggesting to change ownerships or permissions of system directories to a specific user. I highly disadvise from doing so, this can become very awkward and might mess up the entire system!

Here is a more generic and safer approach that supports multi-user as well.

Create a new group for node-users and add the required users to this group. Then set the ownership of node-dependant files/directories to this group.

# Create new group
sudo groupadd nodegrp 

# Add user to group (logname is a variable and gets replaced by the currently logged in user)
sudo usermod -a -G nodegrp `logname`

# Instant access to group without re-login
newgrp nodegrp

# Check group - nodegrp should be listed as well now
groups

# Change group of node_modules, node, npm to new group 
sudo chgrp -R nodegrp /usr/lib/node_modules/
sudo chgrp nodegrp /usr/bin/node
sudo chgrp nodegrp /usr/bin/npm

# (You may want to change a couple of more files (like grunt etc) in your /usr/bin/ directory.)

Now you can easily install your modules as user

npm install -g generator-angular

Some modules (grunt, bower, yo etc.) will still need to be installed as root. This is because they create symlinks in /user/bin/.

Edit

3 years later I'd recommend to use Node Version Manager. It safes you a lot of time and trouble.

Get Selected Item Using Checkbox in Listview

Assuming you want to get items of row whose check boxes are checked at the click of a button. Assumption based on your title "Get Selected Item Using Checkbox in Listview when I click a Button".

Try the below. Make only changes as below. Keep the rest the same.

Explanation and discussion on the topic @

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

MainActivity.java

public class MainActivity extends Activity {
     AppInfoAdapter adapter ;
     AppInfo app_info[] ;
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            final ListView listApplication = (ListView)findViewById(R.id.listApplication);
            Button b= (Button) findViewById(R.id.button1);
            b.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    StringBuilder result = new StringBuilder();
                    for(int i=0;i<adapter.mCheckStates.size();i++)
                    {
                        if(adapter.mCheckStates.get(i)==true)
                        {

                                           result.append(app_info[i].applicationName);
                            result.append("\n");
                        }

                    }
                    Toast.makeText(MainActivity.this, result, 1000).show();
                }

            });

            ApplicationInfo applicationInfo = getApplicationInfo();
            PackageManager pm = getPackageManager();
            List<PackageInfo> pInfo = new ArrayList<PackageInfo>();
            pInfo.addAll(pm.getInstalledPackages(0));
            app_info = new AppInfo[pInfo.size()];

            int counter = 0;
            for(PackageInfo item: pInfo){
                try{

                    applicationInfo = pm.getApplicationInfo(item.packageName, 1);

                    app_info[counter] = new AppInfo(pm.getApplicationIcon(applicationInfo), 
                            String.valueOf(pm.getApplicationLabel(applicationInfo)));

                    System.out.println(counter);

                }
                catch(Exception e){
                     System.out.println(e.getMessage());
                }

                counter++;
            }

           adapter = new AppInfoAdapter(this, R.layout.listview_item_row, app_info);
            listApplication.setAdapter(adapter);

        }
}

activity_main.xml ListView with button at the buton

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:layout_width="fill_parent"
        android:id="@+id/listApplication"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button1"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

</RelativeLayout>

AppInfoAdapter

public class AppInfoAdapter extends ArrayAdapter<AppInfo> implements CompoundButton.OnCheckedChangeListener
{  SparseBooleanArray mCheckStates; 

    Context context;
    int layoutResourceId;
    AppInfo  data[] = null;

    public AppInfoAdapter(Context context, int layoutResourceId, AppInfo[] data){
        super(context, layoutResourceId,data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
        mCheckStates = new SparseBooleanArray(data.length);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        View row = convertView;
        AppInfoHolder holder= null;

        if (row == null){

            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new AppInfoHolder();

            holder.imgIcon = (ImageView) row.findViewById(R.id.imageView1);
            holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
            holder.chkSelect = (CheckBox) row.findViewById(R.id.checkBox1);

            row.setTag(holder);

        }
        else{
            holder = (AppInfoHolder)row.getTag();
        }


        AppInfo appinfo = data[position];
        holder.txtTitle.setText(appinfo.applicationName);
        holder.imgIcon.setImageDrawable(appinfo.icon);
       // holder.chkSelect.setChecked(true);
        holder.chkSelect.setTag(position);
        holder.chkSelect.setChecked(mCheckStates.get(position, false));
        holder.chkSelect.setOnCheckedChangeListener(this);
        return row;

    }
    public boolean isChecked(int position) {
        return mCheckStates.get(position, false);
    }

    public void setChecked(int position, boolean isChecked) {
        mCheckStates.put(position, isChecked);

    }

    public void toggle(int position) {
        setChecked(position, !isChecked(position));

    }
@Override
public void onCheckedChanged(CompoundButton buttonView,
        boolean isChecked) {

     mCheckStates.put((Integer) buttonView.getTag(), isChecked);    

}
static class AppInfoHolder
{
    ImageView imgIcon;
    TextView txtTitle;
    CheckBox chkSelect;

}
}

Here's the snap shot

enter image description here

Support for "border-radius" in IE

The answer to this question has changed since it was asked a year ago. (This question is currently one of the top results for Googling "border-radius ie".)

IE9 will support border-radius.

There is a platform preview available which supports border-radius. You will need Windows Vista or Windows 7 to run the preview (and IE9 when it is released).

How to set maximum fullscreen in vmware?

Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

2018 update:

For AdMob users, this causes AdMob version 12.0.0 (currently last version). It wrongly requests READ_PHONE_STATE permission, so even if your app doesn't require READ_PHONE_STATE permission in manifest, you won't be able to update your app in the Google Play Console (it will tell you to create a privacy policy page for your app, because your app requires this permission).

See this: https://developers.google.com/android/guides/releases#march_20_2018_-_version_1200

Also, they wrote they will publish an update to 12.0.1 fixing this soon.

How to show the text on a ImageButton?

you can use a regular Button and the android:drawableTop attribute (or left, right, bottom) instead.

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

Activity transition in Android

For a list of default animations see: http://developer.android.com/reference/android/R.anim.html

There is in fact fade_in and fade_out for API level 1 and up.

How to install ADB driver for any android device?

You don't really need to install or use any third party tools.

The drivers located in ...\Android\Sdk\extras\google\usb_driver work just fine.

Step 1: In Device Manager, Right click on the malfunctioning Android ADB Interface driver

Step 2: Select Update Driver Software

Step 3: Select Browse my computer for driver software

Step 4: Select Let me pick from a list of device drivers on my computer

Step 5: Select Have Disk

This window pops up:

enter image description here

Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver) or browse to it.

Step 7: Click Ok

This window pops up:

enter image description here

Step 8: Select Android ADB Interface and click Next

The window below pops up with a warning:

enter image description here

That's it. You driver installation will start and in a few seconds, you should be able to see your device