Programs & Examples On #Logcat

Logcat is the command to view and filter information from the Android logging system, but more often the name is used as a synonym for the Android logging system itself.

Android studio logcat nothing to show

In my case I was sending empty tag i.e

Log.d("","My Log");

Instead send a tag name

Log.d("Class name","My Log");

Hope it helps someone

sendUserActionEvent() is null

This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project

How to enable LogCat/Console in Eclipse for Android?

Go to your desired perspective. Go to 'Window->show view' menu.

If you see logcat there, click it and you are done.

Else, click on 'other' (at the bottom), chose 'Android'->logcat.

Hope that helps :-)

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

Couldn't load memtrack module Logcat Error

This error, as you can read on the question linked in comments above, results to be:

"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."

The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:

  • package="com.example.hive" in <manifest> tag,
  • android:name="com.sit.gems.app.GemsApplication" for <application>
  • and android:name="com.sit.gems.activity" in <activity>

As you know, these things do not prevent your app to be displayed. But I think:

the Couldn't load memtrack module error could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.

For better using and with few things, this can be resolved by following these tips:


1. Try an other emulator...

And even a real device! The memtrack module error seems related to your emulator. So change it into Run configuration, don't forget to change the API too.


2. OpenGL error logs

For OpenGl errors, as called unimplemented OpenGL ES API, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java, it might help you):

<uses-feature android:glEsVersion="0x00020000"></uses-feature>  
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />

3. Use the same package

Don't declare different package names to all the tags in Manifest. You should have the same for Manifest, Activities, etc. Something like this looks right:

<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sit.gems.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- don't set a package name in <application> -->
    <application ... >

        <!-- then, declare the activities -->
        <activity
            android:name="com.sit.gems.activity.SplashActivity" ... >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- same package here -->
        <activity
            android:name="com.sit.gems.activity.HomeActivity" ... >
        </activity>
    </application>
</manifest>  

4. Don't get lost with layouts:

You should set another layout for SplashScreenActivity.java because you're not using the TabHost for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:

// inside SplashScreen class
setContentView(R.layout.splash_screen);

// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" 
     android:gravity="center"
     android:text="@string/appname" />  

Avoid using a layout in activities which don't use it.


5. Splash Screen?

Finally, I don't understand clearly the purpose of your SplashScreenActivity. It sets a content view and directly finish. This is useless.

As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity. Therefore, you should do this and don't use the TabHost layout ;):

// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set your splash_screen layout
        setContentView(R.layout.splash_screen);

        // create a new Thread
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sleep during 800ms
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // start HomeActivity
                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                SplashActivity.this.finish();
            }
        }).start();
    }
}  

I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.

Restore LogCat window within Android Studio

Tools-> Android -> Android Device Monitor

will open a separate window

Android: How can I print a variable on eclipse console?

Writing the followin code to print anything on LogCat works perfectly fine!!

int score=0;
score++;
System.out.println(score);

prints score on LogCat.Try this

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:

  • Verbose - Show all log messages (the default).
  • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
  • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
  • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
  • Error - Show issues that have caused errors, as well as the message level lower in this list.
  • Assert - Show issues that the developer expects should never happen.

How do I write outputs to the Log in Android?

You can use my libary called RDALogger. Here is github link.

With this library, you can log your message with method name/class name/line number and anchor link. With this link, when you click log, screen goes to this line of code.

To use library, you must do implementations below.

in root level gradle

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

in app level gradle

dependencies {
            implementation 'com.github.ardakaplan:RDALogger:1.0.0'
    }

For initializing library, you should start like this (in Application.class or before first use)

RDALogger.start("TAG NAME").enableLogging(true);

And than you can log whatever you want;

    RDALogger.info("info");
    RDALogger.debug("debug");
    RDALogger.verbose("verbose");
    RDALogger.warn("warn");
    RDALogger.error("error");
    RDALogger.error(new Throwable());
    RDALogger.error("error", new Throwable());

And finally output shows you all you want (class name, method name, anchor link, message)

08-09 11:13:06.023 20025-20025/com.ardakaplan.application I/Application: IN CLASS : (ENApplication.java:29)   ///   IN METHOD : onCreate
    info

Why doesn't logcat show anything in my Android?

This is simple.

Just close the Logcat from eclipse.

Then reopen it by following steps in Eclipse.

Window - Show View - Other - Android - LogCat - ok

Hope this solves your problem.

How to filter Android logcat by application?

On the left in the logcat view you have the "Saved Filters" windows. Here you can add a new logcat filter by Application Name (for example, com.your.package)

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

error opening trace file: No such file or directory (2)

You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.

Filter output in logcat by tagname

Do not depend on ADB shell, just treat it (the adb logcat) a normal linux output and then pip it:

$ adb shell logcat | grep YouTag
# just like: 
$ ps -ef | grep your_proc 

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

In my case, it was literally a bad USB cable. Apparently it was right on the edge - adb logcat would work, but about half the time I would get this error when trying to push an app to the device.

Changed to a different cable, and everything was fine. The old cable was also very slow at charging, so I should have suspected it sooner...

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

Body of Http.DELETE request in Angular2

If you use Angular 6 we can put body in http.request method.

Reference from github

You can try this, for me it works.

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
    private http: HttpClient
  ) {
    http.request('delete', url, {body: body}).subscribe();
  }
}

MySQL "between" clause not inclusive?

In MySql between the values are inclusive therefore when you give try to get between '2011-01-01' and '2011-01-31'

it will include from 2011-01-01 00:00:00 upto 2011-01-31 00:00:00 therefore nothing actually in 2011-01-31 since its time should go from 2011-01-31 00:00:00 ~ 2011-01-31 23:59:59

For the upper bound you can change to 2011-02-01 then it will get all data upto 2011-01-31 23:59:59

How do I detect if a user is already logged in Firebase?

One another way is to use the same thing what firebase uses.

For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.

enter image description here

ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)

Mockito. Verify method arguments

Are you trying to do logical equality utilizing the object's .equals method? You can do this utilizing the argThat matcher that is included in Mockito

import static org.mockito.Matchers.argThat

Next you can implement your own argument matcher that will defer to each objects .equals method

private class ObjectEqualityArgumentMatcher<T> extends ArgumentMatcher<T> {
    T thisObject;

    public ObjectEqualityArgumentMatcher(T thisObject) {
        this.thisObject = thisObject;
    }

    @Override
    public boolean matches(Object argument) {
        return thisObject.equals(argument);
    }
}

Now using your code you can update it to read...

Object obj = getObject();
Mockeable mock= Mockito.mock(Mockeable.class);
Mockito.when(mock.mymethod(obj)).thenReturn(null);

Testeable obj = new Testeable();
obj.setMockeable(mock);
command.runtestmethod();

verify(mock).mymethod(argThat(new ObjectEqualityArgumentMatcher<Object>(obj)));

If you are just going for EXACT equality (same object in memory), just do

verify(mock).mymethod(obj);

This will verify it was called once.

How to get response from S3 getObject in Node.js?

When doing a getObject() from the S3 API, per the docs the contents of your file are located in the Body property, which you can see from your sample output. You should have code that looks something like the following

const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary

var getParams = {
    Bucket: 'abc', // your bucket name,
    Key: 'abc.txt' // path to the object you're looking for
}

s3.getObject(getParams, function(err, data) {
    // Handle any error and exit
    if (err)
        return err;

  // No error happened
  // Convert Body from a Buffer to a String

  let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});

You may not need to create a new buffer from the data.Body object but if you need you can use the sample above to achieve that.

Qt: How do I handle the event of the user pressing the 'X' (close) button?

also you can reimplement protected member QWidget::closeEvent()

void YourWidgetWithXButton::closeEvent(QCloseEvent *event)
{
    // do what you need here
    // then call parent's procedure
    QWidget::closeEvent(event);
}

How to make MySQL table primary key auto increment with some prefix

Here is PostgreSQL example without trigger if someone need it on PostgreSQL:

CREATE SEQUENCE messages_seq;

 CREATE TABLE IF NOT EXISTS messages (
    id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
    name CHAR(30) NOT NULL,
);

ALTER SEQUENCE messages_seq OWNED BY messages.id;

php search array key and get value

array_search('20120504', array_keys($your_array));

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

Python popen command. Wait until the command is finished

I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

Python function as a function argument?

  1. Yes, it's allowed.
  2. You use the function as you would any other: anotherfunc(*extraArgs)

How to suppress scientific notation when printing float values?

Since this is the top result on Google, I will post here after failing to find a solution for my problem. If you are looking to format the display value of a float object and have it remain a float - not a string, you can use this solution:

Create a new class that modifies the way that float values are displayed.

from builtins import float
class FormattedFloat(float):

    def __str__(self):
        return "{:.10f}".format(self).rstrip('0')

You can modify the precision yourself by changing the integer values in {:f}

Switching to landscape mode in Android Emulator

The complete listing is buried in the android docs, and i only found it via google / dogpile.

http://developer.android.com/tools/help/emulator.html

That link has the emulator shortcut keys as of right now.

=\

How to run a script file remotely using SSH

You can do:

ssh user@host 'bash -s' < /path/script.sh

Jquery validation plugin - TypeError: $(...).validate is not a function

You're not loading the validation plugin. You need:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

Put this before the line that loads the additional methods.

Also, you should get the additional methods from the CDN as well, rather than jquery.bassistance.de.

Other errors:

[4.20]

should be

[4,20]

and

rangelenght:

should be:

rangelength:

Deleting array elements in JavaScript - delete vs splice

I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
?

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Are dictionaries ordered in Python 3.6+?

Update: Guido van Rossum announced on the mailing list that as of Python 3.7 dicts in all Python implementations must preserve insertion order.

ArrayAdapter in android to create simple listview

You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.

ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);

Convert Base64 string to an image file?

$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";

This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

Single Page Application: advantages and disadvantages

I would like to make the case for SPA being best for Data Driven Applications. gmail, of course is all about data and thus a good candidate for a SPA.

But if your page is mostly for display, for example, a terms of service page, then a SPA is completely overkill.

I think the sweet spot is having a site with a mixture of both SPA and static/MVC style pages, depending on the particular page.

For example, on one site I am building, the user lands on a standard MVC index page. But then when they go to the actual application, then it calls up the SPA. Another advantage to this is that the load-time of the SPA is not on the home page, but on the app page. The load time being on the home page could be a distraction to first time site users.

This scenario is a little bit like using Flash. After a few years of experience, the number of Flash only sites dropped to near zero due to the load factor. But as a page component, it is still in use.

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

INNER JOIN ON vs WHERE clause

If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.

hasOwnProperty in JavaScript

hasOwnProperty is a normal JavaScript function that takes a string argument.

When you call shape1.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).

You need to call hasOwnProperty with a string containing name, like this: shape1.hasOwnProperty("name").

Java abstract interface

It is not necessary to declare the interface abstract.

Just like declaring all those methods public (which they already are if the interface is public) or abstract (which they already are in an interface) is redundant.

No one is stopping you, though.

Other things you can explicitly state, but don't need to:

  • call super() on the first line of a constructor
  • extends Object
  • implement inherited interfaces

Is there other rules that applies with an abstract interface?

An interface is already "abstract". Applying that keyword again makes absolutely no difference.

Fatal error: Call to undefined function sqlsrv_connect()

If you are using Microsoft Drivers 3.1, 3.0, and 2.0. Please check your PHP version already install with IIS.

Use this script to check the php version:

<?php echo phpinfo(); ?>

OR

If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.

Then:
If you are using new PHP version (5.6) please download Drivers from here

For PHP version Lower than 5.6 - please download Drivers from here

  • PHP Driver version 3.1 requires PHP 5.4.32, or PHP 5.5.16, or later.
  • PHP Driver version 3.0 requires PHP 5.3.0 or later. If possible, use PHP 5.3.6, or later.
  • PHP Driver version 2.0 driver works with PHP 5.2.4 or later, but not with PHP 5.4. If possible, use PHP 5.2.13, or later.

Then use the PHP Manager to add that downloaded drivers into php config file.You can do it as shown below (browse the files and press OK). Then Restart the IIS Server

enter image description here

If this method not work please change the php version and try to run your php script. enter image description here

Tip:Change the php version to lower and try to understand what happened.then you can download relevant drivers.

CSS to stop text wrapping under image

Very simple answer for this problem that seems to catch a lot of people:

<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>

    img {
        float: left;
    }
    p {
        overflow: hidden;
    }

See example: http://jsfiddle.net/vandigroup/upKGe/132/

setOnItemClickListener on custom ListView

If above answers don't work maybe you didn't add return value into getItem method in the custom adapter see this question and check out first answer.

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Get value of a specific object property in C# without knowing the class behind

Use reflection

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));

How to find memory leak in a C++ code/project?

Search your code for occurrences of new, and make sure that they all occur within a constructor with a matching delete in a destructor. Make sure that this is the only possibly throwing operation in that constructor. A simple way to do this is to wrap all pointers in std::auto_ptr, or boost::scoped_ptr (depending on whether or not you need move semantics). For all future code just ensure that every resource is owned by an object that cleans up the resource in its destructor. If you need move semantics then you can upgrade to a compiler that supports r-value references (VS2010 does I believe) and create move constructors. If you don't want to do that then you can use a variety of tricky techniques involving conscientious usage of swap, or try the Boost.Move library.

How can I pass a Bitmap object from one activity to another

Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

To store bitmap in a file myImage in internal storage:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));

Note A lot of checking for null and scaling bitmap's is ommited.

Font Awesome not working, icons showing as squares

This should be much simpler in the new version 3.0. Easiest is to point to the Bootstrap CDN: http://www.bootstrapcdn.com/?v=01042013155511#tab_fontawesome

iPhone SDK on Windows (alternative solutions)

There is another solution if you want to develop in C/C++. http://www.DragonFireSDK.com will allow you to build iPhone applications in Visual Studio on Windows. It's worth a look-see for sure.

Mapping US zip code to time zone

I just found a free zip database that includes time offset and participation in DST. I do like Erik J's answer, as it would help me choose the actual time zone as opposed to just the offset (because you never can be completely sure on the rules), but I think I might start with this, and have it try to find the best time zone match based on offset/dst configuration. I think I may try to set up a simple version of Development 4.0's answer to check against what I get from the zip info as a sanity test. It's definitely not as simple as I'd hope, but a combination should get me at least 90% sure of a user's time zone.

Handlebars.js Else If

I usually use this form:

{{#if FriendStatus.IsFriend}}
  ...
{{else}} {{#if FriendStatus.FriendRequested}}
  ...
{{else}}
  ...
{{/if}}{{/if}}

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

In the pom.xml (after loading effective pom.xml in eclipse), you may see it "http://repo.maven.apache.org/maven2" under central repository instead of "https://repo.maven.apache.org/maven2". Fix it

Get all unique values in a JavaScript array (remove duplicates)

How about using set?

   let productPrice = [230,560,125,230,678,45,230,125,127];

   let tempData = new Set(productPrice);
   let uniqeProductPrice = [...tempData];

   uniqeProductPrice.forEach((item)=>{
      console.log(item)
    });

How do I get a HttpServletRequest in my spring beans?

If FlexContext is not available:

Solution 1: inside method (>= Spring 2.0 required)

HttpServletRequest request = 
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                .getRequest();

Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

@Autowired
private HttpServletRequest request;

Why is setTimeout(fn, 0) sometimes useful?

setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:

myObject.prototype.myMethodDeferred = function() {
    var deferredObject = $.Deferred();
    var that = this;  // Because setTimeout won't work right with this
    setTimeout(function() { 
        return myMethodActualWork.call(that, deferredObject);
    }, 0);
    return deferredObject.promise();
}

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

CSS: styled a checkbox to look like a button, is there a hover?

Do this for a cool border and font effect:

#ck-button:hover {             /*ADD :hover */
    margin:4px;
    background-color:#EFEFEF;
    border-radius:4px;
    border:1px solid red;      /*change border color*/ 
    overflow:auto;
    float:left;
    color:red;                 /*add font color*/
}

Example: http://jsfiddle.net/zAFND/6/

Convert char to int in C#

By default you use UNICODE so I suggest using faulty's method

int bar = int.Parse(foo.ToString());

Even though the numeric values under are the same for digits and basic Latin chars.

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

ITextSharp HTML to PDF?

I would one-up'd mightymada's answer if I had the reputation - I just implemented an asp.net HTML to PDF solution using Pechkin. results are wonderful.

There is a nuget package for Pechkin, but as the above poster mentions in his blog (http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ - I hope she doesn't mind me reposting it), there's a memory leak that's been fixed in this branch:

https://github.com/tuespetre/Pechkin

The above blog has specific instructions for how to include this package (it's a 32 bit dll and requires .net4). here is my code. The incoming HTML is actually assembled via HTML Agility pack (I'm automating invoice generations):

public static byte[] PechkinPdf(string html)
{
  //Transform the HTML into PDF
  var pechkin = Factory.Create(new GlobalConfig());
  var pdf = pechkin.Convert(new ObjectConfig()
                          .SetLoadImages(true).SetZoomFactor(1.5)
                          .SetPrintBackground(true)
                          .SetScreenMediaType(true)
                          .SetCreateExternalLinks(true), html);

  //Return the PDF file
  return pdf;
}

again, thank you mightymada - your answer is fantastic.

How do I properly clean up Excel interop objects?

Tested with Microsoft Excel 2016

A really tested solution.

To C# Reference please see: https://stackoverflow.com/a/1307180/10442623

To VB.net Reference please see: https://stackoverflow.com/a/54044646/10442623

1 include the class job

2 implement the class to handle the apropiate dispose of excel proces

twitter bootstrap typeahead ajax example

One can make calls by using Bootstrap. The current version does not has any source update issues Trouble updating Bootstrap's typeahead data-source with post response , i.e. the source of bootstrap once updated can be again modified.

Please refer to below for an example:

jQuery('#help').typeahead({
    source : function(query, process) {
        jQuery.ajax({
            url : "urltobefetched",
            type : 'GET',
            data : {
                "query" : query
            },
            dataType : 'json',
            success : function(json) {
                process(json);
            }
        });
    },
    minLength : 1,
});

How to get previous month and year relative to today, using strtotime and date?

if i understand the question correctly you just want last month and the year it is in:

<?php

  $month = date('m');
  $year = date('Y');
  $last_month = $month-1%12;
  echo ($last_month==0?($year-1):$year)."-".($last_month==0?'12':$last_month);

?>

Here is the example: http://codepad.org/c99nVKG8

How to center-justify the last line of text in CSS?

Simple. Text-align: justify; (to get the elements aligned) Padding-left: ?px; (to center the elements)

jQuery If DIV Doesn't Have Class "x"

Use the "not" selector.

For example, instead of:

$(".thumbs").hover()

try:

$(".thumbs:not(.selected)").hover()

How to compute the sum and average of elements in an array?

I use these methods in my personal library:

Array.prototype.sum = Array.prototype.sum || function() {
  return this.reduce(function(sum, a) { return sum + Number(a) }, 0);
}

Array.prototype.average = Array.prototype.average || function() {
  return this.sum() / (this.length || 1);
}

EDIT: To use them, simply ask the array for its sum or average, like:

[1,2,3].sum() // = 6
[1,2,3].average() // = 2

C++ - unable to start correctly (0xc0150002)

In my case, Visual Leak Detector I was using to track down memory leaks in Visual Studio 2015 was missing the Microsoft manifest file Microsoft.DTfW.DHL.manifest, see link Building Visual Leak Detector all way down. This file must be in the folder where vld.dll or vld_x64.dll is in your configuration, say C:\Program Files (x86)\Visual Leak Detector\bin\Win32, C:\Program Files (x86)\Visual Leak Detector\bin\Win64, Debug or x64/Debug.

How to make in CSS an overlay over an image?

Putting this answer here as it is the top result in Google.

If you want a quick and simple way:

    filter: brightness(0.2);

*Not compatible with IE

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

In my case, one of the services either Apache, Apache2 or Nginx was already running and due to that I was not able to start the other service.

How to perform mouseover function in Selenium WebDriver using Java?

Sample program to mouse hover using Selenium java WebDriver :

public class Mhover {
    public static void main(String[] args){
       WebDriver driver = new FirefoxDriver();
       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       driver.get("http://www.google.com");
       WebElement ele = driver.findElement(By.id("gbqfba"));
       Actions action = new Actions(driver);
       action.moveToElement(ele).build().perform();
    }
}

How to replace part of string by position?

All others answers don't work if the string contains Unicode char (like Emojis) because an Unicode char weight more bytes than a char.

Example : the emoji '' converted to bytes, will weight the equivalent of 2 chars. So, if the unicode char is placed at the beginning of your string, offset parameter will be shifted).

With this topic, i extend the StringInfo class to Replace by position keeping the Nick Miller's algorithm to avoid that :

public static class StringInfoUtils
{
    public static string ReplaceByPosition(this string str, string replaceBy, int offset, int count)
    {
        return new StringInfo(str).ReplaceByPosition(replaceBy, offset, count).String;
    }

    public static StringInfo ReplaceByPosition(this StringInfo str, string replaceBy, int offset, int count)
    {
        return str.RemoveByTextElements(offset, count).InsertByTextElements(offset, replaceBy);
    }

    public static StringInfo RemoveByTextElements(this StringInfo str, int offset, int count)
    {
        return new StringInfo(string.Concat(
            str.SubstringByTextElements(0, offset),
            offset + count < str.LengthInTextElements
                ? str.SubstringByTextElements(offset + count, str.LengthInTextElements - count - offset)
                : ""
            ));
    }
    public static StringInfo InsertByTextElements(this StringInfo str, int offset, string insertStr)
    {
        if (string.IsNullOrEmpty(str?.String))
            return new StringInfo(insertStr);
        return new StringInfo(string.Concat(
            str.SubstringByTextElements(0, offset),
            insertStr,
            str.LengthInTextElements - offset > 0 ? str.SubstringByTextElements(offset, str.LengthInTextElements - offset) : ""
        ));
    }
}

Testing javascript with Mocha - how can I use console.log to debug a test?

If you are testing asynchronous code, you need to make sure to place done() in the callback of that asynchronous code. I had that issue when testing http requests to a REST API.

Vim autocomplete for Python

I found a good choice to be coc.nvim with the python language server.

It takes a bit of effort to set up. I got frustrated with jedi-vim, because it would always freeze vim for a bit when completing. coc.nvim doesn't do it because it's asyncronous, meaning that . It also gives you linting for your code. It supports many other languages and is highly configurable.

The python language server uses jedi so you get the same completion as you would get from jedi.

What is in your .vimrc?

When I launch gVim without arguments, I want it to open in my "project" directory, so that I can do :find etc. However, when I launch it with files, I don't want it to switch directory, I want it to stay right there (in part, so that it opens the file I want it to open!).

if argc() == 0
   cd $PROJECT_DIR
endif

So that I can use :find from any file in the current project, I set up my path to look up the directory tree 'til it finds src or scripts and descends into those, at least until it hits c:\work which is the root of all of my projects. This allows me to open files in a project that is not current (i.e. PROJECT_DIR above specifies a different directory).

set path+=src/**;c:/work,scripts/**;c:/work

So that I get automatic saving and reloading, and exiting of insert mode when gVim loses focus, as well as automatic checkout from Perforce when editing a readonly file...

augroup AutoSaveGroup
    autocmd!
    autocmd FocusLost       *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel    wa
    autocmd FileChangedRO   *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel    silent !p4 edit %:p
    autocmd FileChangedRO   *.cpp,*.h,*.cs,*.rad*,Jam*,*.py,*.bat,*.mel    w!
augroup END

augroup OutOfInsert
    autocmd!
    autocmd FocusLost * call feedkeys("\<C-\>\<C-N>")
augroup END

And finally, switch to the directory of the file in the current buffer so that it's easy to :e other files in that directory.

augroup MiscellaneousTomStuff
    autocmd!
    " make up for the deficiencies in 'autochdir'
    autocmd BufEnter * silent! lcd %:p:h:gs/ /\\ /
augroup END

Using XPATH to search text containing &nbsp;

I found I can make the match when I input a hard-coded non-breaking space (U+00A0) by typing Alt+0160 on Windows between the two quotes...

//table[@id='TableID']//td[text()=' ']

worked for me with the special char.

From what I understood, the XPath 1.0 standard doesn't handle escaping Unicode chars. There seems to be functions for that in XPath 2.0 but it looks like Firefox doesn't support it (or I misunderstood something). So you have to do with local codepage. Ugly, I know.

Actually, it looks like the standard is relying on the programming language using XPath to provide the correct Unicode escape sequence... So, somehow, I did the right thing.

How to set the opacity/alpha of a UIImage?

If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:

    UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
//  UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);

If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.

Hopefully, this reply will save beginners a lot of aggravation.

JSON order mixed up

You cannot and should not rely on the ordering of elements within a JSON object.

From the JSON specification at http://www.json.org/

An object is an unordered set of name/value pairs

As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.

How do I display images from Google Drive on a website?

1 - Create a folder in your google drive;

2 - Make this folder public (on share property)

3 - use something like this as your image src: https://drive.google.com/thumbnail?id=${imageId}&sz=w${width || 200}-h${height || 200}

How to put a List<class> into a JSONObject and then read that object?

Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<String>();

    //if List not empty
    if (!(sList.size() ==0)) {

        //Loop index size()
        for(int index = 0; index < sList.size(); index++) {
            JSONObject eachData = new JSONObject();
            try {
                eachData.put("name", sList.get(index).getName());
                eachData.put("dob", sList.get(index).getDob());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            allDataArray.put(eachData);
        }
    } else {
        //Do something when sList is empty
    }

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();
    try {
        root.put("data", allDataArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

You can further get this data as a String too.

String jsonString = root.toString();

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How do I check what version of Python is running my script?

Just for fun, the following is a way of doing it on CPython 1.0-3.7b2, Pypy, Jython and Micropython. This is more of a curiosity than a way of doing it in modern code. I wrote it as part of http://stromberg.dnsalias.org/~strombrg/pythons/ , which is a script for testing a snippet of code on many versions of python at once, so you can easily get a feel for what python features are compatible with what versions of python:

via_platform = 0
check_sys = 0
via_sys_version_info = 0
via_sys_version = 0
test_sys = 0
try:
    import platform
except (ImportError, NameError):
    # We have no platform module - try to get the info via the sys module
    check_sys = 1

if not check_sys:
    if hasattr(platform, "python_version"):
        via_platform = 1
    else:
        check_sys = 1

if check_sys:
    try:
        import sys
        test_sys = 1
    except (ImportError, NameError):
        # just let via_sys_version_info and via_sys_version remain False - we have no sys module
        pass

if test_sys:
    if hasattr(sys, "version_info"):
        via_sys_version_info = 1
    elif hasattr(sys, "version"):
        via_sys_version = 1
    else:
        # just let via_sys remain False
        pass

if via_platform:
    # This gives pretty good info, but is not available in older interpreters.  Also, micropython has a
    # platform module that does not really contain anything.
    print(platform.python_version())
elif via_sys_version_info:
    # This is compatible with some older interpreters, but does not give quite as much info.
    print("%s.%s.%s" % sys.version_info[:3])
elif via_sys_version:
    import string
    # This is compatible with some older interpreters, but does not give quite as much info.
    verbose_version = sys.version
    version_list = string.split(verbose_version)
    print(version_list[0])
else:
    print("unknown")

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

This is caused by a gradle dependency on some out-of-date thing which causes the error. Remove gradle dependencies until the error stops appearing. For me, it was:

implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'

This line needed to be updated to a newer version such as:

api group: 'commons-io', name: 'commons-io', version: '2.6'

Find a class somewhere inside dozens of JAR files?

You can use locate and grep:

locate jar | xargs grep 'my.class'

Make sure you run updatedb before using locate.

What is the difference between null and undefined in JavaScript?

Please read the following carefully. It should remove all your doubts regarding the difference between null and undefined in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.

In JavaScript we can have the following types of variables:

  1. Undeclared Variables
  2. Declared but Unassigned Variables
  3. Variables assigned with literal undefined
  4. Variables assigned with literal null
  5. Variables assigned with anything other than undefined or null

The following explains each of these cases one by one:

  1. Undeclared Variables

    • Can only be checked with the typeof operator which returns string 'undefined'
    • Cannot be checked with the loose equality operator ( == undefined ), let alone the strict equality operator ( === undefined ),
      as well as if-statements and ternary operators ( ? : ) — these throw Reference Errors
  2. Declared but Unassigned Variables

    • typeof returns string 'undefined'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns false
    • === check with undefined returns true
    • Is falsy to if-statements and ternary operators ( ? : )
  3. Variables assigned with literal undefined
    These variables are treated exactly the same as Declared But Unassigned Variables.

  4. Variables assigned with literal null

    • typeof returns string 'object'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns true
    • === check with undefined returns false
    • Is falsy to if-statements and ternary operators ( ? : )
  5. Variables assigned with anything other than undefined or null

    • typeof returns one of the following strings: 'bigint', 'boolean', 'function', 'number', 'object', 'string', 'symbol'

Following provides the algorithm for correct type checking of a variable:

  1. Get the typeof our variable and return it if it isn't 'object'
  2. Check for null, as typeof null returns 'object' as well
  3. Evaluate Object.prototype.toString.call(o) with a switch statement to return a more precise value. Object's toString method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'
  4. If that last part is the case (the stringified version of the variable being '[object Object]') and the parameter returnConstructorBoolean is true, it will try to get the name of the constructor by toString-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned

(supports all types up to ECMAScript 2020)

function TypeOf(o, returnConstructorBoolean) {
  const type = typeof o

  if (type !== 'object') return type
  if (o === null)        return 'null'

  const toString = Object.prototype.toString.call(o)

  switch (toString) {
    // Value types: 6
    case '[object BigInt]':            return 'bigint'
    case '[object Boolean]':           return 'boolean'
    case '[object Date]':              return 'date'
    case '[object Number]':            return 'number'
    case '[object String]':            return 'string'
    case '[object Symbol]':            return 'symbol'

    // Error types: 7
    case '[object Error]':             return 'error'
    case '[object EvalError]':         return 'evalerror'
    case '[object RangeError]':        return 'rangeerror'
    case '[object ReferenceError]':    return 'referenceerror'
    case '[object SyntaxError]':       return 'syntaxerror'
    case '[object TypeError]':         return 'typeerror'
    case '[object URIError]':          return 'urierror'

    // Indexed Collection and Helper types: 13
    case '[object Array]':             return 'array'
    case '[object Int8Array]':         return 'int8array'
    case '[object Uint8Array]':        return 'uint8array'
    case '[object Uint8ClampedArray]': return 'uint8clampedarray'
    case '[object Int16Array]':        return 'int16array'
    case '[object Uint16Array]':       return 'uint16array'
    case '[object Int32Array]':        return 'int32array'
    case '[object Uint32Array]':       return 'uint32array'
    case '[object Float32Array]':      return 'float32array'
    case '[object Float64Array]':      return 'float64array'
    case '[object ArrayBuffer]':       return 'arraybuffer'
    case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
    case '[object DataView]':          return 'dataview'

    // Keyed Collection types: 2
    case '[object Map]':               return 'map'
    case '[object WeakMap]':           return 'weakmap'

    // Set types: 2
    case '[object Set]':               return 'set'
    case '[object WeakSet]':           return 'weakset'

    // Operation types: 3
    case '[object RegExp]':            return 'regexp'
    case '[object Proxy]':             return 'proxy'
    case '[object Promise]':           return 'promise'

    // Plain objects
    case '[object Object]':
      if (!returnConstructorBoolean)
        return type

      const _prototype = Object.getPrototypeOf(o)
      if (!_prototype)              
        return type

      const _constructor = _prototype.constructor
      if (!_constructor)            
        return type

      const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
        return matches ? matches[1] : 'anonymous'

    default: return toString.split(' ')[1].slice(0, -1)
  }
}

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

How to detect duplicate values in PHP array?

$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
    $eachArrayValue = $array[$i];
    if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
        for( $j=$i; $j < sizeof($array); $j++) {
            if ($array[$j] === $eachArrayValue) {
                $count++;
            }
        }
        $ischeckedvalueArray[] = $eachArrayValue;
        $output .= $eachArrayValue. " Repated ". $count."<br/>";
        $count = 0;
    }

}

echo $output;

How to add number of days to today's date?

The prototype-solution from Krishna Chytanya is very nice, but needs a minor but important improvement. The days param must be parsed as Integer to avoid weird calculations when days is a String like "1". (I needed several hours to find out, what went wrong in my application.)

Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + parseInt(days));
    return this;
};

Even if you do not use this prototype function: Always be sure to have an Integer when using setDate().

Setting table row height

try setting the attribute for td so:

.topic td{ height: 14px };

How to modify a text file?

As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it.

If you're dealing with a small file or have no memory issues this might help:

Option 1) Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.

# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')   
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()

Option 2) Figure out middle line, and replace it with that line plus the extra line.

# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')   
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()

Replace negative values in an numpy array

Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.

>>> a = [1, 2, 3, -4, 5]

>>> def zero_if_negative(x):
...   if x < 0:
...     return 0
...   return x
...

>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]

>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]

Vector erase iterator

You increment it past the end of the (empty) container in the for loop's loop expression.

What is the difference between i++ and ++i?

int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.

Does this answer your question ?

What is the boundary in multipart/form-data?

multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.

The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).

The payload passed looks something like this:

Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”file”; filename=”captcha”
    Content-Type:

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”action”

    submit
    -----WebKitFormBoundary7MA4YWxkTrZu0gW--

On the webservice side, it's consumed in @Consumes("multipart/form-data") form.

Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.

See RFC1341 sec7.2 The Multipart Content-Type

what is the use of "response.setContentType("text/html")" in servlet

From JavaEE docs ServletResponse#setContentType

  • Sets the content type of the response being sent to the client, if the response has not been committed yet.

  • The given content type may include a character encoding specification, for example,

response.setContentType("text/html;charset=UTF-8");

  • The response's character encoding is only set from the given content type if this method is called before getWriter is called.

  • This method may be called repeatedly to change content type and character encoding.

  • This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter has been called or after the response has been committed.

  • Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.

Find a line in a file and remove it

This solution uses a RandomAccessFile to only cache the portion of the file subsequent to the string to remove. It scans until it finds the String you want to remove. Then it copies all of the data after the found string, then writes it over the found string, and everything after. Last, it truncates the file size to remove the excess data.

public static long scanForString(String text, File file) throws IOException {
    if (text.isEmpty())
        return file.exists() ? 0 : -1;
    // First of all, get a byte array off of this string:
    byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);

    // Next, search the file for the byte array.
    try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {

        List<Integer> matches = new LinkedList<>();

        for (long pos = 0; pos < file.length(); pos++) {
            byte bite = dis.readByte();

            for (int i = 0; i < matches.size(); i++) {
                Integer m = matches.get(i);
                if (bytes[m] != bite)
                    matches.remove(i--);
                else if (++m == bytes.length)
                    return pos - m + 1;
                else
                    matches.set(i, m);
            }

            if (bytes[0] == bite)
                matches.add(1);
        }
    }
    return -1;
}

public static void remove(String text, File file) throws IOException {
    try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) {
        long scanForString = scanForString(text, file);
        if (scanForString == -1) {
            System.out.println("String not found.");
            return;
        }
        long remainderStartPos = scanForString + text.getBytes().length;
        rafile.seek(remainderStartPos);
        int remainderSize = (int) (rafile.length() - rafile.getFilePointer());
        byte[] bytes = new byte[remainderSize];
        rafile.read(bytes);
        rafile.seek(scanForString);

        rafile.write(bytes);
        rafile.setLength(rafile.length() - (text.length()));
    }
}

Usage:

File Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method Call: remove("ABC", new File("Drive:/Path/File.extension"));

Resulting Contents: DEFGHIJKLMNOPQRSTUVWXYZ

This solution could easily be modified to remove with a certain, specifiable cacheSize, if memory is a concern. This would just involve iterating over the rest of the file to continually replace portions of size, cacheSize. Regardless, this solution is generally much better than caching an entire file in memory, or copying it to a temporary directory, etc.

Display back button on action bar

Add below code in the onCreate function:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And then override: @Override public boolean onOptionsItemSelected(MenuItem item){ onBackPressed(); return true; }

Are "while(true)" loops so bad?

I guess using break to your teacher is like breaking a branch of tree to get the fruit,use some other tricks (bow the branch) so that you get the fruit and the branch is still alive.:)

What exactly are DLL files, and how do they work?

What is a DLL?

Dynamic Link Libraries (DLL)s are like EXEs but they are not directly executable. They are similar to .so files in Linux/Unix. That is to say, DLLs are MS's implementation of shared libraries.

DLLs are so much like an EXE that the file format itself is the same. Both EXE and DLLs are based on the Portable Executable (PE) file format. DLLs can also contain COM components and .NET libraries.

What does a DLL contain?

A DLL contains functions, classes, variables, UIs and resources (such as icons, images, files, ...) that an EXE, or other DLL uses.

Types of libraries:

On virtually all operating systems, there are 2 types of libraries. Static libraries and dynamic libraries. In windows the file extensions are as follows: Static libraries (.lib) and dynamic libraries (.dll). The main difference is that static libraries are linked to the executable at compile time; whereas dynamic linked libraries are not linked until run-time.

More on static and dynamic libraries:

You don't normally see static libraries though on your computer, because a static library is embedded directly inside of a module (EXE or DLL). A dynamic library is a stand-alone file.

A DLL can be changed at any time and is only loaded at runtime when an EXE explicitly loads the DLL. A static library cannot be changed once it is compiled within the EXE. A DLL can be updated individually without updating the EXE itself.

Loading a DLL:

A program loads a DLL at startup, via the Win32 API LoadLibrary, or when it is a dependency of another DLL. A program uses the GetProcAddress to load a function or LoadResource to load a resource.

Further reading:

Please check MSDN or Wikipedia for further reading. Also the sources of this answer.

Linear Layout and weight in Android

Below are the changes (Marked in BOLD) in your code:

<LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

  </LinearLayout>

Since your LinearLayout has orientation as horizontal, therefore you will need to keep your width only as 0dp. for using weights in that direction . (If your orientation was vertical, you would have kept your height only 0dp).

Since there are 2 views and you have placed android:layout_weight="1" for both the views, it means it will divide the two views equally in horizontal direction (or by width).

svn list of files that are modified in local copy

Below command will display the modfied files alone in windows.

svn status | findstr "^M"

Custom CSS for <audio> tag?

I discovered quite by accident (I was working with images at the time) that the box-shadow, border-radius and transitions work quite well with the bog-standard audio tag player. I have this working in Chrome, FF and Opera.

audio:hover, audio:focus, audio:active
{
-webkit-box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
-moz-box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);
-webkit-transform: scale(1.05);
-moz-transform: scale(1.05);
transform: scale(1.05);
}

with:-

audio
{
-webkit-transition:all 0.5s linear;
-moz-transition:all 0.5s linear;
-o-transition:all 0.5s linear;
transition:all 0.5s linear;
-moz-box-shadow: 2px 2px 4px 0px #006773;
-webkit-box-shadow:  2px 2px 4px 0px #006773;
box-shadow: 2px 2px 4px 0px #006773;
-moz-border-radius:7px 7px 7px 7px ;
-webkit-border-radius:7px 7px 7px 7px ;
border-radius:7px 7px 7px 7px ;
}

I grant you it only "tarts it up a bit", but it makes them a sight more exciting than what's already there, and without doing MAJOR fannying about in JS.

NOT available in IE, unfortunately (not yet supporting the transition bit), but it seems to degrade nicely.

Python - Check If Word Is In A String

if 'seek' in 'those who seek shall find':
    print('Success!')

but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, 'word' in 'swordsmith' is True. If you only want to match whole words, you ought to use regular expressions:

import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

$watch'ing for data changes in an Angular directive

My version for a directive that uses jqplot to plot the data once it becomes available:

    app.directive('lineChart', function() {
        $.jqplot.config.enablePlugins = true;

        return function(scope, element, attrs) {
            scope.$watch(attrs.lineChart, function(newValue, oldValue) {
                if (newValue) {
                    // alert(scope.$eval(attrs.lineChart));
                    var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
                }
            });
        }
});

Angular - ng: command not found

100% working solution

1) rm -rf /usr/local/lib/node_modules

2)brew uninstall node

3)echo prefix=~/.npm-packages >> ~/.npmrc

4)brew install node

5) npm install -g @angular/cli

Finally and most importantly

6) export PATH="$HOME/.npm-packages/bin:$PATH"

Also if any editor still shown err than write

7) point over there .

100% working

Oracle: how to set user password unexpire?

The following statement causes a user's password to expire:

ALTER USER user PASSWORD EXPIRE;

If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.

ALTER USER scott IDENTIFIED BY password;

Will set/reset the users password.

See the alter user doc for more info

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

How to delete a cookie?

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

Replace values in list using Python

>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

eval command in Bash and its typical uses

You asked about typical uses.

One common complaint about shell scripting is that you (allegedly) can't pass by reference to get values back out of functions.

But actually, via "eval", you can pass by reference. The callee can pass back a list of variable assignments to be evaluated by the caller. It is pass by reference because the caller can allowed to specify the name(s) of the result variable(s) - see example below. Error results can be passed back standard names like errno and errstr.

Here is an example of passing by reference in bash:

#!/bin/bash
isint()
{
    re='^[-]?[0-9]+$'
    [[ $1 =~ $re ]]
}

#args 1: name of result variable, 2: first addend, 3: second addend 
iadd()
{
    if isint ${2} && isint ${3} ; then
        echo "$1=$((${2}+${3}));errno=0"
        return 0
    else
        echo "errstr=\"Error: non-integer argument to iadd $*\" ; errno=329"
        return 1
    fi
}

var=1
echo "[1] var=$var"

eval $(iadd var A B)
if [[ $errno -ne 0 ]]; then
    echo "errstr=$errstr"
    echo "errno=$errno"
fi
echo "[2] var=$var (unchanged after error)"

eval $(iadd var $var 1)
if [[ $errno -ne 0 ]]; then
    echo "errstr=$errstr"
    echo "errno=$errno"
fi  
echo "[3] var=$var (successfully changed)"

The output looks like this:

[1] var=1
errstr=Error: non-integer argument to iadd var A B
errno=329
[2] var=1 (unchanged after error)
[3] var=2 (successfully changed)

There is almost unlimited band width in that text output! And there are more possibilities if the multiple output lines are used: e.g., the first line could be used for variable assignments, the second for continuous 'stream of thought', but that's beyond the scope of this post.

"RangeError: Maximum call stack size exceeded" Why?

The answer with for is correct, but if you really want to use functional style avoiding for statement - you can use the following instead of your expression:

Array.from(Array(1000000), () => Math.random());

The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.

Following the same idea you can rewrite it using ES2015 Spread operator:

[...Array(1000000)].map(() => Math.random())

In both examples you can get an index of the iteration if you need, for example:

[...Array(1000000)].map((_, i) => i + Math.random())

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

Using Abizern code for swift 2.2

let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)

PHP shell_exec() vs exec()

Here are the differences. Note the newlines at the end.

> shell_exec('date')
string(29) "Wed Mar  6 14:18:08 PST 2013\n"
> exec('date')
string(28) "Wed Mar  6 14:18:12 PST 2013"

> shell_exec('whoami')
string(9) "mark\n"
> exec('whoami')
string(8) "mark"

> shell_exec('ifconfig')
string(1244) "eth0      Link encap:Ethernet  HWaddr 10:bf:44:44:22:33  \n          inet addr:192.168.0.90  Bcast:192.168.0.255  Mask:255.255.255.0\n          inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n          TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:13151177627 (13.1 GB)  TX bytes:2779457335 (2.7 GB)\n"...
> exec('ifconfig')
string(0) ""

Note that use of the backtick operator is identical to shell_exec().

Update: I really should explain that last one. Looking at this answer years later even I don't know why that came out blank! Daniel explains it above -- it's because exec only returns the last line, and ifconfig's last line happens to be blank.

Saving an image in OpenCV

I know the problem! You just put a dot after "test.jpg"!

cvSaveImage("test.jpg". ,pSaveImg);

I may be wrong but I think its not good!

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

Within your app in the Android Emulator press Command + M on macOS or Ctrl + M on Linux and Windows.

"Data too long for column" - why?

With Hibernate you can create your own UserType. So thats what I did for this issue. Something as simple as this:

    public class BytesType implements org.hibernate.usertype.UserType {

         private final int[] SQL_TYPES = new int[] { java.sql.Types.VARBINARY };
     //...
    }

There of course is more to implement from extending your own UserType but I just wanted to throw that out there for anyone looking for other methods.

How can I use interface as a C# generic type constraint?

If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.

  • I let my interfaces, which came into question, inherit an empty interface IInterface.
  • I constrained the generic T parameter to be of IInterface

In source, it looks like this:

  • Any interface you want to be passed as the generic parameter:

    public interface IWhatever : IInterface
    {
        // IWhatever specific declarations
    }
    
  • IInterface:

    public interface IInterface
    {
        // Nothing in here, keep moving
    }
    
  • The class on which you want to put the type constraint:

    public class WorldPeaceGenerator<T> where T : IInterface
    {
        // Actual world peace generating code
    }
    

@Value annotation type casting to Integer from String

I had the same issue I solved using this. Refer this Spring MVC: @Value annotation to get int value defined in *.properties file

@Value(#{propertyfileId.propertyName})

works

Regular expression for not allowing spaces in the input field

Use + plus sign (Match one or more of the previous items),

var regexp = /^\S+$/

Compare two objects in Java with possible null values

boolean compare(String str1, String str2) {
  return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}

int to string in MySQL

If you have a column called "col1" which is int, you cast it to String like this:

CONVERT(col1,char)

e.g. this allows you to check an int value is containing another value (here 9) like this:

CONVERT(col1,char) LIKE '%9%'

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

Reading in double values with scanf in c

As far as i know %d means decadic which is number without decimal point. if you want to load double value, use %lf conversion (long float). for printf your values are wrong for same reason, %d is used only for integer (and possibly chars if you know what you are doing) numbers.

Example:

double a,b;
printf("--------\n"); //seperate lines
scanf("%lf",&a);
printf("--------\n"); 
scanf("%lf",&b);
printf("%lf %lf",a,b);

How to detect if numpy is installed

Option 1:

Use following command in python ide.:

import numpy

Option 2:

Go to Python -> site-packages folder. There you should be able to find numpy and the numpy distribution info folder.

If any of the above is true then you installed numpy successfully.

What is the difference between git clone and checkout?

checkout can be use for many case :

1st case : switch between branch in local repository For instance : git checkout exists_branch_to_switch

You can also create new branch and switch out in throught this case with -b

git checkout -b new_branch_to_switch

2nd case : restore file from x rev

git checkout rev file_to_restore ...

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2
...

:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

How do I parse a string to a float or int?

The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:

   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

Get div height with plain JavaScript

One option would be

const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);

How to paste text to end of every line? Sublime 2

Here's the workflow I use all the time, using the keyboard only

  1. Ctrl/Cmd + A Select All
  2. Ctrl/Cmd + Shift + L Split into Lines
  3. ' Surround every line with quotes

Note that this doesn't work if there are blank lines in the selection.

Convert a tensor to numpy array in Tensorflow?

You can convert a tensor in tensorflow to numpy array in the following ways.

First: Use np.array(your_tensor)

Second: Use your_tensor.numpy

Android studio - Failed to find target android-18

You can solve the problem changing the compileSdkVersion in the Grandle.build file from 18 to wtever SDK is installed ..... BUTTTTT

  1. If you are trying to goin back in SDK versions like 18 to 17 ,You can not use the feature available in 18 or 18+

  2. If you are migrating your project (Eclipse to Android Studio ) Then off course you Don't have build.gradle file in your Existed Eclipse project

So, the only solution is to ensure the SDK version installed or not, you are targeting to , If not then install.

Error:Cause: failed to find target with hash string 'android-19' in: C:\Users\setia\AppData\Local\Android\sdk

How to reference a file for variables using Bash?

Use the source command to import other scripts:

#!/bin/bash
source /REFERENCE/TO/CONFIG.FILE
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

How do I search an SQL Server database for a string?

For getting a table by name in SQL Server:

SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'

For finding a stored procedure by name:

SELECT name
FROM sys.objects
WHERE name = 'spName'

To get all stored procedures related to a table:

----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'

Pass variables to Ruby script via command line

Unless it is the most trivial case, there is only one sane way to use command line options in Ruby. It is called docopt and documented here.

What is amazing with it, is it's simplicity. All you have to do, is specify the "help" text for your command. What you write there will then be auto-parsed by the standalone (!) ruby library.

From the example:

#!/usr/bin/env ruby
require 'docopt.rb'

doc = <<DOCOPT
Usage: #{__FILE__} --help
       #{__FILE__} -v...
       #{__FILE__} go [go]
       #{__FILE__} (--path=<path>)...
       #{__FILE__} <file> <file>

Try: #{__FILE__} -vvvvvvvvvv
     #{__FILE__} go go
     #{__FILE__} --path ./here --path ./there
     #{__FILE__} this.txt that.txt

DOCOPT

begin
  require "pp"
  pp Docopt::docopt(doc)
rescue Docopt::Exit => e
  puts e.message
end

The output:

$ ./counted_example.rb -h
Usage: ./counted_example.rb --help
       ./counted_example.rb -v...
       ./counted_example.rb go [go]
       ./counted_example.rb (--path=<path>)...
       ./counted_example.rb <file> <file>

Try: ./counted_example.rb -vvvvvvvvvv
     ./counted_example.rb go go
     ./counted_example.rb --path ./here --path ./there
     ./counted_example.rb this.txt that.txt

$ ./counted_example.rb something else
{"--help"=>false,
 "-v"=>0,
 "go"=>0,
 "--path"=>[],
 "<file>"=>["something", "else"]}

$ ./counted_example.rb -v
{"--help"=>false, "-v"=>1, "go"=>0, "--path"=>[], "<file>"=>[]}

$ ./counted_example.rb go go
{"--help"=>false, "-v"=>0, "go"=>2, "--path"=>[], "<file>"=>[]}

Enjoy!

Margin on child element moves parent element

Found an alternative at Child elements with margins within DIVs You can also add:

.parent { overflow: auto; }

or:

.parent { overflow: hidden; }

This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:

.parent {
    padding-top: 1px;
    margin-top: -1px;
}

Update by popular request: The whole point of collapsing margins is handling textual content. For example:

_x000D_
_x000D_
h1, h2, p, ul {_x000D_
  margin-top: 1em;_x000D_
  margin-bottom: 1em;_x000D_
}
_x000D_
<h1>Title!</h1>_x000D_
<div class="text">_x000D_
  <h2>Title!</h2>_x000D_
  <p>Paragraph</p>_x000D_
</div>_x000D_
<div class="text">_x000D_
  <h2>Title!</h2>_x000D_
  <p>Paragraph</p>_x000D_
  <ul>_x000D_
    <li>list item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Because the browser collapses margins, the text would appear as you'd expect, and the <div> wrapper tags don't influence the margins. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the <h2> and <p> won't add up, but slide into each other (they collapse). The same happens for the <p> and <ul> element.

Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The overflow or margin trick will give you that.

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

How to use log levels in java

Those are the levels. You'd consider the severity of the message you're logging, and use the appropriate levels.

It's basically a watermark; the higher the level, the more likely you want to retain the information in the log entry. FINEST would be for messages that are of very little importance, so you'd use it for things you usually don't care about but might want to see in some rare circumstance.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

window.location = appurl;// fb://method/call..
!window.document.webkitHidden && setTimeout(function () {
    setTimeout(function () {
    window.location = weburl; // http://itunes.apple.com/..
    }, 100);
}, 600);

document.webkitHidden is to detect if your app is already invoked and current safari tab to going to the background, this code is from www.baidu.com

PHP how to get local IP of system

$_SERVER['SERVER_ADDR']

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

jQuery get value of selected radio button

Here are 2 radio buttons namely rd1 and Radio1

<input type="radio" name="rd" id="rd1" />
<input type="radio" name="rd" id="Radio1" /> 

The simplest wayt to check which radio button is checked ,by checking individual is(":checked") property

if ($("#rd1").is(":checked")) {
      alert("rd1 checked");
   }
 else {
      alert("rd1 not checked");
   }

Convert array to string in NodeJS

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.

Django - makemigrations - No changes detected

The possible reason could be deletion of the existing db file and migrations folder you can use python manage.py makemigrations <app_name> this should work. I once faced a similar problem.

Ajax success event not working

Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.

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

Pure JavaScript answer:

document.querySelector('.menu').classList.contains('active');

Might help someone someday.

How do I open multiple instances of Visual Studio Code?

If you want to open multiple instances of the same folder, then it is not currently supported. Watch and upvote this GitHub issue if you want to see it implemented: Support to open a project folder in multiple Visual Studio Code windows

Date object to Calendar [Java]

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

Is there an effective tool to convert C# code to Java code?

I'm not sure what you are trying to do by wishing to convert C# to java, but if it is .net interoperability that you need, you might want to check out Mono

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

You can also use a formula in excel in order to convert this type of date to a date type excel can read: =DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))

And you get: 12/7/2016 from: Wed Dec 07 00:00:00 UTC 2016

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

Loop through childNodes

I'm very late to the party, but since element.lastChild.nextSibling === null, the following seems like the most straightforward option to me:

for(var child=element.firstChild; child!==null; child=child.nextSibling) {
    console.log(child);
}

In C++ check if std::vector<string> contains a certain value

In C++11, you can use std::any_of instead.

An example to find if there is any zero in the array:

std::array<int,3> foo = {0,1,-1};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "zero found...";

How to insert current_timestamp into Postgres via python

If you use psycopg2 (and possibly some other client library), you can simply pass a Python datetime object as a parameter to a SQL-query:

from datetime import datetime, timezone

dt = datetime.now(timezone.utc)
cur.execute('INSERT INTO mytable (mycol) VALUES (%s)', (dt,))

(This assumes that the timestamp with time zone type is used on the database side.)

More Python types that can be adapted into SQL (and returned as Python objects when a query is executed) are listed here.

How to access form methods and controls from a class in C#?

You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.

If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.

Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg

public void DoSomethingWithText(string formText)
{
   // do something text in here
}

or exposing properties on your form class and setting the form text in there - eg

string SomeProperty
{
   get 
   {
      return textBox1.Text;
   }
   set
   {
      textBox1.Text = value;
   }
}

PHP check if url parameter exists

if(isset($_GET['id']))
{
    // Do something
}

You want something like that

Can someone give an example of cosine similarity, in a very simple, graphical way?

This Python code is my quick and dirty attempt to implement the algorithm:

import math
from collections import Counter

def build_vector(iterable1, iterable2):
    counter1 = Counter(iterable1)
    counter2 = Counter(iterable2)
    all_items = set(counter1.keys()).union(set(counter2.keys()))
    vector1 = [counter1[k] for k in all_items]
    vector2 = [counter2[k] for k in all_items]
    return vector1, vector2

def cosim(v1, v2):
    dot_product = sum(n1 * n2 for n1, n2 in zip(v1, v2) )
    magnitude1 = math.sqrt(sum(n ** 2 for n in v1))
    magnitude2 = math.sqrt(sum(n ** 2 for n in v2))
    return dot_product / (magnitude1 * magnitude2)


l1 = "Julie loves me more than Linda loves me".split()
l2 = "Jane likes me more than Julie loves me or".split()


v1, v2 = build_vector(l1, l2)
print(cosim(v1, v2))

How to update maven repository in Eclipse?

In newer versions of Eclipse that use the M2E plugin it is:

Right-click on your project(s) --> Maven --> Update Project...

In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")

How to change option menu icon in the action bar?

//just edit menu.xml file    
//add icon for item which will change default setting icon
//add sub menus


 ///menu.xml file


    <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            android:icon="@drawable/your_icon"
            app:showAsAction="always" >

            <menu>

                <item android:id="@+id/action_menu1"
                    android:icon="@android:drawable/ic_menu_preferences"
                    android:title="menu 1" />

                <item android:id="@+id/action_menu2"
                    android:icon="@android:drawable/ic_menu_help"
                    android:title="menu 2" />

            </menu>
        </item>

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

JavaScript global event mechanism

It seems that window.onerror doesn't provide access to all possible errors. Specifically it ignores:

  1. <img> loading errors (response >= 400).
  2. <script> loading errors (response >= 400).
  3. global errors if you have many other libraries in your app also manipulating window.onerror in an unknown way (jquery, angular, etc.).
  4. probably many cases I haven't run into after exploring this now (iframes, stack overflow, etc.).

Here is the start of a script that catches many of these errors, so that you may add more robust debugging to your app during development.

(function(){

/**
 * Capture error data for debugging in web console.
 */

var captures = [];

/**
 * Wait until `window.onload`, so any external scripts
 * you might load have a chance to set their own error handlers,
 * which we don't want to override.
 */

window.addEventListener('load', onload);

/**
 * Custom global function to standardize 
 * window.onerror so it works like you'd think.
 *
 * @see http://www.quirksmode.org/dom/events/error.html
 */

window.onanyerror = window.onanyerror || onanyerrorx;

/**
 * Hook up all error handlers after window loads.
 */

function onload() {
  handleGlobal();
  handleXMLHttp();
  handleImage();
  handleScript();
  handleEvents();
}

/**
 * Handle global window events.
 */

function handleGlobal() {
  var onerrorx = window.onerror;
  window.addEventListener('error', onerror);

  function onerror(msg, url, line, col, error) {
    window.onanyerror.apply(this, arguments);
    if (onerrorx) return onerrorx.apply(null, arguments);
  }
}

/**
 * Handle ajax request errors.
 */

function handleXMLHttp() {
  var sendx = XMLHttpRequest.prototype.send;
  window.XMLHttpRequest.prototype.send = function(){
    handleAsync(this);
    return sendx.apply(this, arguments);
  };
}

/**
 * Handle image errors.
 */

function handleImage() {
  var ImageOriginal = window.Image;
  window.Image = ImageOverride;

  /**
   * New `Image` constructor. Might cause some problems,
   * but not sure yet. This is at least a start, and works on chrome.
   */

  function ImageOverride() {
    var img = new ImageOriginal;
    onnext(function(){ handleAsync(img); });
    return img;
  }
}

/**
 * Handle script errors.
 */

function handleScript() {
  var HTMLScriptElementOriginal = window.HTMLScriptElement;
  window.HTMLScriptElement = HTMLScriptElementOverride;

  /**
   * New `HTMLScriptElement` constructor.
   *
   * Allows us to globally override onload.
   * Not ideal to override stuff, but it helps with debugging.
   */

  function HTMLScriptElementOverride() {
    var script = new HTMLScriptElement;
    onnext(function(){ handleAsync(script); });
    return script;
  }
}

/**
 * Handle errors in events.
 *
 * @see http://stackoverflow.com/questions/951791/javascript-global-error-handling/31750604#31750604
 */

function handleEvents() {
  var addEventListenerx = window.EventTarget.prototype.addEventListener;
  window.EventTarget.prototype.addEventListener = addEventListener;
  var removeEventListenerx = window.EventTarget.prototype.removeEventListener;
  window.EventTarget.prototype.removeEventListener = removeEventListener;

  function addEventListener(event, handler, bubble) {
    var handlerx = wrap(handler);
    return addEventListenerx.call(this, event, handlerx, bubble);
  }

  function removeEventListener(event, handler, bubble) {
    handler = handler._witherror || handler;
    removeEventListenerx.call(this, event, handler, bubble);
  }

  function wrap(fn) {
    fn._witherror = witherror;

    function witherror() {
      try {
        fn.apply(this, arguments);
      } catch(e) {
        window.onanyerror.apply(this, e);
        throw e;
      }
    }
    return fn;
  }
}

/**
 * Handle image/ajax request errors generically.
 */

function handleAsync(obj) {
  var onerrorx = obj.onerror;
  obj.onerror = onerror;
  var onabortx = obj.onabort;
  obj.onabort = onabort;
  var onloadx = obj.onload;
  obj.onload = onload;

  /**
   * Handle `onerror`.
   */

  function onerror(error) {
    window.onanyerror.call(this, error);
    if (onerrorx) return onerrorx.apply(this, arguments);
  };

  /**
   * Handle `onabort`.
   */

  function onabort(error) {
    window.onanyerror.call(this, error);
    if (onabortx) return onabortx.apply(this, arguments);
  };

  /**
   * Handle `onload`.
   *
   * For images, you can get a 403 response error,
   * but this isn't triggered as a global on error.
   * This sort of standardizes it.
   *
   * "there is no way to get the HTTP status from a 
   * request made by an img tag in JavaScript."
   * @see http://stackoverflow.com/questions/8108636/how-to-get-http-status-code-of-img-tags/8108646#8108646
   */

  function onload(request) {
    if (request.status && request.status >= 400) {
      window.onanyerror.call(this, request);
    }
    if (onloadx) return onloadx.apply(this, arguments);
  }
}

/**
 * Generic error handler.
 *
 * This shows the basic implementation, 
 * which you could override in your app.
 */

function onanyerrorx(entity) {
  var display = entity;

  // ajax request
  if (entity instanceof XMLHttpRequest) {
    // 400: http://example.com/image.png
    display = entity.status + ' ' + entity.responseURL;
  } else if (entity instanceof Event) {
    // global window events, or image events
    var target = entity.currentTarget;
    display = target;
  } else {
    // not sure if there are others
  }

  capture(entity);
  console.log('[onanyerror]', display, entity);
}

/**
 * Capture stuff for debugging purposes.
 *
 * Keep them in memory so you can reference them
 * in the chrome debugger as `onanyerror0` up to `onanyerror99`.
 */

function capture(entity) {
  captures.push(entity);
  if (captures.length > 100) captures.unshift();

  // keep the last ones around
  var i = captures.length;
  while (--i) {
    var x = captures[i];
    window['onanyerror' + i] = x;
  }
}

/**
 * Wait til next code execution cycle as fast as possible.
 */

function onnext(fn) {
  setTimeout(fn, 0);
}

})();

It could be used like this:

window.onanyerror = function(entity){
  console.log('some error', entity);
};

The full script has a default implementation that tries to print out a semi-readable "display" version of the entity/error that it receives. Can be used for inspiration for an app-specific error handler. The default implementation also keeps a reference to the last 100 error entities, so you can inspect them in the web console after they occur like:

window.onanyerror0
window.onanyerror1
...
window.onanyerror99

Note: This works by overriding methods on several browser/native constructors. This can have unintended side-effects. However, it has been useful to use during development, to figure out where errors are occurring, to send logs to services like NewRelic or Sentry during development so we can measure errors during development, and on staging so we can debug what is going on at a deeper level. It can then be turned off in production.

Hope this helps.

HTTPS connection Python

Python 2.x: docs.python.org/2/library/httplib.html:

Note: HTTPS support is only available if the socket module was compiled with SSL support.

Python 3.x: docs.python.org/3/library/http.client.html:

Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).

#!/usr/bin/env python

import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# => 
# 200 OK
# <!DOCTYPE html ....

To verify if SSL is enabled, try:

>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>

Reverse a comparator in Java 8

You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:

Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
        .thenComparingInt(SomeEntity::getProperty2)
        .thenComparing(SomeEntity::getProperty3, reverseOrder());

ASP.NET 4.5 has not been registered on the Web server

On Windows 8.1, since .NET 4.5 is built-in, the fix is to run this from an administrative command-prompt:

dism.exe /Online /Enable-Feature /all /FeatureName:IIS-ASPNET45

What is the HTML5 equivalent to the align attribute in table cells?

If they're block level elements they won't be affected by text-align: center;. Someone may have set img { display: block; } and that's throwing it out of whack. You can try:

td { text-align: center; }
td * { display: inline; }

and if it looks as desired you should definitely replace * with the desired elements like:

td img, td foo { display: inline; }

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

How to search JSON data in MySQL?

for MySQL all (and 5.7)

SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;

Releasing memory in Python

eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:

Why does it release 50.5mb in particular - what is the amount that is released based on?

What it's based on is, ultimately, a whole series of coincidences inside Python and malloc that are very hard to predict.

First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.

Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE, etc.

If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk or equivalent to shrink the data segment (very rare nowadays), or you've used munmap or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED for a MADV_FREE segment that you immediately unmap.)

But most programs don't directly allocate things out of memory pages; they use a malloc-style allocator. When you call free, the allocator can only release pages to the OS if you just happen to be freeing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.

CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.

So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString object, and the string buffer).

If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)

If you do deallocate a block of object storage, to know whether this causes a free call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloced region, and even then, it may not happen.)

If you do free a malloced region, to know whether this causes an munmap or equivalent (or brk), you have to know the internal state of the malloc, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc within an mmap segment, and even then, it may not happen.)

So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc unmap 50.5mb worth of pages when you did those one or more free calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.

So, the only useful answer to the question is "Because."

Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.

And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).

How to stop event propagation with inline onclick attribute?

I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:

<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>

I know it's late but I wanted to let you know that this works in one line. The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works. :)

How can I check that JButton is pressed? If the isEnable() is not work?

JButton has a model which answers these question:

  • isArmed(),
  • isPressed(),
  • isRollOVer()

etc. Hence you can ask the model for the answer you are seeking:

     if(jButton1.getModel().isPressed())
        System.out.println("the button is pressed");

How do you create a read-only user in PostgreSQL?

Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:

test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;

How do ACID and database transactions work?

ACID properties are very old and important concept of database theory. I know that you can find lots of posts on this topic, but still I would like to start share answer on this because this is very important topic of RDBMS.

Database System plays with lots of different types of transactions where all transaction has certain characteristic. This characteristic is known ACID Properties. ACID Properties take grantee for all database transactions to accomplish all tasks.

Atomicity : Either commit all or nothing.

Consistency : Make consistent record in terms of validate all rule and constraint of transaction.

Isolation : Make sure that two transaction is unaware to each other.

Durability : committed data stored forever. Reference taken from this article:

How to semantically add heading to a list

In this case I would use a definition list as so:

<dl>
  <dt>Fruits I like:</dt>
  <dd>Apples</dd>
  <dd>Bananas</dd>
  <dd>Oranges</dd>
</dl>

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

How do I copy a string to the clipboard?

In addition to Mark Ransom's answer using ctypes: This does not work for (all?) x64 systems since the handles seem to be truncated to int-size. Explicitly defining args and return values helps to overcomes this problem.

import ctypes
import ctypes.wintypes as w

CF_UNICODETEXT = 13

u32 = ctypes.WinDLL('user32')
k32 = ctypes.WinDLL('kernel32')

OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = w.HWND,
OpenClipboard.restype = w.BOOL

GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = w.UINT,
GetClipboardData.restype = w.HANDLE

EmptyClipboard = u32.EmptyClipboard
EmptyClipboard.restype = w.BOOL

SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE,
SetClipboardData.restype = w.HANDLE

CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL

GHND = 0x0042

GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
GlobalAlloc.restype = w.HGLOBAL

GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID

GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL

GlobalSize = k32.GlobalSize
GlobalSize.argtypes = w.HGLOBAL,
GlobalSize.restype = w.ctypes.c_size_t

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GHND, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

#Test run
paste = get
copy = put
copy("Hello World!")
print(paste())

How can I make an EXE file from a Python program?

py2exe:

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.

How to give Jenkins more heap space when it´s started as a service under Windows?

You need to modify the jenkins.xml file. Specifically you need to change

   <arguments>-Xrs -Xmx256m 
    -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
    -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>

to

    <arguments>-Xrs -Xmx2048m -XX:MaxPermSize=512m 
    -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
    -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>

You can also verify the Java options that Jenkins is using by installing the Jenkins monitor plugin via Manage Jenkins / Manage Plugins and then navigating to Managing Jenkins / Monitoring of Hudson / Jenkins master to use monitoring to determine how much memory is available to Jenkins.

If you are getting an out of memory error when Jenkins calls Maven, it may be necessary to set MAVEN_OPTS via Manage Jenkins / Configure System e.g. if you are running on a version of Java prior to JDK 1.8 (the values are suggestions):

-Xmx2048m  -XX:MaxPermSize=512m

If you are using JDK 1.8:

-Xmx2048m

How to change a css class style through Javascript?

Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML

<div id="mydiv" class="oldclass">text</div>

you can comfortably use this syntax:

document.getElementById('mydiv').classList.add("newClass");

This will also result in:

<div id="mydiv" class="oldclass newclass">text</div>

plus you can also use remove, toggle, contains methods.

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

IntelliJ: Never use wildcard imports

The solution above was not working for me. I had to set 'class count to use import with '*'' to a high value, e.g. 999.

Correct way to use StringBuilder in SQL

The aim of using StringBuilder, i.e reducing memory. Is it achieved?

No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)

Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.

Will that take memory equal to using String like below?

No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)

If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):

StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();

Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).

You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:

return "prefix " + variable1 + " middle " + variable2 + " end";

It roughly translates to:

StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();

So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.

But that's only for a single expression. Multiple StringBuilders are used for this:

String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;

That ends up becoming something like this:

String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;

...which is pretty ugly.

It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.

How to run a shell script on a Unix console or Mac terminal?

The file extension .command is assigned to Terminal.app. Double-clicking on any .command file will execute it.

How to generate a random String in Java

I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.

public class RandomNumberGenerator {

private static final Set<String> generatedNumbers = new HashSet<String>();

public RandomNumberGenerator() {
}

public static void main(String[] args) {
    final int maxLength = 7;
    final int maxTry = 10;

    for (int i = 0; i < 10; i++) {
        System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
    }
}

public static String getRandomId(final int maxLength, final int maxTry) {
    final Random random = new Random(System.nanoTime());
    final int max = (int) Math.pow(10, maxLength);
    final int maxMin = (int) Math.pow(10, maxLength-1);
    int i = 0;
    boolean unique = false;
    int randomId = -1;
    while (i < maxTry) {
        randomId = random.nextInt(max - maxMin - 1) + maxMin;

        synchronized (generatedNumbers) {
            if (generatedNumbers.contains(randomId) == false) {
                unique = true;
                break;
            }
        }
        i++;
    }
    if (unique == false) {
        throw new RuntimeException("Cannot generate unique id!");
    }

    synchronized (generatedNumbers) {
        generatedNumbers.add(String.valueOf(randomId));
    }

    return String.valueOf(randomId);
}

}

Putting a simple if-then-else statement on one line

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()

How to escape braces (curly brackets) in a format string in .NET

For you to output foo {1, 2, 3} you have to do something like:

string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);

To output a { you use {{ and to output a } you use }}.

or Now, you can also use c# string interpolation like this (feature available in C# 6.0)

Escaping Brackets: String Interpolation $(""). it is new feature in C# 6.0

var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
//Output will be:  foo {1, 2, 3}

How do I make background-size work in IE?

you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:

.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}

Jquery resizing image

function resize() {resizeFrame(elemento, margin);};

jQuery.event.add(window, "load", resize);
jQuery.event.add(window, "resize", resize);
function resizeFrame(item, marge) {
  $(item).each(function() {
  var m = marge*2;
  var mw = $(window).width()-m; 
  var mh = $(window).height()-m;
  var w = $('img',this).width();
  var h = $('img',this).height();
  var mr = mh/mw;
  var cr = h/w;
  $('img',this).css({position:'absolute',minWidth:(w-w)+20,minHeight:(h-h)+20,margin:'auto',top:'0',right:'0',bottom:'0',left:'0',padding:marge});
    if(cr < mr){
        var r = mw/w;
        $('img',this).css({width: mw});
        $('img',this).css({height: h*r});
    }else if(cr > mr){
        var r = mh/h;
        $('img',this).css({height: mh});
        $('img',this).css({width: w*r});
    }
  });  
}

Location of my.cnf file on macOS

For MAMP 3.5 Mac El Capitan, create a separate empty config file and write your additional settings for mysql

sudo vim /Applications/MAMP/Library/my.cnf

And Add like this

[mysqld]
max_allowed_packet = 256M

How to install OpenSSL in windows 10?

I recently needed to document how to get a version of it installed, so I've copied my steps here, as the other answers were using different sources from what I recommend, which is Cygwin. I like Cygwin because it is well maintained and provides a wealth of other utilities for Windows. Cygwin also allows you to easily update the versions as needed when vulnerabilities are fixed. Please update your version of OpenSSL often!

Open a Windows Command prompt and check to see if you have OpenSSL installed by entering: openssl version

If you get an error message that the command is NOT recognized, then install OpenSSL by referring to Cygwin following the summary steps below:

Basically, download and run the Cygwin Windows Setup App to install and to update as needed the OpenSSL application:

  1. Select an install directory, such as C:\cygwin64. Choose a download mirror such as: http://mirror.cs.vt.edu
  2. Enter in openssl into the search and select it. You can also select/un-select other items of interest at this time. The click Next twice then click Finish.
  3. After installing, you need to edit the PATH variable. On Windows, you can access the System Control Center by pressing Windows Key + Pause. In the System window, click Advanced System Settings ? Advanced (tab) ? Environment Variables. For Windows 10, a quick access is to enter "Edit the system environment variables" in the Start Search of Windows and click the button "Environment Variables". Change the PATH variable (double-click on it or Select and Edit), and add the path where your Cywgwin is, e.g. C:\cygwin\bin.
  4. Verify you have it installed via a new Command Prompt window: openssl version. For example: C:\Program Files\mosquitto>openssl versionOpenSSL 1.1.1f 31 Mar 2020

How to use OUTPUT parameter in Stored Procedure

You need to close the connection before you can use the output parameters. Something like this

con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());

How do you import a large MS SQL .sql file?

The file basically contain data for two new tables.

Then you may find it simpler to just DTS (or SSIS, if this is SQL Server 2005+) the data over, if the two servers are on the same network.

If the two servers are not on the same network, you can backup the source database and restore it to a new database on the destination server. Then you can use DTS/SSIS, or even a simple INSERT INTO SELECT, to transfer the two tables to the destination database.

How do I convert a factor into date format?

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

How to redirect to another page using PHP

_x000D_
_x000D_
----------_x000D_
_x000D_
_x000D_
<?php_x000D_
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>'; _x000D_
  $gourl='http://stackoverflow.com';_x000D_
  echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';    _x000D_
  exit;_x000D_
_x000D_
?>_x000D_
_x000D_
_x000D_
----------
_x000D_
_x000D_
_x000D_

How to update record using Entity Framework Core?

public async Task<bool> Update(MyObject item)
{
    Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
    return (await Context.SaveChangesAsync()) > 0;
}

Fitting a Normal distribution to 1D data

To see both the normal distribution and your actual data you should plot your data as a histogram, then draw the probability density function over this. See the example on https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.normal.html for exactly how to do this.

MySQL SELECT query string matching

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

Quickest way to convert XML to JSON in Java

The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.

Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.

Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).

How to update attributes without validation

USE update_attribute instead of update_attributes

Updates a single attribute and saves the record without going through the normal validation procedure.

if a.update_attribute('state', a.state)

Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

I also read the answers and comments and tried some solutions from this thread.

Then a Googled a little more and this worked for me

https://www.c-sharpcorner.com/blogs/iis-express-failed-to-register-url-access-is-denied

Didn't comment on no one's answer because I didn't read whats written here, so it needed a new answer post. There's answers here that talk about netsh wlan stuff, but I didn't see exactly this solution. If some one wrote the exact same solution please tell me so I can comment there and remove this.

resize2fs: Bad magic number in super-block while trying to open

How to resize root partition online :  

1)  [root@oel7 ~]# df -h  
Filesystem                         Size  Used Avail Use% Mounted on  
/dev/mapper/root_vg-root           5.0G  4.5G  548M  90% /

2)   

PV /dev/sda2   VG root_vg     lvm2 [6.00 GiB / 0    free]

as here it shows that there is no space left on root_vg volume group, so first i need to extend VG 

3)  
[root@oel7 ~]# vgextend root_vg /dev/sdb5  

  Volume group "root_vg" successfully extended

4)  

[root@oel7 ~]# pvscan  
    PV /dev/sda2   VG root_vg     lvm2 [6.00 GiB / 0    free]  
    PV /dev/sdb5   VG root_vg     lvm2 [2.00 GiB / 2.00 GiB free]

5)  Now extend the logical volume   

[root@oel7 ~]# lvextend -L +1G /dev/root_vg/root  

  Size of logical volume root_vg/root changed from 5.00 GiB (1280 extents) to 6.00 GiB (1536 extents).
  Logical volume root successfully resized  

3)  [root@oel7 ~]# resize2fs /dev/root_vg/root  

resize2fs 1.42.9 (28-Dec-2013)  
resize2fs: Bad magic number in super-block while trying to open /dev/root_vg  /root  
Couldn't find valid filesystem superblock.  

as root partition is not a ext* partiton so , you resize2fs will not work for you.  

4)  to check the filesystem type of a partition 
[root@oel7 ~]# df -Th  
Filesystem                        Type      Size  Used Avail Use% Mounted on  
/dev/mapper/root_vg-root          xfs       6.0G  4.5G  1.6G  75% /  
devtmpfs                          devtmpfs  481M     0  481M   0% /dev  
tmpfs                             tmpfs     491M   80K  491M   1% /dev/shm  
tmpfs                             tmpfs     491M  7.1M  484M   2% /run  
tmpfs                             tmpfs     491M     0  491M   0% /sys/fs  /cgroup
/dev/mapper/data_vg-home          xfs       3.5G  2.9G  620M  83% /home  
/dev/sda1                         xfs       497M  132M  365M  27% /boot  
/dev/mapper/data_vg01-data_lv001  ext3      4.0G  2.4G  1.5G  62% /sybase  
/dev/mapper/data_vg02-backup_lv01 ext3      4.0G  806M  3.0G  22% /backup  

above command shows that root is an xfs filesystem , so we are sure that we need to use xfs_growfs command to resize the partition.

6)  [root@oel7 ~]# xfs_growfs /dev/root_vg/root  
meta-data=/dev/mapper/root_vg-root isize=256    agcount=4, agsize=327680 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=0        finobt=0
data     =                       bsize=4096   blocks=1310720, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=0
log      =internal               bsize=4096   blocks=2560, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 1310720 to 1572864  

[root@oel7 ~]# df -Th  

Filesystem                        Type      Size  Used Avail Use% Mounted on
/dev/mapper/root_vg-root          xfs       6.0G  4.5G  1.6G  75% /