Programs & Examples On #Android capture

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

PHP how to get local IP of system

$_SERVER['SERVER_NAME']

It worked for me.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I have got the solution for my query:

i have done something like this:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

This way it's working in all browsers.

Entity Framework - Code First - Can't Store List<String>

This answer is based on the ones provided by @Sasan and @CAD bloke.

If you wish to use this in .NET Standard 2 or don't want Newtonsoft, see Xaniff's answer below

Works only with EF Core 2.1+ (not .NET Standard compatible)(Newtonsoft JsonConvert)

builder.Entity<YourEntity>().Property(p => p.Strings)
    .HasConversion(
        v => JsonConvert.SerializeObject(v),
        v => JsonConvert.DeserializeObject<List<string>>(v));

Using the EF Core fluent configuration we serialize/deserialize the List to/from JSON.

Why this code is the perfect mix of everything you could strive for:

  • The problem with Sasn's original answer is that it will turn into a big mess if the strings in the list contains commas (or any character chosen as the delimiter) because it will turn a single entry into multiple entries but it is the easiest to read and most concise.
  • The problem with CAD bloke's answer is that it is ugly and requires the model to be altered which is a bad design practice (see Marcell Toth's comment on Sasan's answer). But it is the only answer that is data-safe.

Visual Studio Code: Auto-refresh file changes

SUPER-SHIFT-p > File: Revert File is the only way

(where SUPER is Command on Mac and Ctrl on PC)

How to write to an existing excel file without overwriting data (using pandas)?

With openpyxlversion 2.4.0 and pandasversion 0.19.2, the process @ski came up with gets a bit simpler:

import pandas
from openpyxl import load_workbook

with pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') as writer:
    writer.book = load_workbook('Masterfile.xlsx')
    data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])
#That's it!

Search text in fields in every table of a MySQL database

i got this to work. you just need to change the variables

$query ="SELECT `column_name` FROM `information_schema`.`columns` WHERE `table_schema`='" . $_SESSION['db'] . "' AND `table_name`='" . $table . "' ";
$stmt = $dbh->prepare($query);
$stmt->execute(); 
$columns = $stmt->fetchAll(PDO::FETCH_ASSOC);       

$query="SELECT name FROM `" . $database . "`.`" . $table . "` WHERE ( ";
foreach ( $columns as $column ) {
    $query .=" CONVERT( `" . $column['column_name'] . "` USING utf8 ) LIKE '%" . $search . "%' OR ";
}
$query = substr($query, 0, -3);
$query .= ")";

echo $query . "<br>";
$stmt=$dbh->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r ($results );
echo "</pre>";

remove inner shadow of text input

None of the solution are working currently. Here is my solution. You can add prefixes.

box-shadow: inset 0px 0px 0px 0px red;

Importing json file in TypeScript

Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:

const config = require('./config.json');

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

PHP - Merging two arrays into one array (also Remove Duplicates)

try to use the array_unique()

this elminates duplicated data inside the list of your arrays..

Int to Char in C#

int i = 65;
char c = Convert.ToChar(i);

How do I mock an autowired @Value field in Spring with Mockito?

I used the below code and it worked for me:

@InjectMocks
private ClassABC classABC;

@Before
public void setUp() {
    ReflectionTestUtils.setField(classABC, "constantFromConfigFile", 3);
}

Reference: https://www.jeejava.com/mock-an-autowired-value-field-in-spring-with-junit-mockito/

Accessing localhost of PC from USB connected Android mobile device

Here is a piece of my Android app's code:

This app is able to communicate with a HTTP get-post model between a servlet running on a server and an Android device plugged in USB-Debuggable mode (because the app was in developing progress).

I also can run the app over Wi-Fi when the server, Tomcat Apache 7, running on (when the app development was finished).

enter image description here

To get the IP address of yours

  1. Go to Command Prompt
  2. Type ipconfig
  3. Hit enter

In the list, IPv4 Address is your IP.

Where to put Gradle configuration (i.e. credentials) that should not be committed?

For those of you who are building on a MacOS, and don't like leaving your password in clear text on your machine, you can use the keychain tool to store the credentials and then inject it into the build. Credits go to Viktor Eriksson. https://pilloxa.gitlab.io/posts/safer-passwords-in-gradle/

php - insert a variable in an echo string

Single quotes will not parse PHP variables inside of them. Either use double quotes or use a dot to extend the echo.

$variableName = 'Ralph';
echo 'Hello '.$variableName.'!';

OR

echo "Hello $variableName!";

And in your case:

$i = 1;
echo '<p class="paragraph'.$i.'"></p>';
++i;

OR

$i = 1;
echo "<p class='paragraph$i'></p>";
++i;

How do I get a list of all the duplicate items using pandas in python?

df[df.duplicated(['ID'], keep=False)]

it'll return all duplicated rows back to you.

According to documentation:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Mark duplicates as True except for the first occurrence.
  • last : Mark duplicates as True except for the last occurrence.
  • False : Mark all duplicates as True.

Difference between [routerLink] and routerLink

ROUTER LINK DIRECTIVE:

[routerLink]="link"                  //when u pass URL value from COMPONENT file
[routerLink]="['link','parameter']" //when you want to pass some parameters along with route

 routerLink="link"                  //when you directly pass some URL 
[routerLink]="['link']"              //when you directly pass some URL

What is the difference between "INNER JOIN" and "OUTER JOIN"?

The precise algorithm for INNER JOIN, LEFT/RIGHT OUTER JOIN are as following:

  1. Take each row from the first table: a
  2. Consider all rows from second table beside it: (a, b[i])
  3. Evaluate the ON ... clause against each pair: ON( a, b[i] ) = true/false?
    • When the condition evaluates to true, return that combined row (a, b[i]).
    • When reach end of second table without any match, and this is an Outer Join then return a (virtual) pair using Null for all columns of other table: (a, Null) for LEFT outer join or (Null, b) for RIGHT outer join. This is to ensure all rows of first table exists in final results.

Note: the condition specified in ON clause could be anything, it is not required to use Primary Keys (and you don't need to always refer to Columns from both tables)! For example:

Inner Join vs. Left Outer Join


enter image description here

Note: Left Join = Left Outer Join, Right Join = Right Outer Join.

Make body have 100% of the browser height

What I use on the start of literally every CSS file I use is the following:

html, body{
    margin: 0;

    padding: 0;

    min-width: 100%;
    width: 100%;
    max-width: 100%;

    min-height: 100%;
    height: 100%;
    max-height: 100%;
}

The margin of 0 ensures that the HTML and BODY elements aren't being auto-positioned by the browser to have some space to the left or right of them.

The padding of 0 ensures that the HTML and BODY elements aren't automatically pushing everything inside them down or right because of browser defaults.

The width and height variants are set to 100% to ensure that the browser doesn't resize them in anticipation of actually having an auto-set margin or padding, with min and max set just in case some weird, unexplainable stuff happens, though you probably dont need them.

This solution also means that, like I did when I first started on HTML and CSS several years ago, you won't have to give your first <div> a margin:-8px; to make it fit in the corner of the browser window.


Before I posted, I looked at my other fullscreen CSS project and found that all I used there was just body{margin:0;} and nothing else, which has worked fine over the 2 years I've been working on it.

Hope this detailed answer helps, and I feel your pain. In my eyes, it is dumb that browsers should set an invisible boundary on the left and sometimes top side of the body/html elements.

MongoDB query multiple collections at once

Here is answer for your question.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$project : {
            posts : { $filter : {input : "$posts"  , as : "post", cond : { $eq : ['$$post.via' , 'facebook'] } } },
            admin : 1

        }}

])

Or either you can go with mongodb group option.

db.getCollection('users').aggregate([
    {$match : {admin : 1}},
    {$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
    {$unwind : "$posts"},
    {$match : {"posts.via":"facebook"}},
    { $group : {
            _id : "$_id",
            posts : {$push : "$posts"}
    }}
])

What is meant with "const" at end of function declaration?

Similar to this question.

In essence it means that the method Bar will not modify non mutable member variables of Foo.

printf %f with only 2 numbers after the decimal point?

Use this:

printf ("%.2f", 3.14159);

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

How to get pandas.DataFrame columns containing specific dtype

dtypes is a Pandas Series. That means it contains index & values attributes. If you only need the column names:

headers = df.dtypes.index

it will return a list containing the column names of "df" dataframe.

SQLAlchemy IN clause

Assuming you use the declarative style (i.e. ORM classes), it is pretty easy:

query = db_session.query(User.id, User.name).filter(User.id.in_([123,456]))
results = query.all()

db_session is your database session here, while User is the ORM class with __tablename__ equal to "users".

Convert Pandas column containing NaNs to dtype `int`

Assuming your DateColumn formatted 3312018.0 should be converted to 03/31/2018 as a string. And, some records are missing or 0.

df['DateColumn'] = df['DateColumn'].astype(int)
df['DateColumn'] = df['DateColumn'].astype(str)
df['DateColumn'] = df['DateColumn'].apply(lambda x: x.zfill(8))
df.loc[df['DateColumn'] == '00000000','DateColumn'] = '01011980'
df['DateColumn'] = pd.to_datetime(df['DateColumn'], format="%m%d%Y")
df['DateColumn'] = df['DateColumn'].apply(lambda x: x.strftime('%m/%d/%Y'))

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

The $.browser method has been removed as of jQuery 1.9.

jQuery.browser() removed

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

jQuery Core 1.9 Upgrade Guide.

As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work.

Why I've got no crontab entry on OS X when using vim?

In user crontab (crontab -e) do not put the user field.

Correct cron is:

0-59 * * * * echo "Hello World"

Syntax with user field is for /etc/crontab only:

0-59 * * * * mollerhoj3 echo "Hello World"

Laravel Advanced Wheres how to pass variable into function?

@kajetons' answer is fully functional.

You can also pass multiple variables by passing them like: use($var1, $var2)

DB::table('users')->where(function ($query) use ($activated,$var2) {
    $query->where('activated', '=', $activated);
    $query->where('var2', '>', $var2);
})->get();

Vuejs and Vue.set(), update array

EDIT 2

  • For all object changes that need reactivity use Vue.set(object, prop, value)
  • For array mutations, you can look at the currently supported list here

EDIT 1

For vuex you will want to do Vue.set(state.object, key, value)


Original

So just for others who come to this question. It appears at some point in Vue 2.* they removed this.items.$set(index, val) in favor of this.$set(this.items, index, val).

Splice is still available and here is a link to array mutation methods available in vue link.

How to count duplicate value in an array in javascript

You can do something like that:

uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = new Object();

for(var i = 0; i < uniqueCount.length; i++) {
 if(map[uniqueCount[i]] != null) {
    map[uniqueCount[i]] += 1;
} else {
    map[uniqueCount[i]] = 1;
    }
}

now you have a map with all characters count

SQL: How to get the id of values I just INSERTed?

Simplest answer:

command.ExecuteScalar()

by default returns the first column

Return Value Type: System.Object The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.

Copied from MSDN

Log exception with traceback

This is how I do it.

try:
    do_something()
except:
    # How can I log my exception here, complete with its traceback?
    import traceback
    traceback.format_exc() # this will print a complete trace to stout.

How do I specify different layouts for portrait and landscape orientations?

You just have to put it under separate folders with different names depending on orientation and resolution, the device will automatically select the right one for its screen settings

More info here:

http://developer.android.com/guide/practices/screens_support.html

under "Resource directory qualifiers for screen size and density"

Different color for each bar in a bar chart; ChartJS

try this :

  function getChartJs() {
        **var dynamicColors = function () {
            var r = Math.floor(Math.random() * 255);
            var g = Math.floor(Math.random() * 255);
            var b = Math.floor(Math.random() * 255);
            return "rgb(" + r + "," + g + "," + b + ")";
        }**

        $.ajax({
            type: "POST",
            url: "ADMIN_DEFAULT.aspx/GetChartByJenisKerusakan",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var labels = r.d[0];
                var series1 = r.d[1];
                var data = {
                    labels: r.d[0],
                    datasets: [
                        {
                            label: "My First dataset",
                            data: series1,
                            strokeColor: "#77a8a8",
                            pointColor: "#eca1a6"
                        }
                    ]
                };

                var ctx = $("#bar_chart").get(0).getContext('2d');
                ctx.canvas.height = 300;
                ctx.canvas.width = 500;
                var lineChart = new Chart(ctx).Bar(data, {
                    bezierCurve: false,
                    title:
                      {
                          display: true,
                          text: "ProductWise Sales Count"
                      },
                    responsive: true,
                    maintainAspectRatio: true
                });

                $.each(r.d, function (key, value) {
                    **lineChart.datasets[0].bars[key].fillColor = dynamicColors();
                    lineChart.datasets[0].bars[key].fillColor = dynamicColors();**
                    lineChart.update();
                });
            },
            failure: function (r) {
                alert(r.d);
            },
            error: function (r) {
                alert(r.d);
            }
        });
    }

Nullable type as a generic parameter possible?

Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.

However, you can use the generic constraints to make sure that the methods are used correctly.

In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.

I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.

    public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
        where TSource: class
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a class is null
        return result;
    }

    public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
        where TSource : struct
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a nullable is null
        return result;
    }

How to write "not in ()" sql query using join

This article:

may be if interest to you.

In a couple of words, this query:

SELECT  d1.short_code
FROM    domain1 d1
LEFT JOIN
        domain2 d2
ON      d2.short_code = d1.short_code
WHERE   d2.short_code IS NULL

will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

You can also use this:

SELECT  short_code
FROM    domain1
EXCEPT
SELECT  short_code
FROM    domain2

This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

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

Add this code into your StyleSheet:

margin-top:80px;

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Python interpreter error, x takes no arguments (1 given)

Make sure, that all of your class methods (updateVelocity, updatePosition, ...) take at least one positional argument, which is canonically named self and refers to the current instance of the class.

When you call particle.updateVelocity(), the called method implicitly gets an argument: the instance, here particle as first parameter.

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

Reading Excel files from C#

You can try using this open source solution that makes dealing with Excel a lot more cleaner.

http://excelwrapperdotnet.codeplex.com/

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

Make first letter of a string upper case (with maximum performance)

The right way is to use Culture:

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())

Note: This will capitalise each word within a string, e.g. "red house" --> "Red House". The solution will also lower-case capitalisation within words, e.g. "old McDonald" --> "Old Mcdonald".

Object of class stdClass could not be converted to string

try this

return $query->result_array();

Should URL be case sensitive?

URLs should be case insensitive unless there is a good reason why they are should not be.

This is not mandatory (it is not any part of an RFC) but it makes the communication and storage of URLs far more reliable.

If I have two pages on a website:

http://stackoverflow.com/ABOUT.html

and

http://stackoverflow.com/about.html

How should they differ? Maybe one is written 'shouting style' (caps) - but from an IA point of view, the distinction should never be made by a change in the case of the URL.

Moreover, it is easy to implement this in Apache - just use CheckSpelling On from mod_Speling.

Refused to apply inline style because it violates the following Content Security Policy directive

As per http://content-security-policy.com/ The best place to start:

    default-src 'none'; 
    script-src 'self'; 
    connect-src 'self'; 
    img-src 'self'; 
    style-src 'self';
    font-src 'self';

Never inline styles or scripts as it undermines the purpose of CSP. You can use a stylesheet to set a style property and then use a function in a .js file to change the style property (if need be).

add title attribute from css

On the one hand, the title is helpful as a tooltip when moving the mouse over the element. This could be solved with CSS-> element::after. But it is much more important as an aid for visually impaired people (topic handicap-free website). And for this it MUST be included as an attribute in the HTML element. Everything else is junk, botch, idiot stuff ...!

How can I fill a div with an image while keeping it proportional?

This should do it:

img {    
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
}

How to use custom font in a project written in Android Studio

  1. Create folder assets in Project -> app (or your app name) -> src -> main -> right click -> New -> Directory.
  2. Then create a new directory inside assets called "fonts".

To assign the font to the textView:

TextView textView = (TextView) findViewById(R.id.your_textView);

final Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/your_font_name");

your_font_name includes font extension.

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2

This seems to me slightly shorter than the solution presented above

Using DISTINCT inner join in SQL

I believe your 1:m relationships should already implicitly create DISTINCT JOINs.

But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.

SELECT DISTINCT a.valueA, c.valueC
FROM C
    INNER JOIN B ON B.lookupC = C.id
    INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC

In Postgresql, force unique on combination of two columns

Seems like regular UNIQUE CONSTRAINT :)

CREATE TABLE example (
a integer,
b integer,
c integer,
UNIQUE (a, c));

More here

Reflection: How to Invoke Method with parameters

A fundamental mistake is here:

result = methodInfo.Invoke(methodInfo, parametersArray); 

You are invoking the method on an instance of MethodInfo. You need to pass in an instance of the type of object that you want to invoke on.

result = methodInfo.Invoke(classInstance, parametersArray);

How to calculate the SVG Path for an arc (of a circle)

ES6 version:

const angleInRadians = angleInDegrees => (angleInDegrees - 90) * (Math.PI / 180.0);

const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
    const a = angleInRadians(angleInDegrees);
    return {
        x: centerX + (radius * Math.cos(a)),
        y: centerY + (radius * Math.sin(a)),
    };
};

const arc = (x, y, radius, startAngle, endAngle) => {
    const fullCircle = endAngle - startAngle === 360;
    const start = polarToCartesian(x, y, radius, endAngle - 0.01);
    const end = polarToCartesian(x, y, radius, startAngle);
    const arcSweep = endAngle - startAngle <= 180 ? '0' : '1';

    const d = [
        'M', start.x, start.y,
        'A', radius, radius, 0, arcSweep, 0, end.x, end.y,
    ].join(' ');

    if (fullCircle) d.push('z');
    return d;
};

Find object by id in an array of JavaScript objects

More generic and short

function findFromArray(array,key,value) {
        return array.filter(function (element) {
            return element[key] == value;
        }).shift();
}

in your case Ex. var element = findFromArray(myArray,'id',45) that will give you the whole element.

Batch program to to check if process exists

TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
  specific commands to perform if the process was not found
)
exit

There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
  specific commands to perform if the process
  was not terminated because it was not found
)
exit

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

Python subprocess/Popen with a modified environment

With Python 3.5 you could do it this way:

import os
import subprocess

my_env = {**os.environ, 'PATH': '/usr/sbin:/sbin:' + os.environ['PATH']}

subprocess.Popen(my_command, env=my_env)

Here we end up with a copy of os.environ and overridden PATH value.

It was made possible by PEP 448 (Additional Unpacking Generalizations).

Another example. If you have a default environment (i.e. os.environ), and a dict you want to override defaults with, you can express it like this:

my_env = {**os.environ, **dict_with_env_variables}

ExecJS and could not find a JavaScript runtime

Ubuntu Users

I'm on Ubuntu 11.04 and had similar issues. Installing Node.js fixed it.

As of Ubuntu 13.04 x64 you only need to run:

sudo apt-get install nodejs

This will solve the problem.


CentOS/RedHat Users

sudo yum install nodejs

What is the difference between Serializable and Externalizable in Java?

There are so many difference exist between Serializable and Externalizable but when we compare difference between custom Serializable(overrided writeObject() & readObject()) and Externalizable then we find that custom implementation is tightly bind with ObjectOutputStream class where as in Externalizable case , we ourself provide an implementation of ObjectOutput which may be ObjectOutputStream class or it could be some other like org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream

In case of Externalizable interface

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(key);
    out.writeUTF(value);
    out.writeObject(emp);
}

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.key = in.readUTF();
    this.value = in.readUTF();
    this.emp = (Employee) in.readObject();
}





**In case of Serializable interface**


        /* 
             We can comment below two method and use default serialization process as well
             Sequence of class attributes in read and write methods MUST BE same.
        // below will not work it will not work . 
        // Exception = java.io.StreamCorruptedException: invalid type code: 00\
              private void writeObject(java.io.ObjectOutput stream) 
              */
            private void writeObject(java.io.ObjectOutputStream Outstream)
                    throws IOException {

                System.out.println("from writeObject()");
                /*     We can define custom validation or business rules inside read/write methods.
 This way our validation methods will be automatically 
    called by JVM, immediately after default serialization 
    and deserialization process 
    happens.
                 checkTestInfo();
                */

                stream.writeUTF(name);
                stream.writeInt(age);
                stream.writeObject(salary);
                stream.writeObject(address);
            }

            private void readObject(java.io.ObjectInputStream Instream)
                    throws IOException, ClassNotFoundException {
                System.out.println("from readObject()");
                name = (String) stream.readUTF();
                age = stream.readInt();
                salary = (BigDecimal) stream.readObject();
                address = (Address) stream.readObject();
                // validateTestInfo();
            }

I have added sample code to explain better. please check in/out object case of Externalizable. These are not bound to any implementation directly.
Where as Outstream/Instream are tightly bind to classes. We can extends ObjectOutputStream/ObjectInputStream but it will a bit difficult to use.

Windows CMD command for accessing usb?

Try this batch :

@echo off
Title List of connected external devices by Hackoo
Mode con cols=100 lines=20 & Color 9E
wmic LOGICALDISK where driveType=2 get deviceID > wmic.txt
for /f "skip=1" %%b IN ('type wmic.txt') DO (echo %%b & pause & Dir %%b)
Del wmic.txt
pause

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get < span > value?

<div id="test">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
</div>
<div id="test2"></div>

<script type="text/javascript">
    var getDiv = document.getElementById('test');
    var getSpan = getDiv.getElementsByTagName('span');???
    var divDump = document.getElementById('test2');

    for (var i=0; i<getSpan.length; i++) {
        divDump.innerHTML = divDump.innerHTML + ' ' + getSpan[i].innerHTML;
    }
</script>

?

Is it possible to have multiple styles inside a TextView?

In case, anyone is wondering how to do this, here's one way: (Thanks to Mark again!)

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
            "<small>" + description + "</small>" + "<br />" + 
            "<small>" + DateAdded + "</small>"));

For an unofficial list of tags supported by this method, refer to this link or this question: Which HTML tags are supported by Android TextView?

Base64 encoding in SQL Server 2005 T-SQL

Here's a modification to mercurial's answer that uses the subquery on the decode as well, allowing the use of variables in both instances.

DECLARE
    @EncodeIn VARCHAR(100) = 'Test String In',
    @EncodeOut VARCHAR(500),
    @DecodeOut VARCHAR(200)    

SELECT @EncodeOut = 
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )
FROM (
    SELECT CAST(@EncodeIn AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;

PRINT @EncodeOut

SELECT @DecodeOut = 
CAST(
    CAST(N'' AS XML).value(
        'xs:base64Binary(sql:column("bin"))'
      , 'VARBINARY(MAX)'
    ) 
    AS VARCHAR(MAX)
) 
FROM (
    SELECT CAST(@EncodeOut AS VARCHAR(MAX)) AS bin
) AS bin_sql_server_temp;

PRINT @DecodeOut

How do I pass parameters to a jar file at the time of execution?

To pass arguments to the jar:

java -jar myjar.jar one two

You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf file of a JAR).

String one = args[0];  
String two = args[1];  

How to write multiple line string using Bash with variables?

The heredoc solutions are certainly the most common way to do this. Other common solutions are:

echo 'line 1, '"${kernel}"'
line 2,
line 3, '"${distro}"'
line 4' > /etc/myconfig.conf

and

exec 3>&1 # Save current stdout
exec > /etc/myconfig.conf
echo line 1, ${kernel}
echo line 2, 
echo line 3, ${distro}
...
exec 1>&3  # Restore stdout

How to save RecyclerView's scroll position using RecyclerView.State?

I've had the same requirement, but the solutions here didn't quite get me across the line, due to the source of data for the recyclerView.

I was extracting the RecyclerViews' LinearLayoutManager state in onPause()

private Parcelable state;

Public void onPause() {
    state = mLinearLayoutManager.onSaveInstanceState();
}

Parcelable state is saved in onSaveInstanceState(Bundle outState), and extracted again in onCreate(Bundle savedInstanceState), when savedInstanceState != null.

However, the recyclerView adapter is populated and updated by a ViewModel LiveData object returned by a DAO call to a Room database.

mViewModel.getAllDataToDisplay(mSelectedData).observe(this, new Observer<List<String>>() {
    @Override
    public void onChanged(@Nullable final List<String> displayStrings) {
        mAdapter.swapData(displayStrings);
        mLinearLayoutManager.onRestoreInstanceState(state);
    }
});

I eventually found that restoring the instance state directly after the data is set in the adapter would keep the scroll-state across rotations.

I suspect this either is because the LinearLayoutManager state that I'd restored was being overwritten when the data was returned by the database call, or the restored state was meaningless against an 'empty' LinearLayoutManager.

If the adapter data is available directly (ie not contigent on a database call), then restoring the instance state on the LinearLayoutManager can be done after the adapter is set on the recyclerView.

The distinction between the two scenarios held me up for ages.

How do I find a particular value in an array and return its index?

Here is a very simple way to do it by hand. You could also use the <algorithm>, as Peter suggests.

#include <iostream>
int find(int arr[], int len, int seek)
{
    for (int i = 0; i < len; ++i)
    {
        if (arr[i] == seek) return i;
    }
    return -1;
}
int main()
{
    int arr[ 5 ] = { 4, 1, 3, 2, 6 };
    int x = find(arr,5,3);
    std::cout << x << std::endl;    
}

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Looks like the installed driver was in bad state. Here is what I did to make it work:

  1. Delete the device from Device Manager.
  2. Rescan for hardware changes.
  3. "Slate 21" will show up with "Unknown driver" status.
  4. Click on "Update Driver" and select /extras/google/usb_driver
  5. Device Manager will find the driver and warn you about installing it. Select "Yes."

This time the device got installed properly.

Note that I didn't have to modify winusb.inf file or update any other driver.

Hope this helps.

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

SQL to generate a list of numbers from 1 to 100

Using Oracle's sub query factory clause: "WITH", you can select numbers from 1 to 100:

WITH t(n) AS (
  SELECT 1 from dual
  UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT * FROM t;

In Java, can you modify a List while iterating through it?

There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

Java - Convert integer to string

The way I know how to convert an integer into a string is by using the following code:

Integer.toString(int);

and

String.valueOf(int);

If you had an integer i, and a string s, then the following would apply:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

If you wanted to convert a string "s" into an integer "i", then the following would work:

i = Integer.valueOf(s).intValue();

Best way to concatenate List of String objects?

Using the Functional Java library, import these:

import static fj.pre.Monoid.stringMonoid;
import static fj.data.List.list;
import fj.data.List;

... then you can do this:

List<String> ss = list("foo", "bar", "baz");
String s = stringMonoid.join(ss, ", ");

Or, the generic way, if you don't have a list of Strings:

public static <A> String showList(List<A> l, Show<A> s) {
  return stringMonoid.join(l.map(s.showS_()), ", ");
}

How do I check if an element is really visible with JavaScript?

I don't know how much of this is supported in older or not-so-modern browsers, but I'm using something like this (without the neeed for any libraries):

function visible(element) {
  if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;
  var height = document.documentElement.clientHeight,
      rects = element.getClientRects(),
      on_top = function(r) {
        var x = (r.left + r.right)/2, y = (r.top + r.bottom)/2;
        return document.elementFromPoint(x, y) === element;
      };
  for (var i = 0, l = rects.length; i < l; i++) {
    var r = rects[i],
        in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
    if (in_viewport && on_top(r)) return true;
  }
  return false;
}

It checks that the element has an area > 0 and then it checks if any part of the element is within the viewport and that it is not hidden "under" another element (actually I only check on a single point in the center of the element, so it's not 100% assured -- but you could just modify the script to itterate over all the points of the element, if you really need to...).

Update

Modified on_top function that check every pixel:

on_top = function(r) {
  for (var x = Math.floor(r.left), x_max = Math.ceil(r.right); x <= x_max; x++)
  for (var y = Math.floor(r.top), y_max = Math.ceil(r.bottom); y <= y_max; y++) {
    if (document.elementFromPoint(x, y) === element) return true;
  }
  return false;
};

Don't know about the performance :)

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

Space between Column's children in Flutter

You can also use a helper function to add spacing after each child.

List<Widget> childrenWithSpacing({
  @required List<Widget> children,
  double spacing = 8,
}) {
  final space = Container(width: spacing, height: spacing);
  return children.expand((widget) => [widget, space]).toList();
}

So then, the returned list may be used as a children of a column

Column(
  children: childrenWithSpacing(
    spacing: 14,
    children: [
      Text('This becomes a text with an adjacent spacing'),
      if (true == true) Text('Also, makes it easy to add conditional widgets'),
    ],
  ),
);

I'm not sure though if it's wrong or have a performance penalty to run the children through a helper function for the same goal?

How to prevent errno 32 broken pipe?

It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.

For example, if your sendall always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).


In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.

Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

Problem 2 is OK, because " System.out.println(set);" means "System.out.println(set.toString());" set is an instance of List, so complier will call List.toString();

public static void test(List<?> set){
set.add(new Long(2)); //--> Error  
set.add("2");    //--> Error
System.out.println(set);
} 
Element ? will not promise Long and String, so complier will  not accept Long and String Object

public static void test(List<String> set){
set.add(new Long(2)); //--> Error
set.add("2");    //--> Work
System.out.println(set);
}
Element String promise it a String, so complier will accept String Object

Problem 3: these symbols are same, but you can give them differet specification. For example:

public <T extends Integer,E extends String> void p(T t, E e) {}

Problem 4: Collection does not allow type parameter covariance. But array does allow covariance.

Find records with a date field in the last 24 hours

There are so many ways to do this. The listed ones work great, but here's another way if you have a datetime field:

SELECT [fields] 
FROM [table] 
WHERE timediff(now(), my_datetime_field) < '24:00:00'

timediff() returns a time object, so don't make the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

Java: how to add image to Jlabel?

You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor:

Image image=GenerateImage.toImage(true);  //this generates an image file
ImageIcon icon = new ImageIcon(image); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information.

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

How to output a multiline string in Bash?

Inspired by the insightful answers on this page, I created a mixed approach, which I consider the simplest and more flexible one. What do you think?

First, I define the usage in a variable, which allows me to reuse it in different contexts. The format is very simple, almost WYSIWYG, without the need to add any control characters. This seems reasonably portable to me (I ran it on MacOS and Ubuntu)

__usage="
Usage: $(basename $0) [OPTIONS]

Options:
  -l, --level <n>              Something something something level
  -n, --nnnnn <levels>         Something something something n
  -h, --help                   Something something something help
  -v, --version                Something something something version
"

Then I can simply use it as

echo "$__usage"

or even better, when parsing parameters, I can just echo it there in a one-liner:

levelN=${2:?"--level: n is required!""${__usage}"}

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

I had the same error message, my mistake was that I had a semicolon at the end of COMMIT TRANSACTION line

Remove all occurrences of a value from a list?

p=[2,3,4,4,4]
p.clear()
print(p)
[]

Only with Python 3

What is the best way to check for Internet connectivity using .NET?

Instead of checking, just perform the action (web request, mail, ftp, etc.) and be prepared for the request to fail, which you have to do anyway, even if your check was successful.

Consider the following:

1 - check, and it is OK
2 - start to perform action 
3 - network goes down
4 - action fails
5 - lot of good your check did

If the network is down your action will fail just as rapidly as a ping, etc.

1 - start to perform action
2 - if the net is down(or goes down) the action will fail

USB Debugging option greyed out

Connect the phone to a PC, make sure your developer options are enabled. Then, connection type must be MTP or File Transfer. Charge only does not allow USB debugging(disables the option).

The 'json' native gem requires installed build tools

I would like to add that you should make sure that the generated config.yml file when doing ruby dk.rb init contains the path to the ruby installation you want to use DevKit with. In my case, I had the Heroku Toolbelt installed on my system, which provided its own ruby installation, located at a different place. The config.yml file used that particular installation, and that's not what I wanted. I had to manually edit the file to point it to the correct one, then continue with ruby dk.rb review, etc.

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

What resources are shared between threads?

From Wikipedia (I think that would make a really good answer for the interviewer :P)

Threads differ from traditional multitasking operating system processes in that:

  • processes are typically independent, while threads exist as subsets of a process
  • processes carry considerable state information, whereas multiple threads within a process share state as well as memory and other resources
  • processes have separate address spaces, whereas threads share their address space
  • processes interact only through system-provided inter-process communication mechanisms.
  • Context switching between threads in the same process is typically faster than context switching between processes.

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;

...

div {
    height: ~"calc(100vh - "@some-variable-height~")";
}

compiles to

div {
    height: calc(100vh - 10px );
}

How to escape "&" in XML?

use &amp; in place of &

change to

<string name="magazine">Newspaper &amp; Magazines</string>

How can the Euclidean distance be calculated with NumPy?

Find difference of two matrices first. Then, apply element wise multiplication with numpy's multiply command. After then, find summation of the element wise multiplied new matrix. Finally, find square root of the summation.

def findEuclideanDistance(a, b):
    euclidean_distance = a - b
    euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
    euclidean_distance = np.sqrt(euclidean_distance)
    return euclidean_distance

Return a `struct` from a function in C

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

works fine with newer versions of compilers. Just like id, content of the name gets copied to the assigned structure variable.

setContentView(R.layout.main); error

This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml

Simple PHP form: Attachment to email (code golf)

PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.

You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.

Initialize class fields in constructor or at declaration?

In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.

Displaying Image in Java

Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?

Use PHP composer to clone git repo

You can include git repository to composer.json like this:

"repositories": [
{
    "type": "package",
    "package": {
        "name": "example-package-name", //give package name to anything, must be unique
        "version": "1.0",
        "source": {
            "url": "https://github.com/example-package-name.git", //git url
            "type": "git",
            "reference": "master" //git branch-name
        }
    }
}],
"require" : {
  "example-package-name": "1.0"
}

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

Python Loop: List Index Out of Range

You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip the list with a slice of itself such that you can sum the pairs.

b = [i + j for i, j in zip(a, a[1:])]

Does IE9 support console.log, and is it a real function?

console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property

if (window.console)
    console.log(msg)

this throws an exception in IE9 and will not work correctly. Do not do this

if (console) 
    console.log(msg)

Duplicate keys in .NET dictionaries?

Also this is possible:

Dictionary<string, string[]> previousAnswers = null;

This way, we can have unique keys. Hope this works for you.

Using fonts with Rails asset pipeline

Here my approach to using fonts in asset pipeline:

1) Put all your font file under app/assets/fonts/, actually you are not restricted to put it under fonts folder name. You can put any subfolder name you like. E.g. app/assets/abc or app/assets/anotherfonts. But i highly recommend you put it under app/assets/fonts/ for better folder structure.

2) From your sass file, using the sass helper font-path to request your font assets like this

@font-face {
    font-family: 'FontAwesome';
    src: url(font-path('fontawesome-webfont.eot') + '?v=4.4.0');
    src: url(font-path('fontawesome-webfont.eot') + '?#iefix&v=4.4.0') format('embedded-opentype'),
         url(font-path('fontawesome-webfont.woff2') + '?v=4.4.0') format('woff2'),
         url(font-path('fontawesome-webfont.woff') + '?v=4.4.0') format('woff'),
         url(font-path('fontawesome-webfont.ttf') + '?v=4.4.0') format('truetype'),
         url(font-path('fontawesome-webfont.svg') + '?v=4.4.0#fontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

3) Run bundle exec rake assets:precompile from your local machine and see your application.css result. You should see something like this:

@font-face {
    font-family: 'FontAwesome';
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?v=4.4.0");
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?#iefix&v=4.4.0") format("embedded-opentype"), url("/assets/fontawesome-webfont-3c4a1bb7ce3234407184f0d80cc4dec075e4ad616b44dcc5778e1cfb1bc24019.woff2" "?v=4.4.0") format("woff2"), url("/assets/fontawesome-webfont-a7c7e4930090e038a280fd61d88f0dc03dad4aeaedbd8c9be3dd9aa4c3b6f8d1.woff" "?v=4.4.0") format("woff"), url("/assets/fontawesome-webfont-1b7f3de49d68b01f415574ebb82e6110a1d09cda2071ad8451bdb5124131a292.ttf" "?v=4.4.0") format("truetype"), url("/assets/fontawesome-webfont-7414288c272f6cc10304aa18e89bf24fb30f40afd644623f425c2c3d71fbe06a.svg" "?v=4.4.0#fontawesomeregular") format("svg");
    font-weight: normal;
    font-style: normal;
}

If you want to know more how asset pipeline work, you can visit the following simple guide: https://designcode.commandrun.com/rails-asset-pipeline-simple-guide-830e2e666f6c#.6lejlayk2

Delete newline in Vim

If you are on the first line, pressing (upper case) J will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing 3J will combine all 3 lines together.

git with IntelliJ IDEA: Could not read from remote repository

I tried all solutions above (Native, changing url of VCS repository, updating Git, updating IDEA, invalidating Caches), but nothing helped me. Finally I found solution that works for me.

SOLUTION: I closed Idea and replaced content of file ~\.IntelliJIdea20xx.x\config\options\git.xml with this:

<application>
  <component name="Git.Application.Settings">
    <option name="SSH_EXECUTABLE" value="IDEA_SSH" />
  </component>
</application>

Then I started IDEA, try to checkout SSH GIT repository and it works and existing projects works as well. Interesting fact is that when I switch to NATIVE in Idea Settings, repository not working.

How to remove all line breaks from a string

USE THIS FUNCTION BELOW AND MAKE YOUR LIFE EASY

The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.

function remove_linebreaks( var message ) {
    return message.replace( /[\r\n]+/gm, "" );
}

In the above expression, g and m are for global and multiline flags

How to determine if string contains specific substring within the first X characters

You can also use regular expressions (less readable though)

string regex = "^.{0,7}abc";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
string Value1 = "sssddabcgghh";

Console.WriteLine(reg.Match(Value1).Success);

How to install wkhtmltopdf on a linux based (shared hosting) web server

Version 12.5 of wkhtmltopdf only lists DEB files on their download page now. Being a mac user and not knowing much linux or what DEB files were I couldn't use the solutions posted.

This page helped me get past the knew twist of downloading a DEB file: http://www.g-loaded.eu/2008/01/28/how-to-extract-rpm-or-deb-packages/

Basically what I did was:

  1. Downloaded from https://wkhtmltopdf.org/downloads.html
  2. Unzipped the DEB file.
  3. Unzipped data.tar.xz
  4. Uploaded the binary in the unzipped 'usr' folder from step 3 (usr/local/bin/wkhtmltopdf)

Then I found out that the 'exec' function was disabled on my host. So make sure you can specifically run 'exec' if you're using PHP to run this. "Can I run the wkhtmltopdf binary" isn't specific enough. My fault.

What's the best way to cancel event propagation between nested ng-click calls?

What @JosephSilber said, or pass the $event object into ng-click callback and stop the propagation inside of it:

<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
  <img src="http://some_src" ng-click="nextImage($event)"/>
</div>
$scope.nextImage = function($event) {
  $event.stopPropagation();
  // Some code to find and display the next image
}

Handling identity columns in an "Insert Into TABLE Values()" statement?

The best practice is to explicitly list the columns:

Insert Into TableName(col1, col2,col2) Values(?, ?, ?)

Otherwise, your original insert will break if you add another column to your table.

How to create a byte array in C++?

Maybe you can leverage the std::bitset type available in C++11. It can be used to represent a fixed sequence of N bits, which can be manipulated by conventional logic.

#include<iostream>
#include<bitset>

class MissileLauncher {
 public:
  MissileLauncher() {}
  void show_bits() const {
    std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
  }

  bool toggle_a() {
    // toggles (i.e., flips) the value of `a` bit and returns the
    // resulting logical value
    m_abc[0].flip();
    return m_abc[0];
  }

  bool toggle_c() {
    // toggles (i.e., flips) the value of `c` bit and returns the
    // resulting logical value
    m_abc[2].flip();
    return m_abc[2];
  }

  bool matches(const std::bitset<3>& mask) {
    // tests whether all the bits specified in `mask` are turned on in
    // this instance's bitfield
    return ((m_abc & mask) == mask);
  }

 private:
  std::bitset<3> m_abc;
};

typedef std::bitset<3> Mask;
int main() {
  MissileLauncher ml;

  // notice that the bitset can be "built" from a string - this masks
  // can be made available as constants to test whether certain bits
  // or bit combinations are "on" or "off"
  Mask has_a("001");       // the zeroth bit
  Mask has_b("010");       // the first bit
  Mask has_c("100");       // the second bit
  Mask has_a_and_c("101"); // zeroth and second bits
  Mask has_all_on("111");  // all on!
  Mask has_all_off("000"); // all off!

  // I can even create masks using standard logic (in this case I use
  // the or "|" operator)
  Mask has_a_and_b = has_a | has_b;
  std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;

  // print "true" and "false" instead of "1" and "0"
  std::cout<<std::boolalpha;

  std::cout<<"Bits, as created"<<std::endl;
  ml.show_bits();
  std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
  std::cout<<"I will toggle a"<<std::endl;
  ml.toggle_a();
  std::cout<<"Resulting bits:"<<std::endl;
  ml.show_bits();  
  std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
  std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
  std::cout<<"Toggle c"<<std::endl;
  ml.toggle_c();
  std::cout<<"Resulting bits:"<<std::endl;
  ml.show_bits();    
  std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;  
  std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
  return 0;
}

Compiling using gcc 4.7.2

g++ example.cpp -std=c++11

I get:

This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,

=CONCATENATE(YEAR(C2),MONTH(C2)) 

Android XXHDPI resources

As per this PPI calculation tool, Google Nexus 10 has a display density of about 300 DPI...

However, Android documentation states that:

ldpi : ~120dpi mdpi : ~160dpi hdpi : ~240dpi xhdpi : ~320dpi xxhdpi is not specified.

I think we just let Android OS scale up xhdpi resources...

Git add all files modified, deleted, and untracked?

Try:

git add -A

Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:

git add -A .

Also see: Difference of git add -A and git add .

Why does background-color have no effect on this DIV?

Change it to:

<div style="background-color:black; overflow:hidden;" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

Basically the outer div only contains floats. Floats are removed from the normal flow. As such the outer div really contains nothing and thus has no height. It really is black but you just can't see it.

The overflow:hidden property basically makes the outer div enclose the floats. The other way to do this is:

<div style="background-color:black" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
<div style="clear:both></div>
</div>

Oh and just for completeness, you should really prefer classes to direct CSS styles.

How to set top-left alignment for UILabel for iOS application?

I have this problem to but my label was in UITableViewCell, and in fund that the easiest way to solve the problem was to create an empty UIView and set the label inside it with constraints to the top and to the left side only, on off curse set the number of lines to 0

Can I display the value of an enum with printf()?

enum MyEnum
{  A_ENUM_VALUE=0,
   B_ENUM_VALUE,
   C_ENUM_VALUE
};


int main()
{
 printf("My enum Value : %d\n", (int)C_ENUM_VALUE);
 return 0;
}

You have just to cast enum to int !
Output : My enum Value : 2

How do I purge a linux mail box with huge number of emails?

Rather than deleting, I think we can nullify the file, because the file will be created if the mail service is still on. Something like following will do the job

cat /dev/null >/var/spool/mail/tomlinuxusr

And yes, sorry for awakening this old thread but I felt I could contribute.

Updating records codeigniter

In your Controller

public function updtitle() 
{   
    $data = array(
        'table_name' => 'your_table_name_to_update', // pass the real table name
        'id' => $this->input->post('id'),
        'title' => $this->input->post('title')
    );

    $this->load->model('Updmodel'); // load the model first
    if($this->Updmodel->upddata($data)) // call the method from the model
    {
        // update successful
    }
    else
    {
        // update not successful
    }

}

In Your Model

public function upddata($data) {
    extract($data);
    $this->db->where('emp_no', $id);
    $this->db->update($table_name, array('title' => $title));
    return true;
}

The active record query is similar to

"update $table_name set title='$title' where emp_no=$id"

Detect touch press vs long press vs movement?

From the Android Docs -

onLongClick()

From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second).

onTouch()

From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item).

As for the "moving happens even when I touch" I would set a delta and make sure the View has been moved by at least the delta before kicking in the movement code. If it hasn't been, kick off the touch code.

Extract code country from phone number [libphonenumber]

Here's a an answer how to find country calling code without using third-party libraries (as real developer does):

Get list of all available country codes, Wikipedia can help here: https://en.wikipedia.org/wiki/List_of_country_calling_codes

Parse data in a tree structure where each digit is a branch.

Traverse your tree digit by digit until you are at the last branch - that's your country code.

Stop UIWebView from "bouncing" vertically?

It looks to me like the UIWebView has a UIScrollView. You can use documented APIs for this, but bouncing is set for both directions, not individually. This is in the API docs. UIScrollView has a bounce property, so something like this works (don't know if there's more than one scrollview):

NSArray *subviews = myWebView.subviews;
NSObject *obj = nil;
int i = 0;
for (; i < subviews.count ; i++)
{
    obj = [subviews objectAtIndex:i];

    if([[obj class] isSubclassOfClass:[UIScrollView class]] == YES)
    {
        ((UIScrollView*)obj).bounces = NO;
    }
}

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

Traverse all the Nodes of a JSON Object Tree with JavaScript

Most Javascript engines do not optimize tail recursion (this might not be an issue if your JSON isn't deeply nested), but I usually err on the side of caution and do iteration instead, e.g.

function traverse(o, fn) {
    const stack = [o]

    while (stack.length) {
        const obj = stack.shift()

        Object.keys(obj).forEach((key) => {
            fn(key, obj[key], obj)
            if (obj[key] instanceof Object) {
                stack.unshift(obj[key])
                return
            }
        })
    }
}

const o = {
    name: 'Max',
    legal: false,
    other: {
        name: 'Maxwell',
        nested: {
            legal: true
        }
    }
}

const fx = (key, value, obj) => console.log(key, value)
traverse(o, fx)

How do I use CMake?

I don't know about Windows (never used it), but on a Linux system you just have to create a build directory (in the top source directory)

mkdir build-dir

go inside it

cd build-dir

then run cmake and point to the parent directory

cmake ..

and finally run make

make

Notice that make and cmake are different programs. cmake is a Makefile generator, and the make utility is governed by a Makefile textual file. See cmake & make wikipedia pages.

NB: On Windows, cmake might operate so could need to be used differently. You'll need to read the documentation (like I did for Linux)

How do I set the default Java installation/runtime (Windows)?

This is a bit of a pain on Windows. Here's what I do.

Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11, then let the installer install public JRE in the default place (c:\program files\blah). This will setup your default JRE for the majority of things.

Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18, but don't install the public JREs.

When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED and then set PATH=%JAVA_HOME%\bin;%PATH%. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME variable.

The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe, which usually overrides most other settings.

jquery change class name

EDIT:

If you're saying that you're changing it from a nested element, you don't need the ID at all. You can do this instead:

$(this).closest('td').toggleClass('change_me some_other_class');
    //or
$(this).parents('td:first').toggleClass('change_me some_other_class');

Original answer:

$('#td_id').removeClass('change_me').addClass('some_other_class');

Another option is:

$('#td_id').toggleClass('change_me some_other_class');

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

A default/non-bare Git repo contains two pieces of state:

  1. A snapshot of all of the files in the repository (this is what "working tree" means in Git jargon)
  2. A history of all changes made to all the files that have ever been in the repository (there doesn't seem to be a concise piece of Git jargon that encompasses all of this)

The snapshot is what you probably think of as your project: your code files, build files, helper scripts, and anything else you version with Git.

The history is the state that allows you to check out a different commit and get a complete snapshot of what the files in your repository looked like when that commit was added. It consists of a bunch of data structures that are internal to Git that you've probably never interacted with directly. Importantly, the history doesn't just store metadata (e.g. "User U added this many lines to File F at Time T as part of Commit C"), it also stores data (e.g. "User U added these exact lines to File F").

The key idea of a bare repository is that you don't actually need to have the snapshot. Git keeps the snapshot around because it's convenient for humans and other non-Git processes that want to interact with your code, but the snapshot is just duplicating state that's already in the history.

A bare repository is a Git repository that does not have a snapshot. It just stores the history.

Why would you want this? Well, if you're only going to interact with your files using Git (that is, you're not going to edit your files directly or use them to build an executable), you can save space by not keeping around the snapshot. In particular, if you're maintaining a centralized version of your repo on a server somewhere (i.e. you're basically hosting your own GitHub), that server should probably have a bare repo (you would still use a non-bare repo on your local machine though, since you'll presumably want to edit your snapshot).

If you want a more in-depth explanation of bare repos and another example use case, I wrote up a blog post here: https://stegosaurusdormant.com/bare-git-repo/

CURL to access a page that requires a login from a different page

My answer is a mod of some prior answers from @JoeMills and @user.

  1. Get a cURL command to log into server:

    • Load login page for website and open Network pane of Developer Tools
      • In firefox, right click page, choose 'Inspect Element (Q)' and click on Network tab
    • Go to login form, enter username, password and log in
    • After you have logged in, go back to Network pane and scroll to the top to find the POST entry. Right click and choose Copy -> Copy as CURL
    • Paste this to a text editor and try this in command prompt to see if it works
      • Its possible that some sites have hardening that will block this type of login spoofing that would require more steps below to bypass.
  2. Modify cURL command to be able to save session cookie after login

    • Remove the entry -H 'Cookie: <somestuff>'
    • Add after curl at beginning -c login_cookie.txt
    • Try running this updated curl command and you should get a new file 'login_cookie.txt' in the same folder
  3. Call a new web page using this new cookie that requires you to be logged in

    • curl -b login_cookie.txt <url_that_requires_log_in>

I have tried this on Ubuntu 20.04 and it works like a charm.

What does the symbol \0 mean in a string-literal?

Specifically, I want to mention one situation, by which you may confuse.

What is the difference between "\0" and ""?

The answer is that "\0" represents in array is {0 0} and "" is {0}.

Because "\0" is still a string literal and it will also add "\0" at the end of it. And "" is empty but also add "\0".

Understanding of this will help you understand "\0" deeply.

What is class="mb-0" in Bootstrap 4?

m - for classes that set margin, like this :

  • mt - for classes that set margin-top
  • mb - for classes that set margin-bottom
  • ml - for classes that set margin-left
  • mr - for classes that set margin-right
  • mx - for classes that set both margin-left and margin-right
  • my - for classes that set both margin-top and margin-bottom

Where size is one of margin :

  • 0 - for classes that eliminate the margin by setting it to 0, like mt-0
  • 1 - (by default) for classes that set the margin to $spacer * .25, like mt-1
  • 2 - (by default) for classes that set the margin to $spacer * .5, like mt-2
  • 3 - (by default) for classes that set the margin to $spacer, like mt-3
  • 4 - (by default) for classes that set the margin to $spacer * 1.5, like mt-4
  • 5 - (by default) for classes that set the margin to $spacer * 3, like mt-5
  • auto - for classes that set the margin to auto, like mx-auto

ValidateAntiForgeryToken purpose, explanation and example

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.

A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.

It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:

[HttpPost]  
[ValidateAntiForgeryToken]  
public ActionResult CreateProduct(Product product)  
{
  if (ModelState.IsValid)  
  {
    //your logic 
  }
  return View(ModelName);
}

It is derived from System.Web.Mvc namespace.

And in your view, add this code to add the token so it is used to validate the form upon submission.

@Html.AntiForgeryToken()

'tuple' object does not support item assignment

You probably want the next transformation for you pixels:

pixels = map(list, image.getdata())

How to remove all of the data in a table using Django

If you want to remove all the data from all your tables, you might want to try the command python manage.py flush. This will delete all of the data in your tables, but the tables themselves will still exist.

See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/

How can I jump to class/method definition in Atom text editor?

For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-

https://atom.io/packages/atom-typescript#alternative-to-symbols-view

How to use enums in C++

If we want the strict type safety and scoped enum, using enum class is good in C++11.

If we had to work in C++98, we can using the advice given by InitializeSahib,San to enable the scoped enum.

If we also want the strict type safety, the follow code can implement somthing like enum.

#include <iostream>
class Color
{
public:
    static Color RED()
    {
        return Color(0);
    }
    static Color BLUE()
    {
        return Color(1);
    }
    bool operator==(const Color &rhs) const
    {
        return this->value == rhs.value;
    }
    bool operator!=(const Color &rhs) const
    {
        return !(*this == rhs);
    }

private:
    explicit Color(int value_) : value(value_) {}
    int value;
};

int main()
{
    Color color = Color::RED();
    if (color == Color::RED())
    {
        std::cout << "red" << std::endl;
    }
    return 0;
}

The code is modified from the class Month example in book Effective C++ 3rd: Item 18

How to change already compiled .class file without decompile?

Use java assist Java library for manipulating the Java bytecode (.class file) of an application.

-> Spring , Hibernate , EJB using this for proxy implementation

-> we can bytecode manipulation to do some program analysis

-> we can use Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.

Get current user id in ASP.NET Identity 2.0

GetUserId() is an extension method on IIdentity and it is in Microsoft.AspNet.Identity.IdentityExtensions. Make sure you have added the namespace with using Microsoft.AspNet.Identity;.

What is InputStream & Output Stream? Why and when do we use them?

An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends

import java.io.printstream;

class PPrint {
    static PPrintStream oout = new PPrintStream();
}

class PPrintStream {
    void print(String str) { 
        System.out.println(str)
    }
}

class outputstreamDemo {
    public static void main(String args[]) {
        System.out.println("hello world");
        System.out.prinln("this is output stream demo");
    }
}

Creating dummy variables in pandas for python

Based on the official documentation:

dummies = pd.get_dummies(df['Category']).rename(columns=lambda x: 'Category_' + str(x))
df = pd.concat([df, dummies], axis=1)
df = df.drop(['Category'], inplace=True, axis=1)

There is also a nice post in the FastML blog.

.NET - How do I retrieve specific items out of a Dataset?

I prefer to use something like this:

int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");

or

int? var1 = ds.Tables[0].Rows[0].Field<int?>(3);   //column index

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

What is a "cache-friendly" code?

As @Marc Claesen mentioned that one of the ways to write cache friendly code is to exploit the structure in which our data is stored. In addition to that another way to write cache friendly code is: change the way our data is stored; then write new code to access the data stored in this new structure.

This makes sense in the case of how database systems linearize the tuples of a table and store them. There are two basic ways to store the tuples of a table i.e. row store and column store. In row store as the name suggests the tuples are stored row wise. Lets suppose a table named Product being stored has 3 attributes i.e. int32_t key, char name[56] and int32_t price, so the total size of a tuple is 64 bytes.

We can simulate a very basic row store query execution in main memory by creating an array of Product structs with size N, where N is the number of rows in table. Such memory layout is also called array of structs. So the struct for Product can be like:

struct Product
{
   int32_t key;
   char name[56];
   int32_t price'
}

/* create an array of structs */
Product* table = new Product[N];
/* now load this array of structs, from a file etc. */

Similarly we can simulate a very basic column store query execution in main memory by creating an 3 arrays of size N, one array for each attribute of the Product table. Such memory layout is also called struct of arrays. So the 3 arrays for each attribute of Product can be like:

/* create separate arrays for each attribute */
int32_t* key = new int32_t[N];
char* name = new char[56*N];
int32_t* price = new int32_t[N];
/* now load these arrays, from a file etc. */

Now after loading both the array of structs (Row Layout) and the 3 separate arrays (Column Layout), we have row store and column store on our table Product present in our memory.

Now we move on to the cache friendly code part. Suppose that the workload on our table is such that we have an aggregation query on the price attribute. Such as

SELECT SUM(price)
FROM PRODUCT

For the row store we can convert the above SQL query into

int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + table[i].price;

For the column store we can convert the above SQL query into

int sum = 0;
for (int i=0; i<N; i++)
   sum = sum + price[i];

The code for the column store would be faster than the code for the row layout in this query as it requires only a subset of attributes and in column layout we are doing just that i.e. only accessing the price column.

Suppose that the cache line size is 64 bytes.

In the case of row layout when a cache line is read, the price value of only 1(cacheline_size/product_struct_size = 64/64 = 1) tuple is read, because our struct size of 64 bytes and it fills our whole cache line, so for every tuple a cache miss occurs in case of a row layout.

In the case of column layout when a cache line is read, the price value of 16(cacheline_size/price_int_size = 64/4 = 16) tuples is read, because 16 contiguous price values stored in memory are brought into the cache, so for every sixteenth tuple a cache miss ocurs in case of column layout.

So the column layout will be faster in the case of given query, and is faster in such aggregation queries on a subset of columns of the table. You can try out such experiment for yourself using the data from TPC-H benchmark, and compare the run times for both the layouts. The wikipedia article on column oriented database systems is also good.

So in database systems, if the query workload is known beforehand, we can store our data in layouts which will suit the queries in workload and access data from these layouts. In the case of above example we created a column layout and changed our code to compute sum so that it became cache friendly.

Import / Export database with SQL Server Server Management Studio

I tried the answers above but the generated script file was very large and I was having problems while importing the data. I ended up Detaching the database, then copying .mdf to my new machine, then Attaching it to my new version of SQL Server Management Studio.

I found instructions for how to do this on the Microsoft Website:
https://msdn.microsoft.com/en-us/library/ms187858.aspx

NOTE: After Detaching the database I found the .mdf file within this directory:
C:\Program Files\Microsoft SQL Server\

Best cross-browser method to capture CTRL+S with JQuery?

This works for me (using jquery) to overload Ctrl+S, Ctrl+F and Ctrl+G:

$(window).bind('keydown', function(event) {
    if (event.ctrlKey || event.metaKey) {
        switch (String.fromCharCode(event.which).toLowerCase()) {
        case 's':
            event.preventDefault();
            alert('ctrl-s');
            break;
        case 'f':
            event.preventDefault();
            alert('ctrl-f');
            break;
        case 'g':
            event.preventDefault();
            alert('ctrl-g');
            break;
        }
    }
});

How to fix 'android.os.NetworkOnMainThreadException'?

android.os.NetworkOnMainThreadException is thrown when network operations are performed on the main thread. You better do this in AsyncTask to remove this Exception. Write it this way:

    new AsyncTask<Void,String,String>(){

        @Override
        protected Void doInBackground(Void... params) {
            // Perform your network operation.
            // Get JSON or XML string from the server.
            // Store in a local variable (say response) and return.
            return response;
        }

        protected void onPostExecute(String results){
            // Response returned by doInBackGround() will be received
            // by onPostExecute(String results).
            // Now manipulate your jason/xml String(results).
        }

    }.execute();
}

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

docker build with --build-arg with multiple arguments

Use --build-arg with each argument.

If you are passing two argument then add --build-arg with each argument like:

docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .

array.select() in javascript

Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

The source code for Array.prototype is posted in MDN

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

How to log SQL statements in Spring Boot?

This works for me (YAML):

spring:
  jpa:
    properties:
      hibernate:
        show_sql: true
        format_sql: true
logging:
  level:
    org:
      hibernate:
        type: trace

TypeScript and array reduce function

With TypeScript generics you can do something like this.

class Person {
    constructor (public Name : string, public Age: number) {}
}

var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));

var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);

What is the JUnit XML format specification that Hudson supports?

Basic Structure Here is an example of a JUnit output file, showing a skip and failed result, as well as a single passed result.

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
   <testsuite name="JUnitXmlReporter" errors="0" tests="0" failures="0" time="0" timestamp="2013-05-24T10:23:58" />
   <testsuite name="JUnitXmlReporter.constructor" errors="0" skipped="1" tests="3" failures="1" time="0.006" timestamp="2013-05-24T10:23:58">
      <properties>
         <property name="java.vendor" value="Sun Microsystems Inc." />
         <property name="compiler.debug" value="on" />
         <property name="project.jdk.classpath" value="jdk.classpath.1.6" />
      </properties>
      <testcase classname="JUnitXmlReporter.constructor" name="should default path to an empty string" time="0.006">
         <failure message="test failure">Assertion failed</failure>
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default consolidate to true" time="0">
         <skipped />
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default useDotNotation to true" time="0" />
   </testsuite>
</testsuites>

Below is the documented structure of a typical JUnit XML report. Notice that a report can contain 1 or more test suite. Each test suite has a set of properties (recording environment information). Each test suite also contains 1 or more test case and each test case will either contain a skipped, failure or error node if the test did not pass. If the test case has passed, then it will not contain any nodes. For more details of which attributes are valid for each node please consult the following section "Schema".

<testsuites>        => the aggregated result of all junit testfiles
  <testsuite>       => the output from a single TestSuite
    <properties>    => the defined properties at test execution
      <property>    => name/value pair for a single property
      ...
    </properties>
    <error></error> => optional information, in place of a test case - normally if the tests in the suite could not be found etc.
    <testcase>      => the results from executing a test method
      <system-out>  => data written to System.out during the test run
      <system-err>  => data written to System.err during the test run
      <skipped/>    => test was skipped
      <failure>     => test failed
      <error>       => test encountered an error
    </testcase>
    ...
  </testsuite>
  ...
</testsuites>

What is the purpose of the : (colon) GNU Bash builtin?

Another way, not yet mentioned here is the initialisation of parameters in infinite while-loops. Below is not the cleanest example, but it serves it's purpose.

#!/usr/bin/env bash
[ "$1" ] && foo=0 && bar="baz"
while : "${foo=2}" "${bar:=qux}"; do
    echo "$foo"
    (( foo == 3 )) && echo "$bar" && break
    (( foo=foo+1 ))
done

Creating a new ArrayList in Java

Material please go through this Link And also try this

 ArrayList<Class> myArray= new ArrayList<Class>();

How to get ID of button user just clicked?

With pure javascript:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}?

http://jsfiddle.net/TKKBV/2/

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

BackgroundWorker vs background Thread

What's perplexing to me is that the visual studio designer only allows you to use BackgroundWorkers and Timers that don't actually work with the service project.

It gives you neat drag and drop controls onto your service but... don't even try deploying it. Won't work.

Services: Only use System.Timers.Timer System.Windows.Forms.Timer won't work even though it's available in the toolbox

Services: BackgroundWorkers will not work when it's running as a service Use System.Threading.ThreadPools instead or Async calls

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

Getting list of pixel values from PIL

pixVals = list(pilImg.getdata())

output is a list of all RGB values from the picture:

[(248, 246, 247), (246, 248, 247), (244, 248, 247), (244, 248, 247), (246, 248, 247), (248, 246, 247), (250, 246, 247), (251, 245, 247), (253, 244, 247), (254, 243, 247)]

Configuring so that pip install can work from github

You need the whole python package, with a setup.py file in it.

A package named foo would be:

foo # the installable package
+-- foo
¦   +-- __init__.py
¦   +-- bar.py
+-- setup.py

And install from github like:

$ pip install git+ssh://[email protected]/myuser/foo.git
or
$ pip install git+https://github.com/myuser/foo.git@v123
or
$ pip install git+https://github.com/myuser/foo.git@newbranch

More info at https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support

How to default to other directory instead of home directory

This will do it assuming you want this to happen each time you open the command line:

echo cd ../../../d/work_space_for_my_company/project/code_source >> ~/.bashrc

Now when you open the shell it will move up three directories from home and change to code_source.

This code simply appends the line "cd ../../../d/work_space_for_my_company/project/code_source" to a file named ".bashrc". The ">>" creates a file if it does not exist and then appends. The .bashrc file is useful for running commands at start-up/log-in time (i.e. loading modules etc.)

Extract a substring from a string in Ruby using a regular expression

String1.scan(/<([^>]*)>/).last.first

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

How to get the selected index of a RadioGroup in Android

All you need is to set values first to your RadioButton, for example:

RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);      
radioButton.setId(1);        //some int value

and then whenever this spacific radioButton will be chosen you can pull its value by the Id you gave it with

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);                     
int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
                                                       //should be inside the "radioGroup"
                                                       //in the XML

Cheers!

Laravel Migration table already exists, but I want to add new not the older

Add this to AppServiceProvider.php

use Illuminate\Support\Facades\Schema;
public function boot() {
    Schema::defaultStringLength(191);
}

How to downgrade Node version

In Mac there is a fast method with brew:

brew search node

You see some version, for example: node@10 node@12 ... Then

brew unlink node

And now select a before version for example node@12

brew link --overwrite --force node@12

Ready, you have downgraded you node version.

Changing Font Size For UITableView Section Headers

With this method you can set font size, font style and Header background also. there are have 2 method for this

First Method

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
        UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
        header.backgroundView.backgroundColor = [UIColor darkGrayColor];
        header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
        [header.textLabel setTextColor:[UIColor whiteColor]];
    }

Second Method

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
//    myLabel.frame = CGRectMake(20, 8, 320, 20);
    myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
    myLabel.text = [NSString stringWithFormat:@"   %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];

    myLabel.backgroundColor=[UIColor blueColor];
    myLabel.textColor=[UIColor whiteColor];
    UIView *headerView = [[UIView alloc] init];
    [headerView addSubview:myLabel];
    return headerView;
}

python - if not in list

You better do this syntax

if not (item in mylist):  
    Code inside the if

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

ASP.NET MVC Conditional validation

I've been using this amazing nuget that does dynamic annotations ExpressiveAnnotations

You could validate any logic you can dream of:

public string Email { get; set; }
public string Phone { get; set; }
[RequiredIf("Email != null")]
[RequiredIf("Phone != null")]
[AssertThat("AgreeToContact == true")]
public bool? AgreeToContact { get; set; }

Find the number of downloads for a particular app in apple appstore

found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:

d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)

How do you input command line arguments in IntelliJ IDEA?

If you are using intellij go to Run > Edit Configurations menu setting. A dialog box will appear. Now you can add arguments to the Program arguments input field.

How to convert webpage into PDF by using Python

here is the one working fine:

import sys 
from PyQt4.QtCore import *
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 

app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")

def convertIt():
    web.print_(printer)
    print("Pdf generated")
    QApplication.exit()

QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())

What causes a Python segmentation fault?

This happens when a python extension (written in C) tries to access a memory beyond reach.

You can trace it in following ways.

  • Add sys.settrace at the very first line of the code.
  • Use gdb as described by Mark in this answer.. At the command prompt

    gdb python
    (gdb) run /path/to/script.py
    ## wait for segfault ##
    (gdb) backtrace
    ## stack trace of the c code
    

A warning - comparison between signed and unsigned integer expressions

At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).

Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.

How to Find the Default Charset/Encoding in Java?

check

System.getProperty("sun.jnu.encoding")

it seems to be the same encoding as the one used in your system's command line.

Editor does not contain a main type

run "eclipse -clean -refresh" from command line. This fixed the issue for me when all other solutions failed.

C pointer to array/array of pointers disambiguation

int *arr1[5]

In this declaration, arr1 is an array of 5 pointers to integers. Reason: Square brackets have higher precedence over * (dereferncing operator). And in this type, number of rows are fixed (5 here), but number of columns is variable.

int (*arr2)[5]

In this declaration, arr2 is a pointer to an integer array of 5 elements. Reason: Here, () brackets have higher precedence than []. And in this type, number of rows is variable, but the number of columns is fixed (5 here).

How can I check if some text exist or not in the page using Selenium?

You could retrieve the body text of the whole page like this:

bodyText = self.driver.find_element_by_tag_name('body').text

then use an assert to check it like this:

self.assertTrue("the text you want to check for" in bodyText)

Of course, you can be specific and retrieve a specific DOM element's text and then check that instead of retrieving the whole page.

How to fully delete a git repository created with init?

Where $GIT_DIR is the path to the folder to be searched (the git repo path), execute the following in terminal.

find $GIT_DIR -name *.git* -ok rm -Rf {} \;

This will recursively search for any directories or files containing ".git" in the file/directory name within the specified Git directory. This will include .git/ and .gitignore files and any other .git-like assets. The command is interactive and will ask before removing. To proceed with the deletion, simply enter y, then Enter.

Indent List in HTML and CSS

You can also use html to override the css locally. I was having a similar issue and this worked for me:

<html>
<body>

<h4>A nested List:</h4>
<ul style="PADDING-LEFT: 12px">
  <li>Coffee</li>
  <li>Tea
    <ul>
    <li>Black tea</li>
    <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

</body>
</html>

How to set the env variable for PHP?

You need to add the PHP directory to your path. On the command line (e.g. in a batch file), it would look like this:

SET PATH=%PATH%;C:\your\wamp\path\php

if in doubt, it's the directory containing the php.exe.

You can also pre-set the path in Windows' control panel. See here on how to do this in Windows 7 for example.

Be aware that if you call the PHP executable from an arbitrary directory, that directory will be the working directory. You may need to adjust your scripts so they use the proper directories for their file operations (if there are any).

Angular: How to update queryParams without changing route

Better yet - just HTML:

<a [routerLink]="[]" [queryParams]="{key: 'value'}">Your Query Params Link</a>

Note the empty array instead of just doing routerLink="" or [routerLink]="''"

Replace invalid values with None in Pandas DataFrame

Before proceeding with this post, it is important to understand the difference between NaN and None. One is a float type, the other is an object type. Pandas is better suited to working with scalar types as many methods on these types can be vectorised. Pandas does try to handle None and NaN consistently, but NumPy cannot.

My suggestion (and Andy's) is to stick with NaN.

But to answer your question...

pandas >= 0.18: Use na_values=['-'] argument with read_csv

If you loaded this data from CSV/Excel, I have good news for you. You can quash this at the root during data loading instead of having to write a fix with code as a subsequent step.

Most of the pd.read_* functions (such as read_csv and read_excel) accept a na_values attribute.

file.csv

A,B
-,1
3,-
2,-
5,3
1,-2
-5,4
-1,-1
-,0
9,0

Now, to convert the - characters into NaNs, do,

import pandas as pd
df = pd.read_csv('file.csv', na_values=['-'])
df

     A    B
0  NaN  1.0
1  3.0  NaN
2  2.0  NaN
3  5.0  3.0
4  1.0 -2.0
5 -5.0  4.0
6 -1.0 -1.0
7  NaN  0.0
8  9.0  0.0

And similar for other functions/file formats.

P.S.: On v0.24+, you can preserve integer type even if your column has NaNs (yes, talk about having the cake and eating it too). You can specify dtype='Int32'

df = pd.read_csv('file.csv', na_values=['-'], dtype='Int32')
df

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

df.dtypes

A    Int32
B    Int32
dtype: object

The dtype is not a conventional int type... but rather, a Nullable Integer Type. There are other options.


Handling Numeric Data: pd.to_numeric with errors='coerce

If you're dealing with numeric data, a faster solution is to use pd.to_numeric with the errors='coerce' argument, which coerces invalid values (values that cannot be cast to numeric) to NaN.

pd.to_numeric(df['A'], errors='coerce')

0    NaN
1    3.0
2    2.0
3    5.0
4    1.0
5   -5.0
6   -1.0
7    NaN
8    9.0
Name: A, dtype: float64

To retain (nullable) integer dtype, use

pd.to_numeric(df['A'], errors='coerce').astype('Int32')

0    NaN
1      3
2      2
3      5
4      1
5     -5
6     -1
7    NaN
8      9
Name: A, dtype: Int32 

To coerce multiple columns, use apply:

df[['A', 'B']].apply(pd.to_numeric, errors='coerce').astype('Int32')

     A    B
0  NaN    1
1    3  NaN
2    2  NaN
3    5    3
4    1   -2
5   -5    4
6   -1   -1
7  NaN    0
8    9    0

...and assign the result back after.

More information can be found in this answer.

must declare a named package eclipse because this compilation unit is associated to the named module

Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.

Quick fix:

  1. Create a package eg. helloWorld inside the src folder.
  2. Move helloWorld.java file in that package. Just drag and drop on the package. Error should disappear.

Explanation:

  • My Eclipse version: 2020-09 (4.17.0)
  • My Java version: Java 15, 2020-09-15

Latest version of Eclipse required java11 or above. The module feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules

When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java file. If you select don't create then module-info.java will not create and your project will free from this issue.

Best practice is while crating project, after giving project name. Click on next button instead of finish. On next page at the bottom it ask for creation of module-info.java file. Select or deselect as per need.

If selected: (by default) click on finish button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.

If deselect: No issue

Why do people write #!/usr/bin/env python on the first line of a Python script?

The line #!/bin/bash/python3 or #!/bin/bash/python specifies which python compiler to use. You might have multiple python versions installed. For example,
a.py :

#!/bin/bash/python3
print("Hello World")

is a python3 script, and
b.py :

#!/bin/bash/python
print "Hello World"

is a python 2.x script
In order to run this file ./a.py or ./b.py is used, you need to give the files execution privileges before hand, otherwise executing will lead to Permission denied error.
For giving execution permission,

chmod +x a.py

Filter an array using a formula (without VBA)

This will do it if you only want the first "B" value, you can sub a cell address for "B" if you want to make it more generic.

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(B2:B6)="B",0)),1)

To use this based on two columns, just concatenate inside the match:

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(A2:A6&B2:B6)=("3"&"B"),0)),1)

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

sql server #region

No, #region does not exist in the T-SQL language.

You can get code-folding using begin-end blocks:

-- my region
begin
    -- code goes here
end

I'm not sure I'd recommend using them for this unless the code cannot be acceptably refactored by other means though!

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

Addition for BigDecimal

Just another example to add BigDecimals. Key point is that they are immutable and they can be initialized only in the constructor. Here is the code:

import java.util.*;
import java.math.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc;
        boolean first_right_number = false;
        BigDecimal initBigDecimal = BigDecimal.ZERO;
        BigDecimal add1 = BigDecimal.ZERO;
        BigDecimal add2 = BigDecimal.ZERO;

        while (!first_right_number)
        {
            System.out.print("Enter a first single numeric value: ");
            sc = new Scanner(System.in);
            if (sc.hasNextBigDecimal()) 
            {
                first_right_number = true;
                add1 = sc.nextBigDecimal();
            }
        }

        boolean second_right_number = false;
        while (!second_right_number)
        {
            System.out.print("Enter a second single numeric value: ");
            sc = new Scanner(System.in);
            if (sc.hasNextBigDecimal()) 
            {
                second_right_number = true;
                add2 = sc.nextBigDecimal();
            }
        }
        BigDecimal result = initBigDecimal.add(add1).add(add2);
        System.out.println("Sum of the 2 numbers is: " + result.toString());
    }
}

How to debug Ruby scripts

  1. You can print your variables out along the way
  2. Turn on the -w (warnings) flag
  3. Use a tool such as ruby-debug