Programs & Examples On #Mouse coordinates

How do I get the current mouse screen coordinates in WPF?

Or in pure WPF use PointToScreen.

Sample helper method:

// Gets the absolute mouse position, relative to screen
Point GetMousePos() => _window.PointToScreen(Mouse.GetPosition(_window));

Is there a simple way to use button to navigate page as a link does in angularjs

You can also register $location on the scope in the controller (to make it accessible from html)

angular.module(...).controller("...", function($location) {
  $scope.$location = $location;
  ...
});

and then go straight for the honey in your html:

<button ng-click="$location.path('#/new-page.html')">New Page<button>

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

JQuery Validate Dropdown list

Easiest way to get it done is by adding required into your select

Select the best option
<br/>

<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> 

<br/><br/>?

Powershell script does not run via Scheduled Tasks

One more idea that worked. It's really silly, but, apparently, the default target OS setting (bottom right corner of the screen) is Vista / Windows Server 2008. As we're past the 10 year mark, it is likely that your Powershell script will not be compatible to these.

Changing the target to Windows Server 2016, as shown on the screenshot below, did the trick for me.

Change the setting on the screenshot

How to find the difference in days between two dates?

I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:

A=2003-12-11
B=2002-10-10
DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
echo $DIFF

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

Here is Kotlin version.
Thanks you :)

         fun unSafeOkHttpClient() :OkHttpClient.Builder {
            val okHttpClient = OkHttpClient.Builder()
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts:  Array<TrustManager> = arrayOf(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?){}
                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {}
                    override fun getAcceptedIssuers(): Array<X509Certificate>  = arrayOf()
                })

                // Install the all-trusting trust manager
                val  sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())

                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory
                if (trustAllCerts.isNotEmpty() &&  trustAllCerts.first() is X509TrustManager) {
                    okHttpClient.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
                    okHttpClient.hostnameVerifier { _, _ -> true }
                }

                return okHttpClient
            } catch (e: Exception) {
                return okHttpClient
            }
        }

How to re-index all subarray elements of a multidimensional array?

$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);

Array ( [0] => apple [1] => cherry )

//...
array_multisort($result, SORT_DESC);
//...

Array ( [0] => cherry [1] => apple )

Setting environment variable in react-native?

I use babel-plugin-transform-inline-environment-variables.

What I did was put a configuration files within S3 with my different environments.

s3://example-bucket/dev-env.sh
s3://example-bucket/prod-env.sh
s3://example-bucket/stage-env.sh

EACH env file:

FIRSTENV=FIRSTVALUE
SECONDENV=SECONDVALUE

Afterwards, I added a new script in my package.json that runs a script for bundling

if [ "$ENV" == "production" ]
then
  eval $(aws s3 cp s3://example-bucket/prod-env.sh - | sed 's/^/export /')
elif [ "$ENV" == "staging" ]
then
  eval $(aws s3 cp s3://example-bucket/stage-env.sh - | sed 's/^/export /')
else
  eval $(aws s3 cp s3://example-bucket/development-env.sh - | sed 's/^/export /')
fi

react-native start

Within your app you will probably have a config file that has:

const FIRSTENV = process.env['FIRSTENV']
const SECONDENV = process.env['SECONDENV']

which will be replaced by babel to:

const FIRSTENV = 'FIRSTVALUE'
const SECONDENV = 'SECONDVALUE'

REMEMBER you have to use process.env['STRING'] NOT process.env.STRING or it won't convert properly.

Check if a string is a valid Windows directory (folder) path

Call Path.GetFullPath; it will throw exceptions if the path is invalid.

To disallow relative paths (such as Word), call Path.IsPathRooted.

What's the difference between StaticResource and DynamicResource in WPF?

Important benefit of the dynamic resources

if application startup takes extremely long time, you must use dynamic resources, because static resources are always loaded when the window or app is created, while dynamic resources are loaded when they’re first used.

However, you won’t see any benefit unless your resource is extremely large and complex.

Android DialogFragment vs Dialog

I would recommend using DialogFragment.

Sure, creating a "Yes/No" dialog with it is pretty complex considering that it should be rather simple task, but creating a similar dialog box with Dialog is surprisingly complicated as well.

(Activity lifecycle makes it complicated - you must let Activity manage the lifecycle of the dialog box - and there is no way to pass custom parameters e.g. the custom message to Activity.showDialog if using API levels under 8)

The nice thing is that you can usually build your own abstraction on top of DialogFragment pretty easily.

C# static class constructor

You can use static constructor to initialization static variable. Static constructor will be entry point for your class

public class MyClass
{

    static MyClass()
    {

        //write your initialization code here
    }

}

How to remove duplicate values from an array in PHP

I have done this without using any function.

$arr = array("1", "2", "3", "4", "5", "4", "2", "1");

$len = count($arr);
for ($i = 0; $i < $len; $i++) {
  $temp = $arr[$i];
  $j = $i;
  for ($k = 0; $k < $len; $k++) {
    if ($k != $j) {
      if ($temp == $arr[$k]) {
        echo $temp."<br>";
        $arr[$k]=" ";
      }
    }
  }
}

for ($i = 0; $i < $len; $i++) {
  echo $arr[$i] . " <br><br>";
}

How to count the number of true elements in a NumPy bool array

In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:

Prediction:

[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]

Target:

[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

Pandas - Plotting a stacked Bar Chart

Maybe you can use pandas crosstab function

test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])

test5.plot(kind='bar', stacked=True)

SQLite - UPSERT *not* INSERT or REPLACE

Here is a solution that really is an UPSERT (UPDATE or INSERT) instead of an INSERT OR REPLACE (which works differently in many situations).

It works like this:
1. Try to update if a record with the same Id exists.
2. If the update did not change any rows (NOT EXISTS(SELECT changes() AS change FROM Contact WHERE change <> 0)), then insert the record.

So either an existing record was updated or an insert will be performed.

The important detail is to use the changes() SQL function to check if the update statement hit any existing records and only perform the insert statement if it did not hit any record.

One thing to mention is that the changes() function does not return changes performed by lower-level triggers (see http://sqlite.org/lang_corefunc.html#changes), so be sure to take that into account.

Here is the SQL...

Test update:

--Create sample table and records (and drop the table if it already exists)
DROP TABLE IF EXISTS Contact;
CREATE TABLE [Contact] (
  [Id] INTEGER PRIMARY KEY, 
  [Name] TEXT
);
INSERT INTO Contact (Id, Name) VALUES (1, 'Mike');
INSERT INTO Contact (Id, Name) VALUES (2, 'John');

-- Try to update an existing record
UPDATE Contact
SET Name = 'Bob'
WHERE Id = 2;

-- If no record was changed by the update (meaning no record with the same Id existed), insert the record
INSERT INTO Contact (Id, Name)
SELECT 2, 'Bob'
WHERE NOT EXISTS(SELECT changes() AS change FROM Contact WHERE change <> 0);

--See the result
SELECT * FROM Contact;

Test insert:

--Create sample table and records (and drop the table if it already exists)
DROP TABLE IF EXISTS Contact;
CREATE TABLE [Contact] (
  [Id] INTEGER PRIMARY KEY, 
  [Name] TEXT
);
INSERT INTO Contact (Id, Name) VALUES (1, 'Mike');
INSERT INTO Contact (Id, Name) VALUES (2, 'John');

-- Try to update an existing record
UPDATE Contact
SET Name = 'Bob'
WHERE Id = 3;

-- If no record was changed by the update (meaning no record with the same Id existed), insert the record
INSERT INTO Contact (Id, Name)
SELECT 3, 'Bob'
WHERE NOT EXISTS(SELECT changes() AS change FROM Contact WHERE change <> 0);

--See the result
SELECT * FROM Contact;

Branch from a previous commit using Git

You can do it in Stash.

  1. Click the commit
  2. On the right top of the screen click "Tag this commit"
  3. Then you can create the new branch from the tag you just created.

Excel formula to search if all cells in a range read "True", if not, then show "False"

You can just AND the results together if they are stored as TRUE / FALSE values:

=AND(A1:D2)

Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.

=AND(EXACT(A1:D2,"TRUE"))

Can I do Model->where('id', ARRAY) multiple where conditions?

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

How do you display code snippets in MS Word preserving format and syntax highlighting?

Simplest solution, for me atleast, is to paste your code into the document, highlight it, then navigate to:

home -> styles -> << click drop down arrow by styles >> -> code

This has the advantage that the code is now searchable within the document (unlike gargamel's solution), as well as being able to format code that is multiple pages.

SQL - Query to get server's IP address

A simpler way to get the machine name without the \InstanceName is:

SELECT SERVERPROPERTY('MachineName')

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

android start activity from service

one cannot use the Context of the Service; was able to get the (package) Context alike:

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);

scale Image in an UIButton to AspectFit?

I have a method that does it for me. The method takes UIButton and makes the image aspect fit.

-(void)makeImageAspectFitForButton:(UIButton*)button{
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}

How do I automatically play a Youtube video (IFrame API) muted?

_x000D_
_x000D_
var video1;_x000D_
_x000D_
function onYouTubeIframeAPIReady(){_x000D_
 player = new YT.Player("video1", {_x000D_
  videoId: "id-number",_x000D_
  width: 300,_x000D_
  height: 200, _x000D_
  playerVars: {_x000D_
   "autoplay": 1, // and 0 means off_x000D_
   "controls": 1,_x000D_
   "showinfo": 0,_x000D_
   "modestbranding": 0,_x000D_
   "loop": 1,_x000D_
   "fs": 0,_x000D_
   "cc_load_policy": 0,_x000D_
   "iv_load_policy": 3,_x000D_
   },_x000D_
  events: {_x000D_
      'onReady': onPlayerReady_x000D_
  }_x000D_
 });_x000D_
  }_x000D_
_x000D_
function onPlayerReady(event) {_x000D_
    event.target.mute();_x000D_
    event.target.setVolume(0); //this can be set from 0 to 100_x000D_
}
_x000D_
_x000D_
_x000D_

Remember that the sound will not be muted in IE and Safari.

How can I send a file document to the printer and have it print?

Adding a new answer to this as the question of printing PDF's in .net has been around for a long time and most of the answers pre-date the Google Pdfium library, which now has a .net wrapper. For me I was researching this problem myself and kept coming up blank, trying to do hacky solutions like spawning Acrobat or other PDF readers, or running into commercial libraries that are expensive and have not very compatible licensing terms. But the Google Pdfium library and the PdfiumViewer .net wrapper are Open Source so are a great solution for a lot of developers, myself included. PdfiumViewer is licensed under the Apache 2.0 license.

You can get the NuGet package here:

https://www.nuget.org/packages/PdfiumViewer/

and you can find the source code here:

https://github.com/pvginkel/PdfiumViewer

Here is some simple code that will silently print any number of copies of a PDF file from it's filename. You can load PDF's from a stream also (which is how we normally do it), and you can easily figure that out looking at the code or examples. There is also a WinForm PDF file view so you can also render the PDF files into a view or do print preview on them. For us I simply needed a way to silently print the PDF file to a specific printer on demand.

public bool PrintPDF(
    string printer,
    string paperName,
    string filename,
    int copies)
{
    try {
        // Create the printer settings for our printer
        var printerSettings = new PrinterSettings {
            PrinterName = printer,
            Copies = (short)copies,
        };

        // Create our page settings for the paper size selected
        var pageSettings = new PageSettings(printerSettings) {
            Margins = new Margins(0, 0, 0, 0),
        };
        foreach (PaperSize paperSize in printerSettings.PaperSizes) {
            if (paperSize.PaperName == paperName) {
                pageSettings.PaperSize = paperSize;
                break;
            }
        }

        // Now print the PDF document
        using (var document = PdfDocument.Load(filename)) {
            using (var printDocument = document.CreatePrintDocument()) {
                printDocument.PrinterSettings = printerSettings;
                printDocument.DefaultPageSettings = pageSettings;
                printDocument.PrintController = new StandardPrintController();
                printDocument.Print();
            }
        }
        return true;
    } catch {
        return false;
    }
}

SpringMVC RequestMapping for GET parameters

You should write a kind of template into the @RequestMapping:

http://localhost:8080/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}

Now define your business method like following:

@RequestMapping("/userGrid?_search=${search}&nd=${nd}&rows=${rows}&page=${page}&sidx=${sidx}&sord=${sord}")
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "search") String search, 
@RequestParam(value = "nd") int nd, 
@RequestParam(value = "rows") int rows, 
@RequestParam(value = "page") int page, 
@RequestParam(value = "sidx") int sidx, 
@RequestParam(value = "sort") Sort sort) {
...............
}

So, framework will map ${foo} to appropriate @RequestParam.

Since sort may be either asc or desc I'd define it as a enum:

public enum Sort {
    asc, desc
}

Spring deals with enums very well.

Using Thymeleaf when the value is null

Sure there is. You can for example use the conditional expressions. For example:

<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty} : 'null value!'">someValue</span>

You can even omit the "else" expression:

<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty}">someValue</span>

You can also take a look at the Elvis operator to display default values.

Left join only selected columns in R with the merge() function

Nothing elegant but this could be another satisfactory answer.

merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]

This will be useful especially when you don't need the keys that were used to join the tables in your results.

div hover background-color change?

.e:hover{
   background-color:#FF0000;
}

Get the string within brackets in Python

your_string = "lnfgbdgfi343456dsfidf[my data] ljfbgns47647jfbgfjbgskj"
your_string[your_string.find("[")+1 : your_string.find("]")]

courtesy: Regular expression to return text between parenthesis

tsconfig.json: Build:No inputs were found in config file

I was getting this error:

No inputs were found in config file 'tsconfig.json'.

Specified include paths were '["**/*"]' and exclude paths '["**/*.spec.ts","app_/**/*.ts","**/*.d.ts","node_modules"]'.

I had a .tsconfig file, which read TS files from the ./src folder.

The issue here was that with the source folder not containing any .ts files and I was running tslint. I resolved issue by removing tslint task from my gulp file, as I don't have any .ts files to be compiled and linted.

Linking to an external URL in Javadoc?

Taken from the javadoc spec

@see <a href="URL#value">label</a> : Adds a link as defined by URL#value. The URL#value is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<) as the first character.

For example : @see <a href="http://www.google.com">Google</a>

Check if a value is in an array (C#)

    public static bool Contains(Array a, object val)
    {
        return Array.IndexOf(a, val) != -1;
    }

Regular expression to match numbers with or without commas and decimals in text

\b\d+,

\b------->word boundary

\d+------>one or digit

,-------->containing commas,

Eg:

sddsgg 70,000 sdsfdsf fdgfdg70,00

sfsfsd 5,44,4343 5.7788,44 555

It will match:

70,

5,

44,

,44

Detect when an image fails to load in Javascript

Here's a function I wrote for another answer: Javascript Image Url Verify. I don't know if it's exactly what you need, but it uses the various techniques that you would use which include handlers for onload, onerror, onabort and a general timeout.

Because image loading is asynchronous, you call this function with your image and then it calls your callback sometime later with the result.

How disable / remove android activity label and label bar?

Whenever I do rake run:android,

my Androidmenifest.xml file is built-up again so my changes done

for NoTitlebar no more persist.

Rather than user adroid_title: 0

This helped me.

edit your build.yml

android:
  android_title: 0
  #rest of things 
  #you needed 

When should I use the Visitor Design Pattern?

Everyone here is correct, but I think it fails to address the "when". First, from Design Patterns:

Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Now, let's think of a simple class hierarchy. I have classes 1, 2, 3 and 4 and methods A, B, C and D. Lay them out like in a spreadsheet: the classes are lines and the methods are columns.

Now, Object Oriented design presumes you are more likely to grow new classes than new methods, so adding more lines, so to speak, is easier. You just add a new class, specify what's different in that class, and inherits the rest.

Sometimes, though, the classes are relatively static, but you need to add more methods frequently -- adding columns. The standard way in an OO design would be to add such methods to all classes, which can be costly. The Visitor pattern makes this easy.

By the way, this is the problem that Scala's pattern matches intends to solve.

What is the meaning of "operator bool() const"

I'd like to give more codes to make it clear.

struct A
{
    operator bool() const { return true; }
};

struct B
{
    explicit operator bool() const { return true; }
};

int main()
{
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}

What is the difference between "::" "." and "->" in c++

The three operators have related but different meanings, despite the misleading note from the IDE.

The :: operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.

The . and -> operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).

The this object is always a pointer to the current instance, hence why the -> operator is the only one that works.

Examples:

// In a header file
namespace Namespace {
    class Class {
        private:
            int x;
        public:
            Class() : x(4) {}
            void incrementX();
    };
}

// In an implementation file
namespace Namespace {
    void Class::incrementX() {    // Using scope resolution to get to the class member when we aren't using an instance
        ++(this->x);              // this is a pointer, so using ->. Equivalent to ++((*this).x)
    }
}

// In a separate file lies your main method
int main() {
    Namespace::Class myInstance;   // instantiates an instance. Note the scope resolution
    Namespace::Class *myPointer = new Namespace::Class;
    myInstance.incrementX();       // Calling a function on an object instance.
    myPointer->incrementX();       // Calling a function on an object pointer.
    (*myPointer).incrementX();     // Calling a function on an object pointer by dereferencing first

    return 0;
}

Autoplay audio files on an iPad with HTML5

Try calling the .load() method before the .play() method on the audio or video tag... which will be HTMLAudioElement or HTMLVideoElement respectively. That was the only way it would work on the iPad for me!

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

In which case do you use the JPA @JoinTable annotation?

It's also cleaner to use @JoinTable when an Entity could be the child in several parent/child relationships with different types of parents. To follow up with Behrang's example, imagine a Task can be the child of Project, Person, Department, Study, and Process.

Should the task table have 5 nullable foreign key fields? I think not...

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 192.168.1.2 30088

Conditional formatting, entire row based

Use the "indirect" function on conditional formatting.

  1. Select Conditional Formatting
  2. Select New Rule
  3. Select "Use a Formula to determine which cells to format"
  4. Enter the Formula, =INDIRECT("g"&ROW())="X"
  5. Enter the Format you want (text color, fill color, etc).
  6. Select OK to save the new format
  7. Open "Manage Rules" in Conditional Formatting
  8. Select "This Worksheet" if you can't see your new rule.
  9. In the "Applies to" box of your new rule, enter =$A$1:$Z$1500 (or however wide/long you want the conditional formatting to extend depending on your worksheet)

For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.

You can repeat this to do multiple row formatting depending on a column value. Just change either the g column or x specific text in the formula and set different formats.

For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR", then it will format every row that has CAR in the H Column as the format you specified.

The role of #ifdef and #ifndef

Text inside an ifdef/endif or ifndef/endif pair will be left in or removed by the pre-processor depending on the condition. ifdef means "if the following is defined" while ifndef means "if the following is not defined".

So:

#define one 0
#ifdef one
    printf("one is defined ");
#endif
#ifndef one
    printf("one is not defined ");
#endif

is equivalent to:

printf("one is defined ");

since one is defined so the ifdef is true and the ifndef is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:

#define one 0
#ifdef one
    printf("one is defined ");
#else
    printf("one is not defined ");
#endif

since that specifies the intent more clearly in this particular situation.

In your particular case, the text after the ifdef is not removed since one is defined. The text after the ifndef is removed for the same reason. There will need to be two closing endif lines at some point and the first will cause lines to start being included again, as follows:

     #define one 0
+--- #ifdef one
|    printf("one is defined ");     // Everything in here is included.
| +- #ifndef one
| |  printf("one is not defined "); // Everything in here is excluded.
| |  :
| +- #endif
|    :                              // Everything in here is included again.
+--- #endif

Attach a file from MemoryStream to a MailMessage in C#

If all you're doing is attaching a string, you could do it in just 2 lines:

mail.Attachments.Add(Attachment.CreateAttachmentFromString("1,2,3", "text/csv");
mail.Attachments.Last().ContentDisposition.FileName = "filename.csv";

I wasn't able to get mine to work using our mail server with StreamWriter.
I think maybe because with StreamWriter you're missing a lot of file property information and maybe our server didn't like what was missing.
With Attachment.CreateAttachmentFromString() it created everything I needed and works great!

Otherwise, I'd suggest taking your file that is in memory and opening it using MemoryStream(byte[]), and skipping the StreamWriter all together.

What is the equivalent of "!=" in Excel VBA?

Try to use <> instead of !=.

Access index of last element in data frame

You want .iloc with double brackets.

import pandas as pd
df = pd.DataFrame({"date": range(10, 64, 8), "not_date": "fools"})
df.index += 17
df.iloc[[0,-1]][['date']]

You give .iloc a list of indexes - specifically the first and last, [0, -1]. That returns a dataframe from which you ask for the 'date' column. ['date'] will give you a series (yuck), and [['date']] will give you a dataframe.

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Since everyone else is posting their methods, I figured I'd post the extension method I usually use for this:

EDIT: added int/long variants...and fixed a copypasta typo...

public static class Ext
{
    private const long OneKb = 1024;
    private const long OneMb = OneKb * 1024;
    private const long OneGb = OneMb * 1024;
    private const long OneTb = OneGb * 1024;

    public static string ToPrettySize(this int value, int decimalPlaces = 0)
    {
        return ((long)value).ToPrettySize(decimalPlaces);
    }

    public static string ToPrettySize(this long value, int decimalPlaces = 0)
    {
        var asTb = Math.Round((double)value / OneTb, decimalPlaces);
        var asGb = Math.Round((double)value / OneGb, decimalPlaces);
        var asMb = Math.Round((double)value / OneMb, decimalPlaces);
        var asKb = Math.Round((double)value / OneKb, decimalPlaces);
        string chosenValue = asTb > 1 ? string.Format("{0}Tb",asTb)
            : asGb > 1 ? string.Format("{0}Gb",asGb)
            : asMb > 1 ? string.Format("{0}Mb",asMb)
            : asKb > 1 ? string.Format("{0}Kb",asKb)
            : string.Format("{0}B", Math.Round((double)value, decimalPlaces));
        return chosenValue;
    }
}

Python Graph Library

I second zweiterlinde's suggestion to use python-graph. I've used it as the basis of a graph-based research project that I'm working on. The library is well written, stable, and has a good interface. The authors are also quick to respond to inquiries and reports.

Laravel - Forbidden You don't have permission to access / on this server

For me this was simply calling route() on a named route that I had not created/created incorrectly. This caused the Forbidden error page.

Restarting the web server allowed proper Whoops! error to display:

Route [my-route-name] not defined.

Fixing the route name ->name('my-route-name') fixed the error.

This is on Laravel 5.5 & using wampserver.

SQLite error 'attempt to write a readonly database' during insert?

The problem, as it turns out, is that the PDO SQLite driver requires that if you are going to do a write operation (INSERT,UPDATE,DELETE,DROP, etc), then the folder the database resides in must have write permissions, as well as the actual database file.

I found this information in a comment at the very bottom of the PDO SQLite driver manual page.

Return file in ASP.Net Core Web API

Here is a simplistic example of streaming a file:

using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
    var path = "<Get the file path using the ID>";
    var stream = File.OpenRead(path);
    return new FileStreamResult(stream, "application/octet-stream");
}

Note:

Be sure to use FileStreamResult from Microsoft.AspNetCore.Mvc and not from System.Web.Mvc.

SQL: ... WHERE X IN (SELECT Y FROM ...)

Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN. Use whatever is more readable to you.

CheckBox in RecyclerView keeps on checking different items

As stated above, the checked state of the object should be included within object properties. In some cases you may need also to change the object selection state by clicking on the object itself and let the CheckBox inform about the actual state (either selected or unselected). The checkbox will then use the state of the object at the actual position of the given adapter which is (by default/in most cases) the position of the element in the list.

Check the snippet below, it may be useful.

_x000D_
_x000D_
import android.content.Context;_x000D_
import android.graphics.Bitmap;_x000D_
import android.net.Uri;_x000D_
import android.provider.MediaStore;_x000D_
import android.support.v7.widget.RecyclerView;_x000D_
import android.view.LayoutInflater;_x000D_
import android.view.View;_x000D_
import android.view.ViewGroup;_x000D_
import android.widget.CheckBox;_x000D_
import android.widget.CompoundButton;_x000D_
import android.widget.ImageView;_x000D_
_x000D_
import java.io.File;_x000D_
import java.io.IOException;_x000D_
import java.util.List;_x000D_
_x000D_
public class TakePicImageAdapter extends RecyclerView.Adapter<TakePicImageAdapter.ViewHolder>{_x000D_
    private Context context;_x000D_
    private List<Image> imageList;_x000D_
_x000D_
    public TakePicImageAdapter(Context context, List<Image> imageList) {_x000D_
        this.context = context;_x000D_
        this.imageList = imageList;_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public TakePicImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
        View view= LayoutInflater.from(context).inflate(R.layout.image_item,parent,false);_x000D_
        return new ViewHolder(view);_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public void onBindViewHolder(final TakePicImageAdapter.ViewHolder holder, final int position) {_x000D_
        File file=new File(imageList.get(position).getPath());_x000D_
        try {_x000D_
            Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(file));_x000D_
            holder.image.setImageBitmap(bitmap_x000D_
            );_x000D_
        } catch (IOException e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
        holder.selectImage.setOnCheckedChangeListener(null);_x000D_
        holder.selectImage.setChecked(imageList.get(position).isSelected());_x000D_
        holder.selectImage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {_x000D_
            @Override_x000D_
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {_x000D_
                holder.selectImage.setChecked(isChecked);_x000D_
                imageList.get(position).setSelected(isChecked);_x000D_
            }_x000D_
        });_x000D_
        holder.image.setOnClickListener(new View.OnClickListener() {_x000D_
            @Override_x000D_
            public void onClick(View v) {_x000D_
                if (imageList.get(position).isSelected())_x000D_
                {_x000D_
                    imageList.get(position).setSelected(false);_x000D_
                    holder.selectImage.setChecked(false);_x000D_
                }else_x000D_
                {_x000D_
                    imageList.get(position).setSelected(true);_x000D_
                    holder.selectImage.setChecked(true);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public int getItemCount() {_x000D_
        return imageList.size();_x000D_
    }_x000D_
_x000D_
    public class ViewHolder extends RecyclerView.ViewHolder {_x000D_
        public ImageView image;public CheckBox selectImage;_x000D_
        public ViewHolder(View itemView) {_x000D_
            super(itemView);_x000D_
            image=(ImageView)itemView.findViewById(R.id.image);_x000D_
            selectImage=(CheckBox) itemView.findViewById(R.id.ch);_x000D_
_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

This problem is caused by URLSession has two dataTask methods

open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask
open func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask

The first one has URLRequest as parameter, and the second one has URL as parameter, so we need to specify which type to call, for example, I want to call the second method

let task = URLSession.shared.dataTask(with: url! as URL) {
    data, response, error in
    // Handler
}

How to populate a dropdownlist with json data in jquery?

var listItems= "";
var jsonData = jsonObj.d;
    for (var i = 0; i < jsonData.Table.length; i++){
      listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
    }
    $("#<%=DLState.ClientID%>").html(listItems);

Example

   <html>
    <head></head>
    <body>
      <select id="DLState">
      </select>
    </body>
    </html>

    /*javascript*/
    var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
                {"stateid" : "3","statename" : "Karnataka"},
                {"stateid" : "4","statename" : "Andaman and Nicobar"},
                 {"stateid" : "5","statename" : "Andhra Pradesh"},
                 {"stateid" : "6","statename" : "Arunachal Pradesh"}]}

    $(document).ready(function(){
      var listItems= "";
      for (var i = 0; i < jsonList.Table.length; i++){
        listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
      }
      $("#DLState").html(listItems);
    });    

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Are HTTPS headers encrypted?

The whole lot is encrypted - all the headers. That's why SSL on vhosts doesn't work too well - you need a dedicated IP address because the Host header is encrypted.

The Server Name Identification (SNI) standard means that the hostname may not be encrypted if you're using TLS. Also, whether you're using SNI or not, the TCP and IP headers are never encrypted. (If they were, your packets would not be routable.)

How do you read scanf until EOF in C?

Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:

if (scanf("%15s", word) == 1)
    printf("%s\n", word);

If you want to loop as long as you can read a word, use while:

while (scanf("%15s", word) == 1)
    printf("%s\n", word);

Also, as others have noted, you need to give the word array a size that is big enough for your scanf:

char word[16];

Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.

edit

Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

No converter found capable of converting from type to type

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;

public interface DeadlineTypeProjection {
    String getId();

    // can get code and or change name of getter below
    String getCode();

    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();
}

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class DeadlineType {
    String id;

    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

}

Entity class

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {

    @Id
    private String id;
    private String code;
}

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {

    List<ABDeadlineType> findAll();

    List<DeadlineType> findAllDtoBy();

    List<DeadlineTypeProjection> findAllProjectionBy();

}

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {

    private final ABDeadlineTypeRepository abDeadlineTypeRepository;

    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    }

    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {

        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {

        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {

        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);
    }
}

Hope that helps

Les

Browse files and subfolders in Python

I had a similar thing to work on, and this is how I did it.

import os

rootdir = os.getcwd()

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".html"):
            print (filepath)

Hope this helps.

Increasing the maximum post size

; Maximum allowed size for uploaded files.
upload_max_filesize = 40M

; Must be greater than or equal to upload_max_filesize
post_max_size = 40M

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x

From documentation -

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

From urllib2 documentation -

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.

So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .

There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .

There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).

Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)

You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x

C++ sorting and keeping track of indexes

Are the items in the vector unique? If so, copy the vector, sort one of the copies with STL Sort then you can find which index each item had in the original vector.

If the vector is supposed to handle duplicate items, I think youre better of implementing your own sort routine.

Eclipse - Failed to create the java virtual machine

Change the below parameter in the eclipse.ini (which is in the same directory as eclipse.exe) to match one of your current Java version. Note that I also changed the maximum memory allowed for the eclipse process (which is run in a JVM). If you having multiple Java versions installed this can be happen. The below trick word for me.

-Xmx512m
-Dosgi.requiredJavaVersion=1.6

I cahanged this to,

-Xmx1024m
-Dosgi.requiredJavaVersion=1.7

Then It worked...

Count number of 1's in binary representation

   countBits(x){
     y=0;
     while(x){   
       y += x &  1 ;
       x  = x >> 1 ;
     }
   }

thats it?

Simplest way to profile a PHP script

If subtracting microtimes gives you negative results, try using the function with the argument true (microtime(true)). With true, the function returns a float instead of a string (as it does if it is called without arguments).

Getting Checkbox Value in ASP.NET MVC 4

If you really want to use plain HTML (for whatever reason) and not the built-in HtmlHelper extensions, you can do it this way.

Instead of

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

try using

<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked" : "") />

Checkbox inputs in HTML work so that when they're checked, they send the value, and when they're not checked, they don't send anything at all (which will cause ASP.NET MVC to fallback to the default value of the field, false). Also, the value of the checkbox in HTML can be anything not just true/false, so if you really wanted, you can even use a checkbox for a string field in your model.

If you use the built-in Html.RenderCheckbox, it actually outputs two inputs: checkbox and a hidden field so that a false value is sent when the checkbox is unchecked (not just nothing). That may cause some unexpected situations, like this:

VB.NET Empty String Array

try this Dim Arraystr() as String ={}

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

MYSQL import data from csv using LOAD DATA INFILE

You can use LOAD DATA INFILE command to import csv file into table.

Check this link MySQL - LOAD DATA INFILE.

LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);

For MySQL 8.0 users:

Using the LOCAL keyword hold security risks and as of MySQL 8.0 the LOCAL capability is set to False by default. You might see the error:

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

You can overwrite it by following the instructions in the docs. Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.

How to split a delimited string in Ruby and convert it to an array?

For String Integer without space as String

arr = "12345"

arr.split('')

output: ["1","2","3","4","5"]

For String Integer with space as String

arr = "1 2 3 4 5"

arr.split(' ')

output: ["1","2","3","4","5"]

For String Integer without space as Integer

arr = "12345"

arr.split('').map(&:to_i)

output: [1,2,3,4,5]

For String

arr = "abc"

arr.split('')

output: ["a","b","c"]

Explanation:

  1. arr -> string which you're going to perform any action.
  2. split() -> is an method, which split the input and store it as array.
  3. '' or ' ' or ',' -> is an value, which is needed to be removed from given string.

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

Check for a substring in a string in Oracle without LIKE

Bear in mind that it is only worth using anything other than a full table scan to find these values if the number of blocks that contain a row that matches the predicate is significantly smaller than the total number of blocks in the table. That is why Oracle will often decline the use of an index in order to full scan when you use LIKE '%x%' where x is a very small string. For example if the optimizer believes that using an index would still require single-block reads on (say) 20% of the table blocks then a full table scan is probably a better option than an index scan.

Sometimes you know that your predicate is much more selective than the optimizer can estimate. In such a case you can look into supplying an optimizer hint to perform an index fast full scan on the relevant column (particularly if the index is a much smaller segment than the table).

SELECT /*+ index_ffs(users (users.last_name)) */
       * 
FROM   users
WHERE  last_name LIKE "%z%"

how to copy only the columns in a DataTable to another DataTable?

If you want to copy the DataTable to another DataTable of different Schema Structure then you can do this:

  • Firstly Clone the first DataType so that you can only get the structure.
  • Then alter the newly created structure as per your need and then copy the data to newly created DataTable .

So:

Dim dt1 As New DataTable
dt1 = dtExcelData.Clone()
dt1.Columns(17).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(26).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(30).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(35).DataType = System.Type.GetType("System.Decimal")
dt1.Columns(38).DataType = System.Type.GetType("System.Decimal")
dt1 = dtprevious.Copy()

Hence you get the same DataTable but revised structure

Laravel 5.2 not reading env file

Same thing happens when :port is in your local .env

again the double quotes does the trick

APP_URL="http://localhost:8000"

and then

php artisan config:clear

Make: how to continue after a command fails?

Try the -i flag (or --ignore-errors). The documentation seems to suggest a more robust way to achieve this, by the way:

To ignore errors in a command line, write a - at the beginning of the line's text (after the initial tab). The - is discarded before the command is passed to the shell for execution.

For example,

clean:
  -rm -f *.o

This causes rm to continue even if it is unable to remove a file.

All examples are with rm, but are applicable to any other command you need to ignore errors from (i.e. mkdir).

bower command not found

Alternatively, you can use npx which comes along with the npm > 5.6.

npx bower install

How to use RecyclerView inside NestedScrollView?

UPDATE 1

Since Android Support Library 23.2.0 there were added method setAutoMeasureEnabled(true) for LayoutManagers. It makes RecyclerView to wrap it's content and works like a charm.
http://android-developers.blogspot.ru/2016/02/android-support-library-232.html

So just add something like this:

    LayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setAutoMeasureEnabled(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setNestedScrollingEnabled(false);


UPDATE 2

Since 27.1.0 setAutoMeasureEnabled is deprecated, so you should provide custom implementation of LayoutManager with overridden method isAutoMeasureEnabled()

But after many cases of usage RecyclerView I strongly recommend not to use it in wrapping mode, cause this is not what it is intended for. Try to refactor whole your layout using normal single RecyclerView with several items' types. Or use approach with LinearLayout that I described below as last resort


Old answer (not recommended)

You can use RecyclerView inside NestedScrollView. First of all you should implement your own custom LinearLayoutManager, it makes your RecyclerView to wrap its content. For example:

public class WrappingLinearLayoutManager extends LinearLayoutManager
{

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

    private int[] mMeasuredDimension = new int[2];

    @Override
    public boolean canScrollVertically() {
        return false;
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
            int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);

        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            if (getOrientation() == HORIZONTAL) {
                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        heightSpec,
                        mMeasuredDimension);

                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                measureScrapChild(recycler, i,
                        widthSpec,
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        mMeasuredDimension);

                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
            int heightSpec, int[] measuredDimension) {

        View view = recycler.getViewForPosition(position);
        if (view.getVisibility() == View.GONE) {
            measuredDimension[0] = 0;
            measuredDimension[1] = 0;
            return;
        }
        // For adding Item Decor Insets to view
        super.measureChildWithMargins(view, 0, 0);
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(
                widthSpec,
                getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view),
                p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(
                heightSpec,
                getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view),
                p.height);
        view.measure(childWidthSpec, childHeightSpec);

        // Get decorated measurements
        measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
        measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
        recycler.recycleView(view);
    }
}

After that use this LayoutManager for your RecyclerView

recyclerView.setLayoutManager(new WrappingLinearLayoutManager(getContext()));

But you also should call those two methods:

recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);

Here setNestedScrollingEnabled(false) disable scrolling for RecyclerView, so it doesn't intercept scrolling event from NestedScrollView. And setHasFixedSize(false) determine that changes in adapter content can change the size of the RecyclerView

Important note: This solution is little buggy in some cases and has problems with perfomance, so if you have a lot of items in your RecyclerView I'd recommend to use custom LinearLayout-based implementation of list view, create analogue of Adapter for it and make it behave like ListView or RecyclerView

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

Android: Create a toggle button with image and no text

create toggle_selector.xml in res/drawable

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
  <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

How to convert int to float in python?

Other than John's answer, you could also make one of the variable float, and the result will yield float.

>>> 144 / 314.0
0.4585987261146497

socket.shutdown vs socket.close

Isn't this code above wrong?

The close call directly after the shutdown call might make the kernel discard all outgoing buffers anyway.

According to http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable one needs to wait between the shutdown and the close until read returns 0.

how to check if input field is empty

Try this

$.trim($("#spa").val()).length > 0

It will not treat any white space if any as a correct value

how to convert an RGB image to numpy array?

You can use newer OpenCV python interface (if I'm not mistaken it is available since OpenCV 2.2). It natively uses numpy arrays:

import cv2
im = cv2.imread("abc.tiff",mode='RGB')
print type(im)

result:

<type 'numpy.ndarray'>

Android ListView Text Color

I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.

Explode PHP string by new line

Have you tried using double quotes?

How do you test running time of VBA code?

Seconds with 2 decimal spaces:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer

seconds format

Milliseconds:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer

milliseconds format

Milliseconds with comma seperator:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer

Milliseconds with comma seperator

Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.

SyntaxError: unexpected EOF while parsing

Here is one of my mistakes that produced this exception: I had a try block without any except or finally blocks. This will not work:

try:
    lets_do_something_beneficial()

To fix this, add an except or finally block:

try:
    lets_do_something_beneficial()
finally:
    lets_go_to_sleep()

Using grep to search for a string that has a dot in it

grep -F -r '0.49' * treats 0.49 as a "fixed" string instead of a regular expression. This makes . lose its special meaning.

How to check variable type at runtime in Go language

It seems that Go have special form of switch dedicate to this (it is called type switch):

func (e *Easy)SetOption(option Option, param interface{}) {

    switch v := param.(type) { 
    default:
        fmt.Printf("unexpected type %T", v)
    case uint64:
        e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
    case string:
        e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
    } 
}

Uint8Array to string in Javascript

Try these functions,

var JsonToArray = function(json)
{
    var str = JSON.stringify(json, null, 0);
    var ret = new Uint8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        ret[i] = str.charCodeAt(i);
    }
    return ret
};

var binArrayToJson = function(binArray)
{
    var str = "";
    for (var i = 0; i < binArray.length; i++) {
        str += String.fromCharCode(parseInt(binArray[i]));
    }
    return JSON.parse(str)
}

source: https://gist.github.com/tomfa/706d10fed78c497731ac, kudos to Tomfa

Using CMake to generate Visual Studio C++ project files

CMake can generate really nice Visual Studio .projs/.slns, but there is always the problem with the need to modify the .cmake files rather than .proj/.sln. As it is now, we are dealing with it as follows:

  1. All source files go to /src and files visible in Visual Studio are just "links" to them defined in .filter.
  2. Programmer adds/deletes files remembering to work on the defined /src directory, not the default project's one.
  3. When he's done, he run a script that "refreshes" the respective .cmake files.
  4. He checks if the code can be built in the recreated environment.
  5. He commits the code.

At first we were a little afraid of how it will turn out, but the workflow works really well and with nice diff visible before each commit, everyone can easily see if his changes were correctly mapped in .cmake files.

One more important thing to know about is the lack of support (afaik) for "Solution Configurations" in CMake. As it stands, you have to generate two directories with projects/solutions - one for each build type (debug, release, etc.). There is no direct support for more sophisticated features - in other words: switching between configurations won't give you what you might expect.

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

How to save as a new file and keep working on the original one in Vim?

Thanks for the answers. Now I know that there are two ways of "SAVE AS" in Vim.

Assumed that I'm editing hello.txt.

  • :w world.txt will write hello.txt's content to the file world.txt while keeping hello.txt as the opened buffer in vim.
  • :sav world.txt will first write hello.txt's content to the file world.txt, then close buffer hello.txt, finally open world.txt as the current buffer.

Set encoding and fileencoding to utf-8 in Vim

set encoding=utf-8  " The encoding displayed.
set fileencoding=utf-8  " The encoding written to file.

You may as well set both in your ~/.vimrc if you always want to work with utf-8.

Convert blob URL to normal URL

another way to create a data url from blob url may be using canvas.

var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)

as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)

How can I set a proxy server for gem?

When setting http_proxy and https_proxy, you are also probably going to need no_proxy for URLs on the same side of the proxy. https://msdn.microsoft.com/en-us/library/hh272656(v=vs.120).aspx

Force browser to download image files on click

Using HTML5 you can add the attribute 'download' to your links.

<a href="/path/to/image.png" download>

Compliant browsers will then prompt to download the image with the same file name (in this example image.png).

If you specify a value for this attribute, then that will become the new filename:

<a href="/path/to/image.png" download="AwesomeImage.png">

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create <a href="https://i.imgur.com/IskAzqA.jpg" download> on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

python error: no module named pylab

You'll need to install numpy, scipy and matplotlib to get pylab. In ubuntu you can install them with this command:

sudo apt-get install python-numpy python-scipy python-matplotlib

If you installed python from source you will need to install these packages through pip. Note that you may have to install other dependencies to do this, as well as install numpy before the other two.

That said, I would recommend using the version of python in the repositories as I think it is up to date with the current version of python (2.7.3).

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Batch: Remove file extension

Without looping

I am using this if I simply want to strip the extension from a filename or variable (without listing any directories or existing files):

for %%f in ("%filename%") do set filename=%%~nf

If you want to strip the extension from a full path, use %%dpnf instead:

for %%f in ("%path%") do set path=%%~dpnf

Example:

(Use directly in the console)

@for %f in ("file name.dat") do @echo %~nf
@for %f in ("C:\Dir\file.dat") do @echo %~dpnf

OUTPUT:

file name
C:\Dir\file

Why is IoC / DI not common in Python?

It seens that people really dont get what Dependency injection and inversion of control means anymore.

The practice of using inversion of control is to have classes or function that depends of another classes or functions, but instead of creating the instances whithin the class of function code it is better to receive it as a parameter, so loose coupling can be archieved. That has many benefits as more testability and to archieve the liskov substitution principle.

You see, by working with interfaces and injections, your code gets more maintanable, since you can change the behavior easily, because you won't have to rewrite a single line of code (maybe a line or two on the DI configuration) of your class to change it's behavior, since the classes that implements the interface your class is waiting for can vary independently as long as they follow the interface. One of the best strategies to keep code decoupled and easy to maintain is to follow at least the single responsability, substitution and dependency inversion principles.

Whats a DI library good for if you can instantiate a object yourself inside a package and import it to inject it yourself? The chosen answer is right, since java has no procedural sections (code outside of classes), all that goes into boring configuration xml's, hence the need of a class to instantiate and inject dependencies on a lazy load fashion so you don't blow away your performance, while on python you just code the injections on the "procedural" (code outside classes) sections of your code

Trust Store vs Key Store - creating with keytool

keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.

Initializing C dynamic arrays

I think the more tedious way is the only way to do it. I tried the first one and it doesn't compile (After commenting the '...')

No many shortcuts in 'C' I guess.ac

Issue with virtualenv - cannot activate

  1. Open your project using VS code editor .
  2. Change the default shell in vs code terminal to git bash.

  3. now your project is open with bash console and right path, put "source venv\Scripts\activate" in Windows

How to POST using HTTPclient content type = application/x-www-form-urlencoded

The best solution for me is:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}

Using "&times" word in html changes to ×

&times; stands for × in html. Use &amp;times to get &times

What do 'real', 'user' and 'sys' mean in the output of time(1)?

To expand on the accepted answer, I just wanted to provide another reason why real ? user + sys.

Keep in mind that real represents actual elapsed time, while user and sys values represent CPU execution time. As a result, on a multicore system, the user and/or sys time (as well as their sum) can actually exceed the real time. For example, on a Java app I'm running for class I get this set of values:

real    1m47.363s
user    2m41.318s
sys     0m4.013s

How to get a JavaScript object's class?

For Javascript Classes in ES6 you can use object.constructor. In the example class below the getClass() method returns the ES6 class as you would expect:

var Cat = class {

    meow() {

        console.log("meow!");

    }

    getClass() {

        return this.constructor;

    }

}

var fluffy = new Cat();

...

var AlsoCat = fluffy.getClass();
var ruffles = new AlsoCat();

ruffles.meow();    // "meow!"

If you instantiate the class from the getClass method make sure you wrap it in brackets e.g. ruffles = new ( fluffy.getClass() )( args... );

How to set custom location for local installation of npm package?

After searching for this myself wanting several projects with shared dependencies to be DRYer, I’ve found:

  • Installing locally is the Node way for anything you want to use via require()
  • Installing globally is for binaries you want in your path, but is not intended for anything via require()
  • Using a prefix means you need to add appropriate bin and man paths to $PATH
  • npm link (info) lets you use a local install as a source for globals

? stick to the Node way and install locally

ref:

How to print an unsigned char in C?

This is because in this case the char type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u interprets the number as a large positive number:

212 = 0xD4

When it is sign-extended, FFs are pre-pended to your number, so it becomes

0xFFFFFFD4 = 4294967252

which is the number that gets printed.

Note that this behavior is specific to your implementation. According to C99 specification, all char types are promoted to (signed) int, because an int can represent all values of a char, signed or unsigned:

6.1.1.2: If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

This results in passing an int to a format specifier %u, which expects an unsigned int.

To avoid undefined behavior in your program, add explicit type casts as follows:

unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);


* In general, the standard leaves the signedness of char up to the implementation. See this question for more details.

String replacement in java, similar to a velocity template

Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.

  1. Create a map of all the objects that will be referenced in the template.
  2. Use a regular expression to find variable references in the template and replace them with their values (see step 3). The Matcher class will come in handy for find-and-replace.
  3. Split the variable name at the dot. user.name would become user and name. Look up user in your map to get the object and use reflection to obtain the value of name from the object. Assuming your objects have standard getters, you will look for a method getName and invoke it.

ReactJS - .JS vs .JSX

JSX isn't standard JavaScript, based to Airbnb style guide 'eslint' could consider this pattern

// filename: MyComponent.js
function MyComponent() {
  return <div />;
}

as a warning, if you named your file MyComponent.jsx it will pass , unless if you edit the eslint rule you can check the style guide here

Fatal error: [] operator not supported for strings

I agree with Jeremy Young's comment on Phils answer:

I have found that this can be a problem associated with migrating from php 5 to php 7. php 5 was more tolerant of amibiguity in whether a variable was an array or not than php 7 is. In most cases the solution is to declare the array explicitly, as explained in this answer.

I was just trouble shooting a Wordpress plugin after the migration of php5 to php7. Since the plugin code was relying on user input, and it was intrinsically used in the code either as string, or as array, I added the following code in to prevent a fatal error:

if(is_array($variable_either_string_or_array)){
    // if it's an array, declaration is allowed:
    $variable_either_string_or_array[]=$additionalInfoData[$i];
}else{
    // if it's not an array, declaration it as follows:
    $variable_either_string_or_array=$additionalInfoData[$i];
}

This was the only modification I needed to add to make the plugin php7-proof. Obviously not "best practices", I'd rather read and understand the full code.. but a quick fix was needed.

filter out multiple criteria using excel vba

Alternative using VBA's Filter function

As an innovative alternative to @schlebe 's recent answer, I tried to use the Filter function integrated in VBA, which allows to filter out a given search string setting the third argument to False. All "negative" search strings (e.g. A, B, C) are defined in an array. I read the criteria in column A to a datafield array and basicly execute a subsequent filtering (A - C) to filter these items out.

Code

Sub FilterOut()
Dim ws  As Worksheet
Dim rng As Range, i As Integer, n As Long, v As Variant
' 1) define strings to be filtered out in array
  Dim a()                    ' declare as array
  a = Array("A", "B", "C")   ' << filter out values
' 2) define your sheetname and range (e.g. criteria in column A)
  Set ws = ThisWorkbook.Worksheets("FilterOut")
  n = ws.Range("A" & ws.Rows.Count).End(xlUp).row
  Set rng = ws.Range("A2:A" & n)
' 3) hide complete range rows temporarily
  rng.EntireRow.Hidden = True
' 4) set range to a variant 2-dim datafield array
  v = rng
' 5) code array items by appending row numbers
  For i = 1 To UBound(v): v(i, 1) = v(i, 1) & "#" & i + 1: Next i
' 6) transform to 1-dim array and FILTER OUT the first search string, e.g. "A"
  v = Filter(Application.Transpose(Application.Index(v, 0, 1)), a(0), False, False)
' 7) filter out each subsequent search string, i.e. "B" and "C"
  For i = 1 To UBound(a): v = Filter(v, a(i), False, False): Next i
' 8) get coded row numbers via split function and unhide valid rows
  For i = LBound(v) To UBound(v)
      ws.Range("A" & Split(v(i) & "#", "#")(1)).EntireRow.Hidden = False
  Next i
End Sub

How to change Rails 3 server default port in develoment?

Combining two previous answers, for Rails 4.0.4 (and up, presumably), this suffices at the end of config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    def default_options
      super.merge({Port: 10524})
    end
  end
end

How can apply multiple background color to one div

You can create something like c using CSS multiple-backgrounds.

div {
    background: linear-gradient(red, red),
                linear-gradient(blue, blue),
                linear-gradient(green, green);
    background-size: 30% 50%,
                     30% 60%,
                     40% 80%;
    background-position: 0% top,
                         calc(30% * 100 / (100 - 30)) top,
                         calc(60% * 100 / (100 - 40)) top;
    background-repeat: no-repeat;
}

Note, you still have to use linear-gradients for background types, because CSS will not allow you to control the background-size of a single color layer. So here we just make a single-color gradient. Then you can control the size/position of each of those blocks of color independently. You also have to make sure they don't repeat, or they'll just expand and cover the whole image.

The trickiest part here is background-position. A background-position of 0% puts your element's left edge at the left. 100% puts its right edge at the right. 50% centers is middle.

For a fun bit of math to solve that, you can guess the transform is probably linear, and just solve two little slope-intercept equations.

// (at 0%, the div's left edge is 0% from the left)
0 = m * 0 + b
// (at 100%, the div's right edge is 100% - width% from the left)
100 = m * (100 - width) + b
b = 0, m = 100 / (100 - width)

so to position our 40% wide div 60% from the left, we put it at 60% * 100 / (100 - 40) (or use css-calc).

Android 5.0 - Add header/footer to a RecyclerView

I know I come late, but only recently I was able to implement such "addHeader" to the Adapter. In my FlexibleAdapter project you can call setHeader on a Sectionable item, then you call showAllHeaders. If you need only 1 header then the first item should have the header. If you delete this item, then the header is automatically linked to the next one.

Unfortunately footers are not covered (yet).

The FlexibleAdapter allows you to do much more than create headers/sections. You really should have a look: https://github.com/davideas/FlexibleAdapter.

Action Image MVC3 Razor

This extension method also works (to be placed in an public static class):

    public static MvcHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions)
    {
        var builder = new TagBuilder("img");
        builder.MergeAttribute("src", imageUrl);
        builder.MergeAttribute("alt", altText);
        var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
        return new MvcHtmlString( link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)) );
    }

How to cut first n and last n columns?

Cut can take several ranges in -f:

Columns up to 4 and from 7 onwards:

cut -f -4,7-

or for fields 1,2,5,6 and from 10 onwards:

cut -f 1,2,5,6,10-

etc

Problem with converting int to string in Linq to entities

With EF v4 you can use SqlFunctions.StringConvert. There is no overload for int so you need to cast to a double or a decimal. Your code ends up looking like this:

var items = from c in contacts
            select new ListItem
            {
                Value = SqlFunctions.StringConvert((double)c.ContactId).Trim(),
                Text = c.Name
            };

WebSockets vs. Server-Sent events/EventSource

Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

Internet Explorer 10 does not attempt to read conditional comments anymore. This means it will treat conditional comments just like any other browser would: as regular HTML comments, meant to be ignored entirely. Looking at the markup given in the question as an example, all browsers including IE10 will ignore the comment portions, highlighted gray, entirely. The HTML5 standard makes no mention of conditional comment syntax, and this is exactly why they have chosen to stop supporting it in IE10.

Note, however, that conditional compilation in JScript is still supported, as shown in the comments as well as the more recent answers. It's not going away in the final release either, unlike jQuery.browser. And of course, it goes without saying that user-agent sniffing remains as fragile as ever and should never be used under any circumstances.

If you really must target IE10, either use conditional compilation which may still see support in the near future, or — if you can help it — use a feature detection library such as Modernizr instead of (or in conjunction with) browser detection. Unless your use case requires noscript or accommodating IE10 on the server side, user-agent sniffing is going to be more of a headache than a viable option.

Sounds pretty cumbersome, but remember that as a modern browser that's highly conformant to today's Web standards1, assuming you've written interoperable code that is highly standards-compliant, you shouldn't have to set aside special code for IE10 unless absolutely necessary, i.e. it's supposed to resemble other browsers in terms of behavior and rendering.2 And it sounds far-fetched, given IE's history, but how many times have you expected Firefox or Chrome to behave the same way only to be met with dismay?

If you do have a legitimate reason to be targeting certain browsers, by all means sniff them out with the other tools given to you. I'm just saying that you're going to be much more hard-pressed to find such a reason today than what it used to be, and it's really just not something you can rely on.


1 Not only IE10, but IE9, and even IE8 which handles most of the mature CSS2.1 standard far better than Chrome, simply because IE8 was so focused on standards compliance (at which time CSS2.1 was already pretty stable with only minor differences from today's recommendation) while Chrome seems to be little more than a half-polished tech demo of cutting-edge pseudo-standards.

2 And I may be biased when I say this, but it sure as hell does. If your code works in other browsers but not IE, the odds that it's an issue with your own code rather than IE10 are far better compared to, say, 3 years ago, with previous versions of IE. Again, I may be biased, but let's be honest: aren't you too? Just look at your comments.

What are .iml files in Android Studio?

They are project files, that hold the module information and meta data.

Just add *.iml to .gitignore.

In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml files will be generated.

How to find a text inside SQL Server procedures / triggers?

This one i tried in SQL2008, which can search from all the db at one go.

Create table #temp1 
(ServerName varchar(64), dbname varchar(64)
,spName varchar(128),ObjectType varchar(32), SearchString varchar(64))

Declare @dbid smallint, @dbname varchar(64), @longstr varchar(5000)
Declare @searhString VARCHAR(250)

set  @searhString='firstweek'

declare db_cursor cursor for 
select dbid, [name] 
from master..sysdatabases
where [name] not in ('master', 'model', 'msdb', 'tempdb', 'northwind', 'pubs')



open db_cursor
fetch next from db_cursor into @dbid, @dbname

while (@@fetch_status = 0)
begin
    PRINT 'DB='+@dbname
    set @longstr = 'Use ' + @dbname + char(13) +        
        'insert into #temp1 ' + char(13) +  
        'SELECT @@ServerName,  ''' + @dbname + ''', Name 
        , case  when [Type]= ''P'' Then ''Procedure''
                when[Type]= ''V'' Then ''View''
                when [Type]=  ''TF'' Then ''Table-Valued Function'' 
                when [Type]=  ''FN'' Then ''Function'' 
                when [Type]=  ''TR'' Then ''Trigger'' 
                else [Type]/*''Others''*/
                end 
        , '''+ @searhString +''' FROM  [SYS].[SYSCOMMEnTS]
        JOIN  [SYS].objects ON ID = object_id
        WHERE TEXT LIKE ''%' + @searhString + '%'''

 exec (@longstr)
 fetch next from db_cursor into @dbid, @dbname
end

close db_cursor
deallocate db_cursor
select * from #temp1
Drop table #temp1

How to use CSS to surround a number with a circle?

Heres my way of doing it, using square method. upside is it works with different values, but you need 2 spans.

_x000D_
_x000D_
.circle {_x000D_
  display: inline-block;_x000D_
  border: 1px solid black;_x000D_
  border-radius: 50%;_x000D_
  position: relative;_x000D_
  padding: 5px;_x000D_
}_x000D_
.circle::after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  padding-bottom: 100%;_x000D_
  height: 0;_x000D_
  opacity: 0;_x000D_
}_x000D_
.num {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
}_x000D_
.width_holder {_x000D_
  display: block;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="circle">_x000D_
  <span class="width_holder">1</span>_x000D_
  <span class="num">1</span>_x000D_
</div>_x000D_
<div class="circle">_x000D_
  <span class="width_holder">11</span>_x000D_
  <span class="num">11</span>_x000D_
</div>_x000D_
<div class="circle">_x000D_
  <span class="width_holder">11111</span>_x000D_
  <span class="num">11111</span>_x000D_
</div>_x000D_
<div class="circle">_x000D_
  <span class="width_holder">11111111</span>_x000D_
  <span class="num">11111111</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sending images using Http Post

The loopj library can be used straight-forward for this purpose:

SyncHttpClient client = new SyncHttpClient();
RequestParams params = new RequestParams();
params.put("text", "some string");
params.put("image", new File(imagePath));

client.post("http://example.com", params, new TextHttpResponseHandler() {
  @Override
  public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
    // error handling
  }

  @Override
  public void onSuccess(int statusCode, Header[] headers, String responseString) {
    // success
  }
});

http://loopj.com/

String representation of an Enum

Very simple solution to this with .Net 4.0 and above. No other code is needed.

public enum MyStatus
{
    Active = 1,
    Archived = 2
}

To get the string about just use:

MyStatus.Active.ToString("f");

or

MyStatus.Archived.ToString("f");`

The value will be "Active" or "Archived".

To see the different string formats (the "f" from above) when calling Enum.ToString see this Enumeration Format Strings page

Eliminating NAs from a ggplot

You can use the function subset inside ggplot2. Try this

library(ggplot2)

data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example

ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) + 
geom_bar(stat="bin")

jQuery: Uncheck other checkbox on one checked

I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/

Error "library not found for" after putting application in AdMob

In my case there was a naming issue. My library was called ios-admob-mm-adapter.a, but Xcode expected, that the name should start with prefix lib. I've just renamed my lib to libios-admob-mm-adapter.a and fixed the issue.

I use Cocoapods, and it links libraries with Other linker flags option in build settings of my target. The flag looks like -l"ios-admob-mm-adapter"

Hope it helps someone else

How to frame two for loops in list comprehension python

The best way to remember this is that the order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently.

So, the equivalent list comprehension would be:

[entry for tag in tags for entry in entries if tag in entry]

In general, if-else statement comes before the first for loop, and if you have just an if statement, it will come at the end. For e.g, if you would like to add an empty list, if tag is not in entry, you would do it like this:

[entry if tag in entry else [] for tag in tags for entry in entries]

Spring JUnit: How to Mock autowired component in autowired component

Spring Boot 1.4 introduced testing annotation called @MockBean. So now mocking and spying on Spring beans is natively supported by Spring Boot.

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

HEAD and ORIG_HEAD in Git

From man 7 gitrevisions:

HEAD names the commit on which you based the changes in the working tree. FETCH_HEAD records the branch which you fetched from a remote repository with your last git fetch invocation. ORIG_HEAD is created by commands that move your HEAD in a drastic way, to record the position of the HEAD before their operation, so that you can easily change the tip of the branch back to the state before you ran them. MERGE_HEAD records the commit(s) which you are merging into your branch when you run git merge. CHERRY_PICK_HEAD records the commit which you are cherry-picking when you run git cherry-pick.

javac: file not found: first.java Usage: javac <options> <source files>

So I had the same problem because I wasn't in the right directory where my file was located. So when I ran javac Example.java (for me) it said it couldn't find it. But I needed to go to where my Example.java file was located. So I used the command cd and right after that the location of the file. That worked for me. Tell me if it helps! Thanks!

how to set the background color of the whole page in css

The body's size is dynamic, it is only as large as the size of its contents. In the css file you could use: * {background-color: black} // All elements now have a black background.

or

html {background-color: black} // The page now have a black background, all elements remain the same.

Which font is used in Visual Studio Code Editor and how to change fonts?

On my windows 8.1 machine default VS Code font is Consolas, but you can easily change the font in File->Preferences->User Preferences. setting.json file will be opened alongside with default settings file, from where you can take syntax and names for settings properties and set your own ones in settings.json.enter image description here

Find the last time table was updated

If you're talking about last time the table was updated in terms of its structured has changed (new column added, column changed etc.) - use this query:

SELECT name, [modify_date] FROM sys.tables

If you're talking about DML operations (insert, update, delete), then you either need to persist what that DMV gives you on a regular basis, or you need to create triggers on all tables to record that "last modified" date - or check out features like Change Data Capture in SQL Server 2008 and newer.

Efficiently updating database using SQLAlchemy ORM

There are several ways to UPDATE using sqlalchemy

1) for c in session.query(Stuff).all():
       c.foo += 1
   session.commit()

2) session.query().\
       update({"foo": (Stuff.foo + 1)})
   session.commit()

3) conn = engine.connect()
   stmt = Stuff.update().\
       values(Stuff.foo = (Stuff.foo + 1))
   conn.execute(stmt)

MySQL: How to allow remote connection to mysql

And for OS X people out there be aware that the bind-address parameter is typically set in the launchd plist and not in the my.ini file. So in my case, I removed <string>--bind-address=127.0.0.1</string> from /Library/LaunchDaemons/homebrew.mxcl.mariadb.plist.

jQuery: go to URL with target="_blank"

Detect if a target attribute was used and contains "_blank". For mobile devices that don't like "_blank", this is a reliable alternative.

    $('.someSelector').bind('touchend click', function() {

        var url = $('a', this).prop('href');
        var target = $('a', this).prop('target');

        if(url) {
            // # open in new window if "_blank" used
            if(target == '_blank') { 
                window.open(url, target);
            } else {
                window.location = url;
            }
        }           
    });

Including a groovy script in another groovy

Here's a complete example of including one script within another.
Just run the Testmain.groovy file
Explanatory comments included because I'm nice like that ;]

Testutils.groovy

// This is the 'include file'
// Testmain.groovy will load it as an implicit class
// Each method in here will become a method on the implicit class

def myUtilityMethod(String msg) {
    println "myUtilityMethod running with: ${msg}"
}

Testmain.groovy

// Run this file

// evaluate implicitly creates a class based on the filename specified
evaluate(new File("./Testutils.groovy"))
// Safer to use 'def' here as Groovy seems fussy about whether the filename (and therefore implicit class name) has a capital first letter
def tu = new Testutils()
tu.myUtilityMethod("hello world")

How to run composer from anywhere?

You can do a global installation (archived guide):

Since Composer works with the current working directory it is possible to install it in a system-wide way.

  1. Change into a directory in your path like cd /usr/local/bin
  2. Get Composer curl -sS https://getcomposer.org/installer | php
  3. Make the phar executable chmod a+x composer.phar
  4. Change into a project directory cd /path/to/my/project
  5. Use Composer as you normally would composer.phar install
  6. Optionally you can rename the composer.phar to composer to make it easier

Update: Sometimes you can't or don't want to download at /usr/local/bin (some have experienced user permissions issues or restricted access), in this case, you can try this

  1. Open terminal
  2. curl -sS http://getcomposer.org/installer | php -- --filename=composer
  3. chmod a+x composer
  4. sudo mv composer /usr/local/bin/composer

Update 2: For Windows 10 and PHP 7 I recommend this tutorial (archived). Personally, I installed Visual C++ Redistributable for Visual Studio 2017 x64 before PHP 7.3 VC15 x64 Non Thread Safe version (check which versions of both in the PHP for Windows page, side menu). Read carefully and maybe the enable-extensions section could differ (extension=curl instead of extension=php_curl.dll). Works like a charm, good luck!

How to call a method in MainActivity from another class?

You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Instance of AnotherClass for future use
    private AnotherClass anotherClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Create new instance of AnotherClass and
        // pass instance of MainActivity by "this"
        anotherClass = new AnotherClass(this);
    }

    // Method you want to call from another class
    public void startChronometer(){
        ...
    }
}

AnotherClass.java

public class AnotherClass {

    // Main class instance
    private MainActivity mainActivity;  

    // Constructor
    public AnotherClass(MainActivity activity) {

        // Save instance of main class for future use
        mainActivity = activity;  

        // Call method in MainActivity
        mainActivity.startChronometer();
    }
}

How do I create an iCal-type .ics file that can be downloaded by other users?

That will work just fine. You can export an entire calendar with File > Export…, or individual events by dragging them to the Finder.

iCalendar (.ics) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN: and end with END:. You'll mostly find VEVENT sections (each of which represents an event) and VTIMEZONE sections, each of which represents a time zone that's referenced from one or more events.

Counting repeated elements in an integer array

 public static void duplicatesInteger(int arr[]){
    Arrays.sort(arr);       
    int count=0;
    Set s=new HashSet();
    for(int i=0;i<=arr.length-1;i++){
        for(int j=i+1;j<=arr.length-1;j++){
            if(arr[i]==arr[j] && s.add(arr[i])){
                count=count+1;              
                                }
        }
        System.out.println(count);
    }
}

Why does the order in which libraries are linked sometimes cause errors in GCC?

Another alternative would be to specify the list of libraries twice:

gcc prog.o libA.a libB.a libA.a libB.a -o prog.x

Doing this, you don't have to bother with the right sequence since the reference will be resolved in the second block.

jQuery - Illegal invocation

Just for the record it can also happen if you try to use undeclared variable in data like

var layout = {};
$.ajax({
  ...
  data: {
    layout: laoyut // notice misspelled variable name
  },
  ...
});

How do I test if a variable does not equal either of two values?

May I suggest trying to use in else if statement in your if/else statement. And if you don't want to run any code that not under any conditions you want you can just leave the else out at the end of the statement. else if can also be used for any number of diversion paths that need things to be a certain condition for each.

if(condition 1){

} else if (condition 2) {

}else {

}

Create a dictionary with list comprehension

You can create a new dict for each pair and merge it with the previous dict:

reduce(lambda p, q: {**p, **{q[0]: q[1]}}, bla bla bla, {})

Obviously this approaches requires reduce from functools.

How do I add a newline to a windows-forms TextBox?

Try something like

"Line 1" & Environment.NewLine & "Line 2"

Environment variables for java installation

Under Linux: http://lowfatlinux.com/linux-environment-variables.html

And of course, you can retrieve them from Java using:

String variable = System.getProperty("mykey");

How to recursively list all the files in a directory in C#?

If you only need filenames and since I didn't really like most of the solutions here (feature-wise or readability-wise), how about this lazy one?

private void Foo()
{
  var files = GetAllFiles("pathToADirectory");
  foreach (string file in files)
  {
      // Use can use Path.GetFileName() or similar to extract just the filename if needed
      // You can break early and it won't still browse your whole disk since it's a lazy one
  }
}

/// <exception cref="T:System.IO.DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="T:System.IO.IOException"><paramref name="path" /> is a file name.-or-A network error has occurred.</exception>
/// <exception cref="T:System.IO.PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file names must be less than 260 characters.</exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path" /> is null.</exception>
/// <exception cref="T:System.ArgumentException"><paramref name="path" /> is a zero-length string, contains only white space, or contains one or more invalid characters as defined by <see cref="F:System.IO.Path.InvalidPathChars" />.</exception>
[NotNull]
public static IEnumerable<string> GetAllFiles([NotNull] string directory)
{
  foreach (string file in Directory.GetFiles(directory))
  {
    yield return file; // includes the path
  }

  foreach (string subDir in Directory.GetDirectories(directory))
  {
    foreach (string subFile in GetAllFiles(subDir))
    {
      yield return subFile;
    }
  }
}

Increasing Google Chrome's max-connections-per-server limit to more than 6

I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.

However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.

Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).

"use database_name" command in PostgreSQL

In pgAdmin you can also use

SET search_path TO your_db_name;

Attaching click to anchor tag in angular

I had to combine several of the answers to get a working solution.

This solution will:

  • Style the link with the appropriate 'a' styles.
  • Call the desired function.
  • Not navigate to http://mySite/#

    <a href="#" (click)="!!functionToCall()">Link</a>

How to install a specific version of a ruby gem?

for Ruby 1.9+ use colon.

gem install sinatra:1.4.4 prawn:0.13.0

Return list from async/await method

you can use the following

private async Task<List<string>> GetItems()
{
    return await Task.FromResult(new List<string> 
    { 
      "item1", "item2", "item3" 
    });
}

invalid conversion from 'const char*' to 'char*'

Well, data.str().c_str() yields a char const* but your function Printfunc() wants to have char*s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be

void Printfunc(int a, char const* loc, char const* stream)

The alternative might be to turn the char const* into a char* but fixing the declaration is preferable:

Printfunc(num, addr, const_cast<char*>(data.str().c_str()));

Gradle - Could not find or load main class

For Netbeans 11 users, this works for me:

apply plugin: 'java'
apply plugin: 'application'

// This comes out to package + '.' + mainClassName
mainClassName = 'com.hello.JavaApplication1'

Here generally is my tree:

C:\...\NETBEANSPROJECTS\JAVAAPPLICATION1
¦   build.gradle
+---src
¦   +---main
¦   ¦   +---java
¦   ¦       +---com
¦   ¦           +---hello
¦   ¦                   JavaApplication1.java
¦   ¦
¦   +---test
¦       +---java
+---test

Maven Unable to locate the Javac Compiler in:

None of the current answers helped me here. We were getting something like:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
    #.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar

This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib in the path. Our tools.jar is in $JAVA_HOME/lib/tools.jar not in $JAVA_HOME/../lib/tools.jar.

Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <fork>true</fork>  <!-- not sure if this is also needed -->
      <executable>${JAVA_HOME}/bin/javac</executable>
      <!--        ^^^^^^^^^^^^^^^^^^^^^^ -->
    </configuration>
  </plugin>

By pointing the executable to the right place this at least got past our compilation failures.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

Javascript close alert box

You actually can do this you can basically listen for this pop up to happen and then confirm true before it ever "pops up",

if(window.alert){
  return true
}

Simulate user input in bash script

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

How to make a input field readonly with JavaScript?

Here you have example how to set the readonly attribute:

_x000D_
_x000D_
<form action="demo_form.asp">_x000D_
  Country: <input type="text" name="country" value="Norway" readonly><br>_x000D_
  <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to select the comparison of two columns as one column in Oracle

I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Here's a project that combines the best parts (pros) of both redux-saga and redux-thunk: you can handle all side-effects on sagas while getting a promise by dispatching the corresponding action: https://github.com/diegohaz/redux-saga-thunk

class MyComponent extends React.Component {
  componentWillMount() {
    // `doSomething` dispatches an action which is handled by some saga
    this.props.doSomething().then((detail) => {
      console.log('Yaay!', detail)
    }).catch((error) => {
      console.log('Oops!', error)
    })
  }
}

Can you target an elements parent element using event.target?

I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.

Otherwise parentNode might be what you're looking for.

link to currentTarget
link to parentNode

Converting BitmapImage to Bitmap and vice versa

Here's an extension method for converting a Bitmap to BitmapImage.

    public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        using (var memory = new MemoryStream())
        {
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();

            return bitmapImage;
        }
    }

equals vs Arrays.equals in Java

Look inside the implementation of the two methods to understand them deeply:

array1.equals(array2);
/**
 * Indicates whether some other object is "equal to" this one.
 * <p>
 * The {@code equals} method implements an equivalence relation
 * on non-null object references:
 * <ul>
 * <li>It is <i>reflexive</i>: for any non-null reference value
 *     {@code x}, {@code x.equals(x)} should return
 *     {@code true}.
 * <li>It is <i>symmetric</i>: for any non-null reference values
 *     {@code x} and {@code y}, {@code x.equals(y)}
 *     should return {@code true} if and only if
 *     {@code y.equals(x)} returns {@code true}.
 * <li>It is <i>transitive</i>: for any non-null reference values
 *     {@code x}, {@code y}, and {@code z}, if
 *     {@code x.equals(y)} returns {@code true} and
 *     {@code y.equals(z)} returns {@code true}, then
 *     {@code x.equals(z)} should return {@code true}.
 * <li>It is <i>consistent</i>: for any non-null reference values
 *     {@code x} and {@code y}, multiple invocations of
 *     {@code x.equals(y)} consistently return {@code true}
 *     or consistently return {@code false}, provided no
 *     information used in {@code equals} comparisons on the
 *     objects is modified.
 * <li>For any non-null reference value {@code x},
 *     {@code x.equals(null)} should return {@code false}.
 * </ul>
 * <p>
 * The {@code equals} method for class {@code Object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * Note that it is generally necessary to override the {@code hashCode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashCode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @param   obj   the reference object with which to compare.
 * @return  {@code true} if this object is the same as the obj
 *          argument; {@code false} otherwise.
 * @see     #hashCode()
 * @see     java.util.HashMap
 */
public boolean equals(Object obj) {
    return (this == obj);
}

while:

Arrays.equals(array1, array2);
/**
 * Returns <tt>true</tt> if the two specified arrays of Objects are
 * <i>equal</i> to one another.  The two arrays are considered equal if
 * both arrays contain the same number of elements, and all corresponding
 * pairs of elements in the two arrays are equal.  Two objects <tt>e1</tt>
 * and <tt>e2</tt> are considered <i>equal</i> if <tt>(e1==null ? e2==null
 * : e1.equals(e2))</tt>.  In other words, the two arrays are equal if
 * they contain the same elements in the same order.  Also, two array
 * references are considered equal if both are <tt>null</tt>.<p>
 *
 * @param a one array to be tested for equality
 * @param a2 the other array to be tested for equality
 * @return <tt>true</tt> if the two arrays are equal
 */
public static boolean equals(Object[] a, Object[] a2) {
    if (a==a2)
        return true;
    if (a==null || a2==null)
        return false;

    int length = a.length;
    if (a2.length != length)
        return false;

    for (int i=0; i<length; i++) {
        Object o1 = a[i];
        Object o2 = a2[i];
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }

    return true;
}

Git: How to check if a local repo is up to date?

First use git remote update, to bring your remote refs up to date. Then you can do one of several things, such as:

  1. git status -uno will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same. Sample result:

On branch DEV

Your branch is behind 'origin/DEV' by 7 commits, and can be fast-forwarded.

(use "git pull" to update your local branch)

  1. git show-branch *master will show you the commits in all of the branches whose names end in 'master' (eg master and origin/master).

If you use -v with git remote update (git remote -v update) you can see which branches got updated, so you don't really need any further commands.

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?

How to show full column content in a Spark Dataframe?

PYSPARK

In the below code, df is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as False.

df.show(df.count(),False)

enter image description here


SCALA

In the below code, df is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as false.

df.show(df.count().toInt,false)

enter image description here

Search for all files in project containing the text 'querystring' in Eclipse

Yes, you can do this quite easily. Click on your project in the project explorer or Navigator, go to the Search menu at the top, click File..., input your search string, and make sure that 'Selected Resources' or 'Enclosing Projects' is selected, then hit search. The alternative way to open the window is with Ctrl-H. This may depend on your keyboard accelerator configuration.

More details: http://www.ehow.com/how_4742705_file-eclipse.html and http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html

alt text
(source: avajava.com)

Best way to include CSS? Why use @import?

There is not really much difference in adding a css stylesheet in the head versus using the import functionality. Using @import is generally used for chaining stylesheets so that one can be easily extended. It could be used to easily swap different color layouts for example in conjunction with some general css definitions. I would say the main advantage / purpose is extensibility.

I agree with xbonez comment as well in that portability and maintainability are added benefits.

How to solve ADB device unauthorized in Android ADB host device?

For me, the emulator could not have Google Play Services enabled. It could have Google APIs or be x86 or x64 but not google play store.

Stop Chrome Caching My JS Files

add Something like script.js?a=[random Number] with the Random number generated by PHP.

Have you tried expire=0, the pragma "no-cache" and "cache-control=NO-CACHE"? (I dunno what they say about Scripts).

In STL maps, is it better to use map::insert than []?

Here's another example, showing that operator[] overwrites the value for the key if it exists, but .insert does not overwrite the value if it exists.

void mapTest()
{
  map<int,float> m;


  for( int i = 0 ; i  <=  2 ; i++ )
  {
    pair<map<int,float>::iterator,bool> result = m.insert( make_pair( 5, (float)i ) ) ;

    if( result.second )
      printf( "%d=>value %f successfully inserted as brand new value\n", result.first->first, result.first->second ) ;
    else
      printf( "! The map already contained %d=>value %f, nothing changed\n", result.first->first, result.first->second ) ;
  }

  puts( "All map values:" ) ;
  for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
    printf( "%d=>%f\n", iter->first, iter->second ) ;

  /// now watch this.. 
  m[5]=900.f ; //using operator[] OVERWRITES map values
  puts( "All map values:" ) ;
  for( map<int,float>::iterator iter = m.begin() ; iter !=m.end() ; ++iter )
    printf( "%d=>%f\n", iter->first, iter->second ) ;

}

Cross field validation with Hibernate Validator (JSR 303)

With Hibernate Validator 4.1.0.Final I recommend using @ScriptAssert. Exceprt from its JavaDoc:

Script expressions can be written in any scripting or expression language, for which a JSR 223 ("Scripting for the JavaTM Platform") compatible engine can be found on the classpath.

Note: the evaluation is being performed by a scripting "engine" running in the Java VM, therefore on Java "server side", not on "client side" as stated in some comments.

Example:

@ScriptAssert(lang = "javascript", script = "_this.passVerify.equals(_this.pass)")
public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;
}

or with shorter alias and null-safe:

@ScriptAssert(lang = "javascript", alias = "_",
    script = "_.passVerify != null && _.passVerify.equals(_.pass)")
public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;
}

or with Java 7+ null-safe Objects.equals():

@ScriptAssert(lang = "javascript", script = "Objects.equals(_this.passVerify, _this.pass)")
public class MyBean {
  @Size(min=6, max=50)
  private String pass;

  private String passVerify;
}

Nevertheless, there is nothing wrong with a custom class level validator @Matches solution.

"Permission Denied" trying to run Python on Windows 10

This appears to be a limitation in git-bash. The recommendation to use winpty python.exe worked for me. See Python not working in the command line of git bash for additional information.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

JFrame Exit on close Java

If you don't have it, the JFrame will just be disposed. The frame will close, but the app will continue to run.

How can I put a ListView into a ScrollView without it collapsing?

You should never use listview inside scrollview. Instead you should use NestedScrollView as parent and RecyclerView inside that.... as it handles a lot of scrolling issues

How to set image width to be 100% and height to be auto in react native?

use aspectRatio property in style

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

  • On a node with a set width/height aspect ratio control the size of the unset dimension
  • On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset
  • On a node with a measure function aspect ratio works as though the measure function measures the flex basis
  • On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset
  • Aspect ratio takes min/max dimensions into account

docs: https://reactnative.dev/docs/layout-props#aspectratio

try like this:

import {Image, Dimensions} from 'react-native';

var width = Dimensions.get('window').width; 

<Image
    source={{
        uri: '<IMAGE_URI>'
    }}
    style={{
        width: width * .2,  //its same to '20%' of device width
        aspectRatio: 1, // <-- this
        resizeMode: 'contain', //optional
    }}
/>

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"