Programs & Examples On #Nokogiri

An HTML, XML, SAX and Reader parser for Ruby with the ability to search documents via XPath or CSS3 selectors… and much more

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Just my two sends here

I was facing this issue with datetimes so what I did is this:

const moment = require('moment-timezone')

const date = moment.tz('America/Bogota').format()

Then save date to db to be able to compare it from some query.


To install moment-timezone

npm i moment-timezone

python: how to identify if a variable is an array or a scalar

Previous answers assume that the array is a python standard list. As someone who uses numpy often, I'd recommend a very pythonic test of:

if hasattr(N, "__len__")

CSS Change List Item Background Color with Class

This is an issue of selector specificity. (The selector .selected is less specific than ul.nav li.)

To fix, use as much specificity in the overriding rule as in the original:

ul.nav li {
 background-color:blue;
}
ul.nav li.selected {
 background-color:red;
}

You might also consider nixing the ul, unless there will be other .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

That's a bit cleaner, less typing, and fewer bits.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

git fetch origin
git reset --hard origin/master
git pull

Explanation:

  • Fetch will download everything from another repository, in this case, the one marked as "origin".
  • Reset will discard changes and revert to the mentioned branch, "master" in repository "origin".
  • Pull will just get everything from a remote repository and integrate.

See documentation at http://git-scm.com/docs.

How to replace captured groups only?

A little improvement to Matthew's answer could be a lookahead instead of the last capturing group:

.replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!");

Or you could split on the decimal and join with your new id like this:

.split(/\d+/).join("!NEW_ID!");

Example/Benchmark here: https://codepen.io/jogai/full/oyNXBX

How to avoid the "divide by zero" error in SQL?

I wrote a function a while back to handle it for my stored procedures:

print 'Creating safeDivide Stored Proc ...'
go

if exists (select * from dbo.sysobjects where  name = 'safeDivide') drop function safeDivide;
go

create function dbo.safeDivide( @Numerator decimal(38,19), @divisor decimal(39,19))
   returns decimal(38,19)
begin
 -- **************************************************************************
 --  Procedure: safeDivide()
 --     Author: Ron Savage, Central, ex: 1282
 --       Date: 06/22/2004
 --
 --  Description:
 --  This function divides the first argument by the second argument after
 --  checking for NULL or 0 divisors to avoid "divide by zero" errors.
 -- Change History:
 --
 -- Date        Init. Description
 -- 05/14/2009  RS    Updated to handle really freaking big numbers, just in
 --                   case. :-)
 -- 05/14/2009  RS    Updated to handle negative divisors.
 -- **************************************************************************
   declare @p_product    decimal(38,19);

   select @p_product = null;

   if ( @divisor is not null and @divisor <> 0 and @Numerator is not null )
      select @p_product = @Numerator / @divisor;

   return(@p_product)
end
go

Python 3 print without parenthesis

The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:

SetTitleMatchMode,2         ;;; allows for a partial search 
#IfWinActive, .py           ;;; scope limiter to only python files
:b*:print ::print(){Left}   ;;; I forget what b* does
#IfWinActive                ;;; remove the scope limitation

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

PostgreSQL Forging Key DELETE, UPDATE CASCADE

CREATE TABLE apps_user(
  user_id SERIAL PRIMARY KEY,
  username character varying(30),
  userpass character varying(50),
  created_on DATE
);

CREATE TABLE apps_profile(
    pro_id SERIAL PRIMARY KEY,
    user_id INT4 REFERENCES apps_user(user_id) ON DELETE CASCADE ON UPDATE CASCADE,
    firstname VARCHAR(30),
    lastname VARCHAR(50),
    email VARCHAR UNIQUE,
    dob DATE
);

Getting a list of files in a directory with a glob

You need to roll your own method to eliminate the files you don't want.

This isn't easy with the built in tools, but you could use RegExKit Lite to assist with finding the elements in the returned array you are interested in. According to the release notes this should work in both Cocoa and Cocoa-Touch applications.

Here's the demo code I wrote up in about 10 minutes. I changed the < and > to " because they weren't showing up inside the pre block, but it still works with the quotes. Maybe somebody who knows more about formatting code here on StackOverflow will correct this (Chris?).

This is a "Foundation Tool" Command Line Utility template project. If I get my git daemon up and running on my home server I'll edit this post to add the URL for the project.

#import "Foundation/Foundation.h"
#import "RegexKit/RegexKit.h"

@interface MTFileMatcher : NSObject 
{
}
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
@end

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    MTFileMatcher* matcher = [[[MTFileMatcher alloc] init] autorelease];
    [matcher getFilesMatchingRegEx:@"^.+\\.[Jj][Pp][Ee]?[Gg]$" forPath:[@"~/Pictures" stringByExpandingTildeInPath]];

    [pool drain];
    return 0;
}

@implementation MTFileMatcher
- (void)getFilesMatchingRegEx:(NSString*)inRegex forPath:(NSString*)inPath;
{
    NSArray* filesAtPath = [[[NSFileManager defaultManager] directoryContentsAtPath:inPath] arrayByMatchingObjectsWithRegex:inRegex];
    NSEnumerator* itr = [filesAtPath objectEnumerator];
    NSString* obj;
    while (obj = [itr nextObject])
    {
        NSLog(obj);
    }
}
@end

Remove old Fragment from fragment manager

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

That is it.

Drawing a dot on HTML5 canvas

If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing.

var canvas = document.getElementById("myCanvas");
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext("2d");
var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);

// That's how you define the value of a pixel //
function drawPixel (x, y, r, g, b, a) {
    var index = (x + y * canvasWidth) * 4;

    canvasData.data[index + 0] = r;
    canvasData.data[index + 1] = g;
    canvasData.data[index + 2] = b;
    canvasData.data[index + 3] = a;
}

// That's how you update the canvas, so that your //
// modification are taken in consideration //
function updateCanvas() {
    ctx.putImageData(canvasData, 0, 0);
}

Then, you can use it in this way :

drawPixel(1, 1, 255, 0, 0, 255);
drawPixel(1, 2, 255, 0, 0, 255);
drawPixel(1, 3, 255, 0, 0, 255);
updateCanvas();

For more information, you can take a look at this Mozilla blog post : http://hacks.mozilla.org/2009/06/pushing-pixels-with-canvas/

How to inflate one view with a layout

layout inflation

View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);

How to create an object property from a variable value in JavaScript?

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.

Example #1:

(function(o,a,b){return o[a]=b,o})({},'key','val');

Example: #2:

var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');

As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).

Result #1: { key: 'val' }

Result #2: { foo: 'bar', key: 'val' }

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Here's another path you can use. I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE.

C:\Python25\Lib\idlelib\idle.pyw

java.lang.IllegalArgumentException: View not attached to window manager

I too get this error sometimes when I dismiss dialog and finish activity from onPostExecute method. I guess sometimes activity gets finished before dialog successfully dismisses.

Simple, yet effective solution that works for me

@Override
protected void onPostExecute(MyResult result) {
    try {
        if ((this.mDialog != null) && this.mDialog.isShowing()) {
            this.mDialog.dismiss();
        }
    } catch (final IllegalArgumentException e) {
        // Handle or log or ignore
    } catch (final Exception e) {
        // Handle or log or ignore
    } finally {
        this.mDialog = null;
    }  
}

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

Finding the source code for built-in Python functions?

Since Python is open source you can read the source code.

To find out what file a particular module or function is implemented in you can usually print the __file__ attribute. Alternatively, you may use the inspect module, see the section Retrieving Source Code in the documentation of inspect.

For built-in classes and methods this is not so straightforward since inspect.getfile and inspect.getsource will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list type.

What is the reason behind "non-static method cannot be referenced from a static context"?

I think it is worth pointing out that by the rules of the Java language the Java compiler inserts the equivalent of "this." when it notices that you're accessing instance methods or instance fields without an explicit instance. Of course, the compiler knows that it can only do this from within an instance method, which has a "this" variable, as static methods don't.

Which means that when you're in an instance method the following are equivalent:

instanceMethod();
this.instanceMethod();

and these are also equivalent:

... = instanceField;
... = this.instanceField;

The compiler is effectively inserting the "this." when you don't supply a specific instance.

This (pun intended) bit of "magic help" by the compiler can confuse novices: it means that instance calls and static calls sometimes appear to have the same syntax while in reality are calls of different types and underlying mechanisms.

The instance method call is sometimes referred to as a method invocation or dispatch because of the behaviors of virtual methods supporting polymorphism; dispatching behavior happens regardless of whether you wrote an explicit object instance to use or the compiler inserted a "this.".

The static method call mechanism is simpler, like a function call in a non-OOP language.

Personally, I think the error message is misleading, it could read "non-static method cannot be referenced from a static context without specifying an explicit object instance".


What the compiler is complaining about is that it cannot simply insert the standard "this." as it does within instance methods, because this code is within a static method; however, maybe the author merely forgot to supply the instance of interest for this invocation — say, an instance possibly supplied to the static method as parameter, or created within this static method.

In short, you most certainly can call instance methods from within a static method, you just need to have and specify an explicit instance object for the invocation.

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

Remove HTML tags from a String

Alternatively, one can use HtmlCleaner:

private CharSequence removeHtmlFrom(String html) {
    return new HtmlCleaner().clean(html).getText();
}

curl -GET and -X GET

By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com it will use GET. If you use -d or -F curl will use POST, -I will cause a HEAD and -T will make it a PUT.

If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]. This way you can for example send a DELETE by doing curl -X DELETE [URL].

It is thus pointless to do curl -X GET [URL] as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]... But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL].

Digging deeper

curl -GET (using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G, -E and -T options and that will do something completely different.

There's also a curl option called --get to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d into a GET request instead of a POST.

(I subsequently used my own answer here to populate the curl FAQ to cover this.)

Warnings

Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v) - to make users aware. Further explained and motivated in this blog post.

-G converts a POST + body to a GET + query

You can ask curl to convert a set of -d options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:

curl -d name=daniel -d grumpy=yes -G https://example.com/

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

How can I run a PHP script in the background after a form is submitted?

In my case I have 3 params, one of them is string (mensaje):

exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");

In my Process.php I have this code:

if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{   
    die("Error.");
} 

$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];

What exactly does the .join() method do?

join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring() + strid

Add padding on view programmatically

use below method for setting padding dynamically

setPadding(int left, int top, int right, int bottom)

Example :

view.setPadding(2,2,2,2);

How do you run `apt-get` in a dockerfile behind a proxy?

If you have the proxies set up correctly, and still cannot reach the internet, it could be the DNS resolution. Check /etc/resolve.conf on the host Ubuntu VM. If it contains nameserver 127.0.1.1, that is wrong.

Run these commands on the host Ubuntu VM to fix it:

sudo vi /etc/NetworkManager/NetworkManager.conf
# Comment out the line `dns=dnsmasq` with a `#`

# restart the network manager service
sudo systemctl restart network-manager

cat /etc/resolv.conf

Now /etc/resolv.conf should have a valid value for nameserver, which will be copied by the docker containers.

Clear screen in shell

I am using a class that just uses one of the above methods behind the scenes... I noticed it works on Windows and Linux... I like using it though because it's easier to type clear() instead of system('clear') or os.system('clear')

pip3 install clear-screen

from clear_screen import clear

and then when you want to clear the shell:

clear()

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Getting checkbox values on submit

Perhaps a better way is using the php function in_array() like this:

$style='V';//can be 'V'ertical or 'H'orizontal
$lineBreak=($style=='V')?'<br>':'';
$name='colors';//the name of your options
$Legent="Select your $name";//dress it up in a nice fieldset with a ledgent
$options=array('red','green','blue','orange','yellow','white','black');
$boxes='';//innitiate the list of tickboxes to be generated
if(isset($_REQUEST["$name"])){ 
//we shall use $_REQUEST but $_POST would be better
   $Checked=$_REQUEST["$name"];
}else{
   $Checked=array();
}
foreach($options as $option){
$checkmark=(in_array($option,$Checked))?'checked':'';
$nameAsArray=$name.'[]';//we would like the returned data to be in an array so we end with []
$boxes.=($style=='V')?"<span class='label2' align='right'><b>$option : </b></span>":"<b>$option </b>";
$boxes.="<input style='width:2em;' type='checkbox' name='$nameAsArray' id='$option' value='$option' $checkmark >$lineBreak";
}

echo<<<EOF
<html>
<head></head>
<body>
<form name="Update" method="GET" action="{$_SERVER['PHP_SELF']}">\n
<fieldset id="tickboxes" style="width:25em;">
<legend>{$Legent}</legend>
{$boxes}
</fieldset>
<button type="submit" >Submit Form</button>
</form>
<body>
</html>
EOF
;

To start with we have created a variable $style to set if we want the options in a horizontal or vertical way. This will infrequence how we display our checkboxes. Next we set the $name for our options, this is needed as a name of the array where we want to keep our options. I have created a loop here to construct each option as given in the array $options, then we check each item if it should be checked in our returned form. I believe this should simplify the way we can reproduce a form with checkboxes.

How to discard all changes made to a branch?

git checkout -f

This is suffice for your question. Only thing is, once its done, its done. There is no undo.

Windows batch: echo without new line

I made a function out of @arnep 's idea:

echo|set /p="Hello World"

here it is:

:SL (sameline)
echo|set /p=%1
exit /b

Use it with call :SL "Hello There"
I know this is nothing special but it took me so long to think of it I figured I'd post it here.

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

Import a custom class in Java

I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.

What are MVP and MVC and what is the difference?

There are many versions of MVC, this answer is about the original MVC in Smalltalk. In brief, it is image of mvc vs mvp

This talk droidcon NYC 2017 - Clean app design with Architecture Components clarifies it

enter image description here enter image description here

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

Angular 1 - get current URL parameters

To get parameters from URL with ngRoute . It means that you will need to include angular-route.js in your application as a dependency. More information how to do this on official ngRoute documentation.

The solution for the question:

// You need to add 'ngRoute' as a dependency in your app
angular.module('ngApp', ['ngRoute'])
    .config(function ($routeProvider, $locationProvider) {
        // configure the routing rules here
        $routeProvider.when('/backend/:type/:id', {
            controller: 'PagesCtrl'
        });

        // enable HTML5mode to disable hashbang urls
        $locationProvider.html5Mode(true);
    })
    .controller('PagesCtrl', function ($routeParams) {
        console.log($routeParams.id, $routeParams.type);
    });

If you don't enable the $locationProvider.html5Mode(true);. Urls will use hashbang(/#/).

More information about routing can be found on official angular $route API documentation.


Side note: This question is answering how to achieve this using ng-Route however I would recommend using the ui-Router for routing. It is more flexible, offers more functionality, the documentations is great and it is considered the best routing library for angular.

Error: allowDefinition='MachineToApplication' beyond application level

If you have MVC project with enabled views build, one of the solution is to delete obj folder before build. Add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

Here is article: How to remove bin and/or obj folder before the build or deploy

AttributeError: 'str' object has no attribute 'append'

What you are trying to do is add additional information to each item in the list that you already created so

    alist[ 'from form', 'stuff 2', 'stuff 3']

    for j in range( 0,len[alist]):
        temp= []
        temp.append(alist[j]) # alist[0] is 'from form' 
        temp.append('t') # slot for first piece of data 't'
        temp.append('-') # slot for second piece of data

    blist.append(temp)      # will be alist with 2 additional fields for extra stuff assocated with each item in alist  

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For anyone wondering about the difference between -1.#IND00 and -1.#IND (which the question specifically asked, and none of the answers address):

-1.#IND00

This specifically means a non-zero number divided by zero, e.g. 3.14 / 0 (source)

-1.#IND (a synonym for NaN)

This means one of four things (see wiki from source):

1) sqrt or log of a negative number

2) operations where both variables are 0 or infinity, e.g. 0 / 0

3) operations where at least one variable is already NaN, e.g. NaN * 5

4) out of range trig, e.g. arcsin(2)

SQL QUERY replace NULL value in a row with a value from the previous known value

If you're looking for a solution for Redshift, this will work with the frame clause:

SELECT date, 
       last_value(columnName ignore nulls) 
                   over (order by date
                         rows between unbounded preceding and current row) as columnName 
 from tbl

excel VBA run macro automatically whenever a cell is changed

In an attempt to find a way to make the target cell for the intersect method a name table array, I stumbled across a simple way to run something when ANY cell or set of cells on a particular sheet changes. This code is placed in the worksheet module as well:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 0 Then
'mycode here
end if
end sub

Installing Pandas on Mac OSX

Write down this and try to import pandas again!

import sys
!{sys.executable} -m pip install pandas

It worked for me, hope will work for you too.

How do I display local image in markdown?

Adding a local image worked for me by like so: ![alt text](file://IMG_20181123_115829.jpg)

Without the file:// prefix it did not work (Win10, Notepad++ with MarkdownViewer++ addon)

Edit: I found out it also works with html tags, and that is way better: <img src="file://IMG_20181123_115829.jpg" alt="alt text" width="200"/>

Edit2: In Atom editor it only works without the file:// prefix. What a mess.

How to squash commits in git after they have been pushed?

For squashing two commits, one of which was already pushed, on a single branch the following worked:

git rebase -i HEAD~2
    [ pick     older-commit  ]
    [ squash   newest-commit ]
git push --force

By default, this will include the commit message of the newest commit as a comment on the older commit.

How do I zip two arrays in JavaScript?

Zip Arrays of same length:

Using Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
_x000D_
_x000D_

Zip Arrays of different length:

Using Array.from()

_x000D_
_x000D_
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
_x000D_
_x000D_

Using Array.prototype.fill() and Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
_x000D_
_x000D_

Compare string with all values in list

In Python you may use the in operator. You can do stuff like this:

>>> "c" in "abc"
True

Taking this further, you can check for complex structures, like tuples:

>>> (2, 4, 8) in ((1, 2, 3), (2, 4, 8))
True

How to convert int to float in C?

You are doing integer arithmetic, so there the result is correct. Try

percentage=((double)number/total)*100;

BTW the %f expects a double not a float. By pure luck that is converted here, so it works out well. But generally you'd mostly use double as floating point type in C nowadays.

How can I get LINQ to return the object which has the max value for a given property?

Or you can write your own extension method:

static partial class Extensions
{
    public static T WhereMax<T, U>(this IEnumerable<T> items, Func<T, U> selector)
    {
        if (!items.Any())
        {
            throw new InvalidOperationException("Empty input sequence");
        }

        var comparer = Comparer<U>.Default;
        T   maxItem  = items.First();
        U   maxValue = selector(maxItem);

        foreach (T item in items.Skip(1))
        {
            // Get the value of the item and compare it to the current max.
            U value = selector(item);
            if (comparer.Compare(value, maxValue) > 0)
            {
                maxValue = value;
                maxItem  = item;
            }
        }

        return maxItem;
    }
}

Best data type for storing currency values in a MySQL database

Something like Decimal(19,4) usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money" as it's non-standard.

What are all the uses of an underscore in Scala?

Besides the usages that JAiro mentioned, I like this one:

def getConnectionProps = {
    ( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}

If someone needs all connection properties, he can do:

val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps

If you need just a host and a port, you can do:

val ( host, port, _, _ ) = getConnectionProps

Facebook how to check if user has liked page and show content?

With Javascript SDK, you can change the code as below, this should be added after FB.init call.

     // Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
        // the user is logged in and has authenticated your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token 
        // and signed request each expire
        var uid = response.authResponse.userID;
        var accessToken = response.authResponse.accessToken;
        alert('we are fine');
      } else if (response.status === 'not_authorized') {
        // the user is logged in to Facebook, 
        // but has not authenticated your app
        alert('please like us');
         $("#container_notlike").show();
      } else {
        // the user isn't logged in to Facebook.
        alert('please login');
      }
     });

FB.Event.subscribe('edge.create',
function(response) {
    alert('You liked the URL: ' + response);
      $("#container_like").show();
}

How do I make a transparent border with CSS?

Use transparent property

border-color : transparent;

RecyclerView onClick

Usually you have more than one element in your CardView, so that you need an layout view to wrap and organize them.
You can add an OnClickListener to that layout view.
1. Add an id to your layout. In this case a LinearLayout

<android.support.v7.widget.CardView
 .....>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/card_view_linearLayout">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="name"
            android:id="@+id/card_view_name" />

        ...

    </LinearLayout>

</android.support.v7.widget.CardView>

$ 2. Get the layout view in your inner ViewHolder class.

public static class ViewHolder extends RecyclerView.ViewHolder{
    private TextView nameView;
    ...
    private LinearLayout linearLayout;
    public ViewHolder(View itemView) {
        super(itemView);
        nameView = (TextView)itemView.findViewById(R.id.card_view_name);
        ...
        linearLayout = (LinearLayout)itemView.findViewById(R.id.card_view_linearLayout);
    }
}

$ 3. Add the listener to your layout in onBindViewHolder and use a callback to send data to the Activity or Fragment(not tested).

@Override
public void onBindViewHolder(TrackAdapter.ViewHolder holder, final int position) {
    String str = mStringList.get(position);

    holder.nameView.setText(str);
    ...
    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            callback.itemCallback(mStringList.get(position));
        }
    });
}

how to use callbacks is another story

Trigger change() event when setting <select>'s value with val() function

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

Creating a list of dictionaries results in a list of copies of the same dictionary

If you want one line:

list_of_dict = [{} for i in range(list_len)]

How to open a new tab using Selenium WebDriver

This line of code will open a new browser tab using Selenium WebDriver:

((JavascriptExecutor)getDriver()).executeScript("window.open()");

Storing SHA1 hash values in MySQL

Output size of sha1 is 160 bits. Which is 160/8 == 20 chars (if you use 8-bit chars) or 160/16 = 10 (if you use 16-bit chars).

Logical XOR operator in C++?

For a true logical XOR operation, this will work:

if(!A != !B) {
    // code here
}

Note the ! are there to convert the values to booleans and negate them, so that two unequal positive integers (each a true) would evaluate to false.

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

SSIS Connection Manager Not Storing SQL Password

Check the text contents of the connection manager file itself, the password field might be configured in the Project.params file, in which case entering the password into the connection manager window will cause it to not save.

White space at top of page

Aside from the css reset, I also added the following to the css of my div container and that fixed it.

position: relative;
top: -22px; 

A simple algorithm for polygon intersection

You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.

One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton

Alan Murta has a complete implementation of a polygon clipper GPC.

Edit:

Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.

How to find a value in an array of objects in JavaScript?

If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:

Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }

You can now easily access it like this: Object['sushi']['name']

Or if the object really is this simple (just 'name' in the object), you could just change it to:

Obj = { 'pizza' : 'bob', 'sushi' : 'john' }

And then access it like: Object['sushi'].

It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.

How do you change Background for a Button MouseOver in WPF?

All of the answers so far involve completely replacing the default button behavior with something else. However, IMHO it is useful and important to understand that it's possible to change just the part you care about, by editing the existing, default template for a XAML element.

In the case of dealing with the hover effect on a WPF button, the change in appearance in a WPF Button element is caused by a Trigger in the default style for the Button, which is based on the IsMouseOver property and sets the Background and BorderBrush properties of the top-level Border element in the control template. The Button element's background is underneath the Border element's background, so changing the Button.Background property doesn't prevent the hover effect from being seen.

With some effort, you could override this behavior with your own setter, but because the element you need to affect is in the template and not directly accessible in your own XAML, that approach would be difficult and IMHO overly complex.

Another option would be to make use the graphic as the Content for the Button rather than the Background. If you need additional content over the graphic, you can combine them with a Grid as the top-level object in the content.

However, if you literally just want to disable the hover effect entirely (rather than just hiding it), you can use the Visual Studio XAML Designer:

  1. While editing your XAML, select the "Design" tab.
  2. In the "Design" tab, find the button for which you want to disable the effect.
  3. Right-click that button, and choose "Edit Template/Edit a Copy...". Select in the prompt you get where you want the new template resource to be placed. This will appear to do nothing, but in fact the Designer will have added new resources where you told it, and changed your button element to reference the style that uses those resources as the button template.
  4. Now, you can go edit that style. The easiest thing is to delete or comment-out (e.g. Ctrl+E, C) the <Trigger Property="IsMouseOver" Value="true">...</Trigger> element. Of course, you can make any change to the template you want at that point.

When you're done, the button style will look something like this:

<p:Style x:Key="FocusVisual">
  <Setter Property="Control.Template">
    <Setter.Value>
      <ControlTemplate>
        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</p:Style>
<SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
<SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
<SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
<SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
<SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
<SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
<p:Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
  <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
  <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
  <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
  <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
  <Setter Property="BorderThickness" Value="1"/>
  <Setter Property="HorizontalContentAlignment" Value="Center"/>
  <Setter Property="VerticalContentAlignment" Value="Center"/>
  <Setter Property="Padding" Value="1"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type Button}">
        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
          <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsDefaulted" Value="true">
            <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
          </Trigger>
          <!--<Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
          </Trigger>-->
          <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</p:Style>

(Note: you can omit the p: XML namespace qualifications in the actual code…I provide them here only because the Stack Overflow XML code formatter gets confused by <Style/> elements that don't have a fully-qualified name with XML namespace.)

If you want to apply the same style to other buttons, you can just right-click them and choose "Edit Template/Apply Resource" and select the style you just added for the first button. You can even make that style the default style for all buttons, using the normal techniques for applying a default style to elements in XAML.

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition: Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

How to add class active on specific li on user click with jQuery

You specified both jQuery and Javascript in the tags so here's both approaches.

jQuery

var selector = '.nav li';

$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

Fiddle: http://jsfiddle.net/bvf9u/


Pure Javascript:

var selector, elems, makeActive;

selector = '.nav li';

elems = document.querySelectorAll(selector);

makeActive = function () {
    for (var i = 0; i < elems.length; i++)
        elems[i].classList.remove('active');

    this.classList.add('active');
};

for (var i = 0; i < elems.length; i++)
    elems[i].addEventListener('mousedown', makeActive);

Fiddle: http://jsfiddle.net/rn3nc/1


jQuery with event delegation:

Please note that in approach 1, the handler is directly bound to that element. If you're expecting the DOM to update and new lis to be injected, it's better to use event delegation and delegate to the next element that will remain static, in this case the .nav:

$('.nav').on('click', 'li', function(){
    $('.nav li').removeClass('active');
    $(this).addClass('active');
});

Fiddle: http://jsfiddle.net/bvf9u/1/

The subtle difference is that the handler is bound to the .nav now, so when you click the li the event bubbles up the DOM to the .nav which invokes the handler if the element clicked matches your selector argument. This means new elements won't need a new handler bound to them, because it's already bound to an ancestor.

It's really quite interesting. Read more about it here: http://api.jquery.com/on/

Stretch horizontal ul to fit width of div

People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Inserting code in this LaTeX document with indentation

Use Minted.

It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.

It's much more evolved and customizable than any other package!

Error: Could not find or load main class

Check your BuildPath, it could be that you are referencing a library that does not exist anymore.

High-precision clock in Python

Here is a python 3 solution for Windows building upon the answer posted above by CyberSnoopy (using GetSystemTimePreciseAsFileTime). We borrow some code from jfs

Python datetime.utcnow() returning incorrect datetime

and get a precise timestamp (Unix time) in microseconds

#! python3
import ctypes.wintypes

def utcnow_microseconds():
    system_time = ctypes.wintypes.FILETIME()
    #system call used by time.time()
    #ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(system_time))
    #getting high precision:
    ctypes.windll.kernel32.GetSystemTimePreciseAsFileTime(ctypes.byref(system_time))
    large = (system_time.dwHighDateTime << 32) + system_time.dwLowDateTime
    return large // 10 - 11644473600000000

for ii in range(5):
    print(utcnow_microseconds()*1e-6)

References
https://docs.microsoft.com/en-us/windows/win32/sysinfo/time-functions
https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
https://support.microsoft.com/en-us/help/167296/how-to-convert-a-unix-time-t-to-a-win32-filetime-or-systemtime

How do I add a bullet symbol in TextView?

Since android doesnt support <ol>, <ul> or <li> html elements, I had to do it like this

<string name="names"><![CDATA[<p><h2>List of Names:</h2></p><p>&#8226;name1<br />&#8226;name2<br /></p>]]></string>

if you want to maintain custom space then use </pre> tag

IF a cell contains a string

=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")

Indent multiple lines quickly in vi

As well as the offered solutions, I like to do things a paragraph at a time with >}

Best practices for copying files with Maven

I can only assume that your ${project.server.config} property is something custom defined and is outside of the standard directory layout.

If so, then I'd use the copy task.

Broadcast receiver for checking internet connection in android app

Here's a comfortable way to do it for activity, fragment or context. It will also auto-unregister if you do it for activity/fragment (in onDestroy), if you wish:

abstract class ConnectionBroadcastReceiver : BroadcastReceiver() {
    companion object {
        @JvmStatic
        fun registerWithoutAutoUnregister(context: Context, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
            context.registerReceiver(connectionBroadcastReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
        }

        @JvmStatic
        fun registerToFragmentAndAutoUnregister(context: Context, fragment: Fragment, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
            val applicationContext = context.applicationContext
            registerWithoutAutoUnregister(applicationContext, connectionBroadcastReceiver)
            fragment.lifecycle.addObserver(object : LifecycleObserver {
                @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                fun onDestroy() {
                    applicationContext.unregisterReceiver(connectionBroadcastReceiver)
                }
            })
        }

        @JvmStatic
        fun registerToActivityAndAutoUnregister(activity: AppCompatActivity, connectionBroadcastReceiver: ConnectionBroadcastReceiver) {
            registerWithoutAutoUnregister(activity, connectionBroadcastReceiver)
            activity.lifecycle.addObserver(object : LifecycleObserver {
                @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                fun onDestroy() {
                    activity.unregisterReceiver(connectionBroadcastReceiver)
                }
            })
        }

        @JvmStatic
        fun hasInternetConnection(context: Context): Boolean {
            val info = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
            return !(info == null || !info.isConnectedOrConnecting)
        }
    }

    override fun onReceive(context: Context, intent: Intent) {
        val hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
//        Log.d("AppLog", "conenctivity changed. hasConnection? $hasConnection")
        onConnectionChanged(hasConnection)
    }

    abstract fun onConnectionChanged(hasConnection: Boolean)
}

Usage in fragment:

    ConnectionBroadcastReceiver.registerToFragmentAndAutoUnregister(activity!!, this, object : ConnectionBroadcastReceiver() {
        override fun onConnectionChanged(hasConnection: Boolean) {
            // Log.d("AppLog", "onConnectionChanged:" + hasConnection)
        }
    })

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

Conditional Welcome Message

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

How can I switch my git repository to a particular commit

Just checkout the commit you wants your new branch start from and create a new branch

git checkout -b newbranch 6e559cb95

Convert DOS line endings to Linux line endings in Vim

You can use:

vim somefile.txt +"%s/\r/\r/g" +wq

Or the dos2unix utility.

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

How do I programmatically change file permissions?

Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions(), or atomically at file creation with methods like createFile() or newByteChannel().

You can create a set of permissions using EnumSet.of(), but the helper method PosixFilePermissions.fromString() will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute().

Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);

In earlier versions of Java, using native code of your own, or exec-ing command-line utilities are common approaches.

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How to empty a list in C#?

you can do that

var list = new List<string>();
list.Clear();

Call to a member function on a non-object

It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?

As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:

function page_properties(PageAtrributes $objPortal) {    
    ...
    $objPage->set_page_title($myrow['title']);
}

This function will only accept PageAtrributes for the first parameter.

Stop a youtube video with jquery?

from the API docs:

player.stopVideo()

so in jQuery:

$('#playerID').get(0).stopVideo();

Read Excel sheet in Powershell

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

$lastCell = 11 
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7

$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row

$phoneData = for ($i=1; $i -le $endRow; $i++)
            {
                $pModel = $sh.Cells.Item($startRow,$model).Value2
                $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                $extension = $sh.Cells.Item($startRow,$ext).Value2
                New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                $startRow++
            }

I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

How to get the current date and time of your timezone in Java?

As Jon Skeet already said, java.util.Date does not have a time zone. A Date object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.

When you format a Date object into a string, for example by using SimpleDateFormat, then you can set the time zone on the DateFormat object to let it know in which time zone you want to display the date and time:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

If you want the local time zone of the computer that your program is running on, use:

df.setTimeZone(TimeZone.getDefault());

How to show DatePickerDialog on Button click?

it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.

 btnDate.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                              DialogFragment newFragment = new DatePickerFragment();
                                    newFragment.show(getSupportFragmentManager(), "datePicker");
                            }
                        });

            public static class DatePickerFragment extends DialogFragment
                        implements DatePickerDialog.OnDateSetListener {

                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        final Calendar c = Calendar.getInstance();
                        int year = c.get(Calendar.YEAR);
                        int month = c.get(Calendar.MONTH);
                        int day = c.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
                        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
                        return  dialog;
                    }

                    public void onDateSet(DatePicker view, int year, int month, int day) {
                       btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
                    }
                }

Apache - MySQL Service detected with wrong path. / Ports already in use

  1. Go to cmd and run it with Administrator mode.
  2. Uninstall mysql service through command prompt using the following command.

            sc delete mysql
    
  3. restart XAMPP

How to launch jQuery Fancybox on page load?

I got this to work by calling this function in document ready:

$(document).ready(function () {
        $.fancybox({
            'width': '40%',
            'height': '40%',
            'autoScale': true,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'type': 'iframe',
            'href': 'http://www.example.com'
        });
});

MySQL error - #1062 - Duplicate entry ' ' for key 2

In addition to Sabeen's answer:

The first column id is your primary key.
Don't insert '' into the primary key, but insert null instead.

INSERT INTO users
  (`id`,`title`,`firstname`,`lastname`,`company`,`address`,`city`,`county`
   ,`postcode`,`phone`,`mobile`,`category`,`email`,`password`,`userlevel`) 
VALUES     
  (null,'','John','Doe','company','Streeet','city','county'
  ,'postcode','phone','','category','[email protected]','','');

If it's an autoincrement key this will fix your problem.
If not make id an autoincrement key, and always insert null into it to trigger an autoincrement.

MySQL has a setting to autoincrement keys only on null insert or on both inserts of 0 and null. Don't count on this setting, because your code may break if you change server.
If you insert null your code will always work.

See: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

CMD command to check connected USB devices

you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.

How to display scroll bar onto a html table

If you get to the point where all the mentioned solutions don't work (as it got for me), do this:

  • Create two tables. One for the header and another for the body
  • Give the two tables different parent containers/divs
  • Style the second table's div to allow vertical scroll of its contents.

Like this, in your HTML

<div class="table-header-class">
    <table>
       <thead>
          <tr>
            <th>Ava</th>
            <th>Alexis</th>
            <th>Mcclure</th>
          </tr>
       </thead>
    </table>
</div>
<div class="table-content-class">
   <table>
       <tbody>
          <tr>
            <td>I am the boss</td>
            <td>No, da-da is not the boss!</td>
            <td>Alexis, I am the boss, right?</td>
          </tr>
       </tbody>
    </table>
</div>

Then style the second table's parent to allow vertical scroll, in your CSS

    .table-content-class {
        overflow-y: scroll;    // use auto; or scroll; to allow vertical scrolling; 
        overflow-x: hidden;    // disable horizontal scroll 
    }

Remove Rows From Data Frame where a Row matches a String

Just use the == with the negation symbol (!). If dtfm is the name of your data.frame:

dtfm[!dtfm$C == "Foo", ]

Or, to move the negation in the comparison:

dtfm[dtfm$C != "Foo", ]

Or, even shorter using subset():

subset(dtfm, C!="Foo")

Best Free Text Editor Supporting *More Than* 4GB Files?

The question would need more details.
Do you want just to look at a file (eg. a log file) or to edit it?
Do you have more memory than the size of the file you want to load or less?
For example, TheGun, a very small text editor written in assembly language, claims to "not have an effective file size limit and the maximum size that can be loaded into it is determined by available memory and loading speed of the file. [...] It has been speed optimised for both file load and save."

To abstract the memory limit, I suppose one can use mapped memory. But then, if you need to edit the file, some clever method should be used, like storing in memory the local changes, and applying them chunk by chunk when saving. Might be ineffective in some cases (big search/replace for example).

Bash foreach loop

"foreach" is not the name for bash. It is simply "for". You can do things in one line only like:

for fn in `cat filenames.txt`; do cat "$fn"; done

Reference: http://www.cyberciti.biz/faq/linux-unix-bash-for-loop-one-line-command/

How to assign colors to categorical variables in ggplot2 that have stable mapping?

I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.

png("figure_%d.png")
set.seed(2014)
library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100),
    x = rnorm(500, mean = rep(1:5, 100)),
    y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

Here it is the first figure:

ggplot A-E, mixed colors

and the second figure:

ggplot ADE, mixed colors

As we can see the colors do not stay fixed, for example E switches from magenta to blu.

As suggested by malcook in his comment and by hadley in his comment the code which uses limits works properly:

ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +       
    geom_point() + 
    scale_colour_discrete(drop=TRUE,
        limits = levels(dataset$fCategory))

gives the following figure, which is correct:

correct ggplot

This is the output from sessionInfo():

R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] methods   stats     graphics  grDevices utils     datasets  base     

other attached packages:
[1] ggplot2_0.9.3.1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4       grid_3.0.2        
 [5] gtable_0.1.2       labeling_0.2       MASS_7.3-29        munsell_0.4.2     
 [9] plyr_1.8           proto_0.3-10       RColorBrewer_1.0-5 reshape2_1.2.2    
[13] scales_0.2.3       stringr_0.6.2 

How do I clone a Django model instance object and save it to the database?

Use the below code :

from django.forms import model_to_dict

instance = Some.objects.get(slug='something')

kwargs = model_to_dict(instance, exclude=['id'])
new_instance = Some.objects.create(**kwargs)

How to remove specific value from array using jQuery

Not a jQuery way but... Why don't use simpler way. Remove 'c' from following array

var a = ['a','b','c','d']
a.splice(a.indexOf('c'),1);
>["c"]
a
["a", "b", "d"]

You can also use: (Note to myself: Don’t modify objects you don’t own)

Array.prototype.remove = function(v) { this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1); }
var a = ['a','b','c'];
a.remove('c'); //value of "a" is now ['a','b']

Adding is simplera.push('c')

Why are my CSS3 media queries not working on mobile devices?

For everyone having the same issue, make sure you actually wrote "120px" instead of only "120". This was my mistake and it drove me crazy.

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

Use jQuery to change an HTML tag?

This is my solution. It allows to toggle between tags.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title></title>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>_x000D_
<script type="text/javascript">_x000D_
_x000D_
function wrapClass(klass){_x000D_
 return 'to-' + klass;_x000D_
}_x000D_
_x000D_
function replaceTag(fromTag, toTag){_x000D_
 _x000D_
 /** Create selector for all elements you want to change._x000D_
   * These should be in form: <fromTag class="to-toTag"></fromTag>_x000D_
   */_x000D_
 var currentSelector = fromTag + '.' + wrapClass(toTag);_x000D_
_x000D_
 /** Select all elements */_x000D_
 var $selected = $(currentSelector);_x000D_
_x000D_
 /** If you found something then do the magic. */_x000D_
 if($selected.size() > 0){_x000D_
_x000D_
  /** Replace all selected elements */_x000D_
  $selected.each(function(){_x000D_
_x000D_
   /** jQuery current element. */_x000D_
   var $this = $(this);_x000D_
_x000D_
   /** Remove class "to-toTag". It is no longer needed. */_x000D_
   $this.removeClass(wrapClass(toTag));_x000D_
_x000D_
   /** Create elements that will be places instead of current one. */_x000D_
   var $newElem = $('<' + toTag + '>');_x000D_
_x000D_
   /** Copy all attributes from old element to new one. */_x000D_
   var attributes = $this.prop("attributes");_x000D_
   $.each(attributes, function(){_x000D_
    $newElem.attr(this.name, this.value);_x000D_
   });_x000D_
_x000D_
   /** Add class "to-fromTag" so you can remember it. */_x000D_
   $newElem.addClass(wrapClass(fromTag));_x000D_
_x000D_
   /** Place content of current element to new element. */_x000D_
   $newElem.html($this.html());_x000D_
_x000D_
   /** Replace old with new. */_x000D_
   $this.replaceWith($newElem);_x000D_
  });_x000D_
_x000D_
  /** It is possible that current element has desired elements inside._x000D_
    * If so you need to look again for them._x000D_
    */_x000D_
  replaceTag(fromTag, toTag);_x000D_
 }_x000D_
}_x000D_
_x000D_
_x000D_
</script>_x000D_
_x000D_
<style type="text/css">_x000D_
 _x000D_
 section {_x000D_
  background-color: yellow;_x000D_
 }_x000D_
_x000D_
 div {_x000D_
  background-color: red;_x000D_
 }_x000D_
_x000D_
 .big {_x000D_
  font-size: 40px;_x000D_
 }_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<button onclick="replaceTag('div', 'section');">Section -> Div</button>_x000D_
<button onclick="replaceTag('section', 'div');">Div -> Section</button>_x000D_
_x000D_
<div class="to-section">_x000D_
 <p>Matrix has you!</p>_x000D_
 <div class="to-section big">_x000D_
  <p>Matrix has you inside!</p>_x000D_
 </div>_x000D_
</div>_x000D_
_x000D_
<div class="to-section big">_x000D_
 <p>Matrix has me too!</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

ASP.NET Identity DbContext confusion

I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.

How to line-break from css, without using <br />?

<pre> <---------------------------------------
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
</pre> <--------------------------------------

OR

<div style="white-space:pre">  <-----------------------------------
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
</div>                         <-----------------------------------

source: https://stackoverflow.com/a/36191199/2377343

Unexpected character encountered while parsing value

If you are using downloading data using url...may need to use

var result = client.DownloadData(url);

cmake and libpthread

target_compile_options solution above is wrong, it won't link the library.

Use:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

OR

target_link_libraries(XXX PUBLIC pthread)

OR

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

A formula to copy the values from a formula to another column

you can use those functions together with iferror as a work around.

try =IFERROR(VALUE(A4),(CONCATENATE(A4)))

Negation in Python

try instead:

if not os.path.exists(pathName):
    do this

How to send image to PHP file using Ajax?

Use JavaScript's formData API and set contentType and processData to false

$("form[name='uploader']").on("submit", function(ev) {
  ev.preventDefault(); // Prevent browser default submit.

  var formData = new FormData(this);
    
  $.ajax({
    url: "page.php",
    type: "POST",
    data: formData,
    success: function (msg) {
      alert(msg)
    },
    cache: false,
    contentType: false,
    processData: false
  });
    
});

How can I add new keys to a dictionary?

Here's another way that I didn't see here:

>>> foo = dict(a=1,b=2)
>>> foo
{'a': 1, 'b': 2}
>>> goo = dict(c=3,**foo)
>>> goo
{'c': 3, 'a': 1, 'b': 2}

You can use the dictionary constructor and implicit expansion to reconstruct a dictionary. Moreover, interestingly, this method can be used to control the positional order during dictionary construction (post Python 3.6). In fact, insertion order is guaranteed for Python 3.7 and above!

>>> foo = dict(a=1,b=2,c=3,d=4)
>>> new_dict = {k: v for k, v in list(foo.items())[:2]}
>>> new_dict
{'a': 1, 'b': 2}
>>> new_dict.update(newvalue=99)
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99}
>>> new_dict.update({k: v for k, v in list(foo.items())[2:]})
>>> new_dict
{'a': 1, 'b': 2, 'newvalue': 99, 'c': 3, 'd': 4}
>>> 

The above is using dictionary comprehension.

JQuery, select first row of table

Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find

var $row = $(this).closest('table').children('tr:first');

parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

How to get Client location using Google Maps API v3?

It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:

google.loader.ClientLocation.address.city

Change Bootstrap input focus blue glow

I could not resolve this with CSS. It seems like Boostrap is getting the last say even though I have by site.css after bootstrap. In any event, this worked for me.

$(document).ready(function () {
    var elements = document.getElementsByClassName("form-control");

    Array.from(elements).forEach(function () {
        this.addEventListener("click", cbChange, false);
    })

    });

function cbChange(event) {
    var ele = event.target;
    var obj = document.getElementById(ele.id);
    obj.style.borderColor = "lightgrey";
}

Later I found this to work in the css. Obviously with form-controls only

.form-control.focus, .form-control:focus {
    border-color: gainsboro;
} 

Here are before and after shots from Chrome Developer tool. Notice the difference in border color between focus on and focus off. On a side note, this does not work for buttons. With buttons. With buttons you have to change outline property to none.

enter image description here

enter image description here

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I solved to

test: {
        options: {
          port: 9000,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ],
         middleware: function (connect) {
                  return [
                      modRewrite(['^[^\\.]*$ /index.html [L]']),
                      connect.static('.tmp'),
                      connect().use(
                          '/bower_components',
                          connect.static('./bower_components')
                      ),
                      connect.static('app')
                  ];
              }
        }
      },

What is the difference between CSS and SCSS?

css has variables as well. You can use them like this:

--primaryColor: #ffffff;
--width: 800px;

body {
    width: var(--width);
    color: var(--primaryColor);
}
.content{
    width: var(--width);
    background: var(--primaryColor);
}

How do I update the password for Git?

I was pushing into the repository for the first time. So there was no HEAD defined.

The easiest way would be to:

git push -u origin master

It will then prompt for the password, and once you enter that it will be saved automatically, and you will be able to push.

Error parsing yaml file: mapping values are not allowed here

Change

application:climate-change

to

application: climate-change

The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)

pandas dataframe groupby datetime month

Managed to do it:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

Or

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.

VideoView Full screen in android application

I have done this way:

Check these reference screen shots.

enter image description here

Add class FullScreenVideoView.java:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;

public class FullScreenVideoView extends VideoView {
    public FullScreenVideoView(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }
}

How to bind with xml:

<FrameLayout
   android:id="@+id/secondMedia"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

     <com.my.package.customview.FullScreenVideoView
           android:layout_width="match_parent"
           android:layout_height="match_parent" 
           android:id="@+id/fullScreenVideoView"/>

</FrameLayout>

Hope this will help you.

What is an example of the Liskov Substitution Principle?

It states that if C is a subtype of E then E can be replaced with objects of type C without changing or breaking the behavior of the program. In simple words, derived classes should be substitutable for their parent classes. For example, if a Farmer’s son is Farmer then he can work in place of his father but if a Farmer’s son is a cricketer then he can’t work in place of his father.

Violation Example:

public class Plane{

  public void startEngine(){}      

}        
public class FighterJet extends Plane{}
    
public class PaperPlane extends Plane{}

In the given example FighterPlane and PaperPlane classes both extending the Plane class which contain startEngine() method. So it's clear that FighterPlane can start engine but PaperPlane can’t so it’s breaking LSP.

PaperPlane class although extending Plane class and should be substitutable in place of it but is not an eligible entity that Plane’s instance could be replaced by, because a paper plane can’t start the engine as it doesn’t have one. So the good example would be,

Respected Example:

public class Plane{ 
} 
public class RealPlane{

  public void startEngine(){} 

}
public class FighterJet extends RealPlane{} 
public class PaperPlane extends Plane{}

Facebook Like-Button - hide count?

this worked for me:

.fb-like.fb_edge_widget_with_comment.fb_iframe_widget {
    height: 26px;
    overflow: hidden;
    width: 138px;
}

How to get the client IP address in PHP

Just on this, and I'm surprised it hasn't been mentioned yet, is to get the correct IP addresses of those sites that are nestled behind the likes of CloudFlare infrastructure. It will break your IP addresses, and give them all the same value. Fortunately they have some server headers available too. Instead of me rewriting what's already been written, have a look here for a more concise answer, and yes, I went through this process a long while ago too. https://stackoverflow.com/a/14985633/1190051

Display array values in PHP

There is foreach loop in php. You have to traverse the array.

foreach($array as $key => $value)
{
  echo $key." has the value". $value;
}

If you simply want to add commas between values, consider using implode

$string=implode(",",$array);
echo $string;

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

RequiredIf Conditional Validation Attribute

Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.

I also found that I didn't need the JavaScript.

I added the following class to my Models folder:

public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
    private String PropertyName { get; set; }
    private Object InvalidValue { get; set; }
    private readonly RequiredAttribute _innerAttribute;

    public RequiredIfNotAttribute(String propertyName, Object invalidValue)
    {
        PropertyName = propertyName;
        InvalidValue = invalidValue;
        _innerAttribute = new RequiredAttribute();
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

        if (dependentValue.ToString() != InvalidValue.ToString())
        {
            if (!_innerAttribute.IsValid(value))
            {
                return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
            }
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessageString,
            ValidationType = "requiredifnot",
        };
        rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
        rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;

        yield return rule;
    }

I didn't need to make any changes to my view, but did make a change to the properties of my model:

    [RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
    public string TemplateGTSource { get; set; }

    public string TemplateGTMedium
    {
        get
        {
            return "Email";
        }
    }

    [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
    public string TemplateGTCampaign { get; set; }

    [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
    public string TemplateGTTerm { get; set; }

Hope this helps!

VB.NET - Remove a characters from a String

The string class's Replace method can also be used to remove multiple characters from a string:

Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")

Exploring Docker container's file system

The most upvoted answer is working for me when the container is actually started, but when it isn't possible to run and you for example want to copy files from the container this has saved me before:

docker cp <container-name>:<path/inside/container> <path/on/host/>

Thanks to docker cp (link) you can copy directly from the container as it was any other part of your filesystem. For example, recovering all files inside a container:

mkdir /tmp/container_temp
docker cp example_container:/ /tmp/container_temp/

Note that you don't need to specify that you want to copy recursively.

Maven with Eclipse Juno

All the info you need, is provided in the release announcement for m2e 1.1:

m2e 1.1 has been released as part of Eclipse Juno simultaneous release today.

[...]

m2e 1.1 is already included in "Eclipse IDE for Java Developers" package available from http://eclipse.org/downloads/ or it can be installed from Eclipse Juno release repository [2]. Eclipse 3.7/Indigo users can install the new version from m2e release repository [3]

[...]

[2] http://download.eclipse.org/releases/juno

[3] http://download.eclipse.org/technology/m2e/releases

How can I provide multiple conditions for data trigger in WPF?

THIS ANSWER IS FOR ANIMATIONS ONLY


If you wanna implement the AND logic, you should use MultiTrigger, here is an example:

Suppose we want to do some actions if the property Text="" (empty string) AND IsKeyboardFocused="False", then your code should look like the following:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
        <MultiTrigger.EnterActions>
            <!-- Your actions here -->
        </MultiTrigger.EnterActions>
</MultiTrigger>

If you wanna implement the OR logic, there are couple of ways, and it depends on what you try to do:

The first option is to use multiple Triggers.
So, suppose you wanna do something if either Text="" OR IsKeyboardFocused="False",
then your code should look something like this:

<Trigger Property="IsEnabled" Value="false">
    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
    <Setter Property="BorderBrush" TargetName="border" 
            Value="{StaticResource TextBox.MouseOver.Border}"/>
</Trigger>


But the problem in this is what will I do if i wanna do something if either Text ISN'T null OR IsKeyboard="True"? This can be achieved by the second approach:
Recall De Morgan's rule, that says !(!x && !y) = x || y.
So we'll use it to solve the previous problem, by writing a multi trigger that it's triggered when Text="" and IsKeyboard="True", and we'll do our actions in EXIT ACTIONS, like this:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
    <MultiTrigger.ExitActions>
        <!-- Do something here -->
    </MultiTrigger.ExitActions>
</MultiTrigger>

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tin3;
+----+------------+
| id | val        |
+----+------------+
|  1 | 0000000012 |
|  2 | 0000000007 |
|  4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)

mysql>

mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
|          10 |
+-------------+
1 row in set (0.01 sec)


mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
|     8 |
+-------+
1 row in set (0.00 sec)

Selenium WebDriver: Wait for complex page with JavaScript to load

Don't know how to do that but in my case, end of page load & rendering match with FAVICON displayed in Firefox tab.

So if we can get the favicon image in the webbrowser, the web page is fully loaded.

But how perform this ....

Call a function after previous function is complete

If you're using jQuery 1.5 you can use the new Deferreds pattern:

$('a.button').click(function(){
    if(condition == 'true'){
        $.when(function1()).then(function2());
    }
    else {
        doThis(someVariable);
    }
});

Edit: Updated blog link:

Rebecca Murphy had a great write-up on this here: http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

I had the same error after moving to a new laptop (Windows 10). In addition to setting Copy Local to true as mentioned above, I had to install the Crystal Reports 32-bit runtime engine for .Net Framework, even though everything else is set to run in a 64-bit environment. Hope that helps.

Windows Control Panel - Programs and Features

RelativeLayout center vertical

Adding both android:layout_centerInParent and android:layout_centerVertical work for me to center ImageView both vertical and horizontal:

<ImageView
    ..
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    />

bootstrap datepicker today as default

If none of the above option work, use the following :

$(".datepicker").datepicker();
$(".datepicker").datepicker("setDate", new Date());

This worked for me.

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

So, eventually I did that thing that all developers hate doing. I went and checked the server log files and found a report of a syntax error in line n.

tail -n 20 /var/log/apache2/error.log

JFrame Maximize window

i like this version:

import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class Test
{
    public static void main(String [] args)
    {
        final JFrame frame = new JFrame();
        final GraphicsConfiguration config = frame.getGraphicsConfiguration();

        final int left = Toolkit.getDefaultToolkit().getScreenInsets(config).left;
        final int right = Toolkit.getDefaultToolkit().getScreenInsets(config).right;
        final int top = Toolkit.getDefaultToolkit().getScreenInsets(config).top;
        final int bottom = Toolkit.getDefaultToolkit().getScreenInsets(config).bottom;

        final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        final int width = screenSize.width - left - right;
        final int height = screenSize.height - top - bottom;

        frame.setResizable(false);
        frame.setSize(width,height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        frame.setVisible(true);
    }
}

How to make CSS3 rounded corners hide overflow in Chrome/Opera

As for me none of the solutions worked well, only using:

-webkit-mask-image: -webkit-radial-gradient(circle, white, black);

on the wrapper element did the job.

Here the example: http://jsfiddle.net/gpawlik/qWdf6/74/

How do I get a button to open another activity?

If you declared your button in the xml file similar to this:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="next activity"
        android:onClick="goToActivity2"
        />

then you can use it to change the activity by putting this at the java file:

public void goToActivity2 (View view){
    Intent intent = new Intent (this, Main2Activity.class);
    startActivity(intent);
}

Note that my second activity is called "Main2Activity"

public static const in TypeScript

Just simply 'export' variable and 'import' in your class

export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';

// default err string message
export var errStringMsg = 'Something went wrong';

Now use it as,

import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);

Docker: adding a file from a parent directory

Since -f caused another problem, I developed another solution.

  • Create a base image in the parent folder
  • Added the required files.
  • Used this image as a base image for the project which in a descendant folder.

The -f flag does not solved my problem because my onbuild image looks for a file in a folder and had to call like this:

-f foo/bar/Dockerfile foo/bar

instead of

-f foo/bar/Dockerfile .

Also note that this is only solution for some cases as -f flag

Converting json results to a date

If you use jQuery

In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.

You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.

It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).

Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

TortoiseSVN icons overlay not showing after updating to Windows 10

I was using Subversion 1.7.x and installing the version 1.9.1 or modifying the registry entries did not solve this issue of icon overlays.

In my case, after using SVN upgrade working copy the icon overlays for the upgraded project appeared.

In conclusion, old projects using Subversion 1.7.x do not show icons and projects using Subversion 1.9.x do (under Windows 10).

Tip: there is a button that takes you to the registry in Settings -> Icon Overlays -> Overlay Handlers -> Start registry editor. At least in version 1.9.1

Android ListView with different layouts for each row

In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.

Remove ALL white spaces from text

Now you can use "replaceAll":

console.log(' a b    c d e   f g   '.replaceAll(' ',''));

will print:

abcdefg

But not working in every possible browser:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

how much memory can be accessed by a 32 bit machine?

What's typically meant by 32-bit or 64-bit machine is the size of the externally visible ("architected") general-purpose integer registers.

This has very little to do with how the hardware is built though. For example, let's consider the (long obsolete) Intel Pentium Pro. It's normally considered a "32-bit" processor, even though it supports up to 36-bit physical addresses, has a 64-bit wide data bus, and internally computations on all supported operand types are carried out in a single set of registers (which are therefore 80 bits wide, to support the largest floating point type).

At least in the case of Intel processors, even though larger physical addressing has been available for a long time, the largest amount of memory directly visible within the address space of any one process on a 32-bit processor is also limited to 4 gigabytes (32-bit addressing). The 36-bit physical addressing allows addressing up to 64 gigabytes of RAM, but only 4 gigabytes of that can be directly visible at any given time.

The change to 64-bit machines mostly involved changing what was made visible to the user (or to code at the assembly language level). Again, what you see is rarely identical to what's real. For example, most 64-bit code sees pointers/addresses as being 64 bits, but actual processors don't support that large of addresses. Current CPUs support 48-bit virtual addresses, and (at least as far as I've noticed) a maximum of 40 bits of physical addressing. On the other hand, they're designed so in the future, when larger memory becomes practical, they can extend the physical addressing out to 48 bits without affecting software at all. Even when they increase the 48-bit virtual addressing, in a typical case it'll only affect a small amount of the operating system kernel (normal code is unaffected, because it already assumed addresses are 64 bits).

So, no: a 64-bit machine does not really support up to 64 bits of physical addressing, but most typical 64-bit software should remain compatible with a future processor that did support directly addressing that much RAM.

jquery .on() method with load event

To run function onLoad

jQuery(window).on("load", function(){
    ..code..
});

To run code onDOMContentLoaded (also called onready)

jQuery(document).ready(function(){
    ..code..
});

or the recommended shorthand for onready

jQuery(function($){
    ..code.. ($ is the jQuery object)
});

onready fires when the document has loaded

onload fires when the document and all the associated content, like the images on the page have loaded.

What is the difference between & and && in Java?

Besides && and || being short circuiting, also consider operator precedence when mixing the two forms. I think it will not be immediately apparent to everybody that result1 and result2 contain different values.

boolean a = true;
boolean b = false;
boolean c = false;

boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c

Preprocessor check if multiple defines are not defined

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)

how does unix handle full path name with space and arguments?

You can quote the entire path as in windows or you can escape the spaces like in:

/foo\ folder\ with\ space/foo.sh -help

Both ways will work!

Ways to save enums in database

Multiple values with OR relation for one, enum field. The concept for .NET with storing enum types in database like a byte or an int and using FlagsAttribute in your code.

http://blogs.msdn.com/b/efdesign/archive/2011/06/29/enumeration-support-in-entity-framework.aspx

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

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

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

The problem is you are not in the correct directory. A simple fix in Jupyter is to do the following command:

  1. Move to the GitHub directory for your installation
  2. Run the GitHub command

Here is an example command to use in Jupyter:

%%bash
cd /home/ec2-user/ml_volume/GitHub_BMM
git show

Note you need to do the commands in the same cell.

HTTP POST with Json on Body - Flutter/Dart

OK, finally we have an answer...

You are correctly specifying headers: {"Content-Type": "application/json"}, to set your content type. Under the hood either the package http or the lower level dart:io HttpClient is changing this to application/json; charset=utf-8. However, your server web application obviously isn't expecting the suffix.

To prove this I tried it in Java, with the two versions

conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works

Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.

EDIT Later investigation shows that it's the http package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http and use the dart:io HttpClient directly. You end up with a bit of boilerplate which is normally handled for you by http.

Working example below:

import 'dart:convert';
import 'dart:io';
import 'dart:async';

main() async {
  String url =
      'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
  Map map = {
    'data': {'apikey': '12345678901234567890'},
  };

  print(await apiRequest(url, map));
}

Future<String> apiRequest(String url, Map jsonMap) async {
  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();
  // todo - you should check the response.statusCode
  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)

Synchronization vs Lock

Many answers here recommend using synchronized.

However, it depends on the usecase.

The synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation.

Locks avoid this by allowing configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance.

So, for a smaller system which can do without concurrency and allowing one thread to execute an operation, synchronized can work. Otherwise, lock can be taken on the key.

How do I add button on each row in datatable?

var table =$('#example').DataTable( {
    data: yourdata ,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "parent" },
        { data: "date" },

        {data: "id" , render : function ( data, type, row, meta ) {
              return type === 'display'  ?
                '<a href="<?php echo $delete_url;?>'+ data +'" ><i class="fe fe-delete"></i></a>' :
                data;
            }},
    ],
    }
}

OnClickListener in Android Studio

This worked for me:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_newarea);

    btnSave = (Button)findViewById(R.id.btnSave);

    OnClickListener btnListener = new OnClickListener() {
        @Override
        public void onClick(android.view.View view) {
            finish();
        }
    };
    btnSave.setOnClickListener(btnListener);

}

Is arr.__len__() the preferred way to get the length of an array in Python?

The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call len on it.

l = [1,2,3,4]
s = 'abcde'
len(l) #returns 4
len(s) #returns 5

The reason for the "strange" syntax is that internally python translates len(object) into object.__len__(). This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a __len__() method on it and then one can call len on those instances.

How do I install TensorFlow's tensorboard?

The pip package you are looking for is tensorflow-tensorboard developed by Google.

Bootstrap modal - close modal when "call to action" button is clicked

Make as shown.

_x000D_
_x000D_
  $(document).ready(function(){_x000D_
    $('#myModal').modal('show');_x000D_
_x000D_
    $('#myBtn').on('click', function(){_x000D_
      $('#myModal').modal('show');_x000D_
    });_x000D_
    _x000D_
  });_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Activate Modal with JavaScript</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Finding partial text in range, return an index

I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B

I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.

Filtering Table rows using Jquery

Have a look at this jsfiddle.

The idea is to filter rows with function which will loop through words.

jo.filter(function (i, v) {
    var $t = $(this);
    for (var d = 0; d < data.length; ++d) {
        if ($t.is(":contains('" + data[d] + "')")) {
            return true;
        }
    }
    return false;
})
//show the rows that match.
.show();

EDIT: Note that case insensitive filtering cannot be achieved using :contains() selector but luckily there's text() function so filter string should be uppercased and condition changed to if ($t.text().toUpperCase().indexOf(data[d]) > -1). Look at this jsfiddle.

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

Reporting Services export to Excel with Multiple Worksheets

Group your report data based on the category that you want your sheets to be based on. Specify that you want that grouping to start a new page for every new category. Each page becomes a new worksheet in the Excel workbook.

Note: I use SQL Server 2003 and Excel 2003.

Is std::vector copying the objects with a push_back?

std::vector always makes a copy of whatever is being stored in the vector.

If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.

How to change string into QString?

Moreover, to convert whatever you want, you can use the QVariant class.

for example:

std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();

output

"hello !"
"10"
"5.42"
5

npm global path prefix

If you have linked the node packages using sudo command

Then go to the folder where node_modules are installed globally.

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.

Windows XP - %USERPROFILE%\Application Data\npm\node_modules Windows 7 - %AppData%\npm\node_modules

and then run the command

ls -l

This will give the list of all global node_modules and you can easily see the linked node modules.

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The problem is in this line:

with pattern.findall(row) as f:

You are using the with statement. It requires an object with __enter__ and __exit__ methods. But pattern.findall returns a list, with tries to store the __exit__ method, but it can't find it, and raises an error. Just use

f = pattern.findall(row)

instead.

CSS Layout - Dynamic width DIV

try

<div style="width:100%;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>

or

<div style="width:100%; border:2px solid #dadada;">
    <div style="width:50px; float: left;"><img src="myleftimage" /></div>
    <div style="width:50px; float: right;"><img src="myrightimage" /></div>
    <div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>    
</div>

Solving a "communications link failure" with JDBC and MySQL

I was experiencing similar problem and the solution for my case was

  1. changing bind-address = 0.0.0.0 from 127.0.0.1
  2. changing url's localhost to localhost:3306

the thing i felt is we should never give up, i tried every options from this post and from other forums as well...happy it works @saurab

What character represents a new line in a text area

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

If you use anything else you will cause issues with cut and paste on Windows platforms.

The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.

Interestingly, in spite of the Unix line end convention being \n, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n. Yes, it may not make a lot of sense, but that's history and evolving standards for you!

Log4net does not write the log in the log file

Also, Make sure the "Copy always" option is selected for [log4net].config

enter image description here

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

Replace Your JS with

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Source link

How to merge remote changes at GitHub?

You probably have changes on github that you never merged. Try git pull to fetch and merge the changes, then you should be able to push. Sorry if I misunderstood your question.

Why does DEBUG=False setting make my django Static Files Access fail?

You can use WhiteNoise to serve static files in production.

Install:

pip install WhiteNoise==2.0.6

And change your wsgi.py file to this:

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise

application = get_wsgi_application()
application = DjangoWhiteNoise(application)

And you're good to go!

Credit to Handlebar Creative Blog.

BUT, it's really not recommended serving static files this way in production. Your production web server(like nginx) should take care of that.

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

Converting an int to std::string

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.

Implementation

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.

How to run Nginx within a Docker container without halting?

To expand on Charles Duffy's answer, Nginx uses the daemon off directive to run in the foreground. If it's inconvenient to put this in the configuration file, we can specify it directly on the command line. This makes it easy to run in debug mode (foreground) and directly switch to running in production mode (background) by changing command line args.

To run in foreground:

nginx -g 'daemon off;'

To run in background:

nginx

How to import multiple csv files in a single load?

Ex1:

Reading a single CSV file. Provide complete file path:

 val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\tmp\\cars1.csv")

Ex2:

Reading multiple CSV files passing names:

val df=spark.read.option("header","true").csv("C:spark\\sample_data\\tmp\\cars1.csv", "C:spark\\sample_data\\tmp\\cars2.csv")

Ex3:

Reading multiple CSV files passing list of names:

val paths = List("C:spark\\sample_data\\tmp\\cars1.csv", "C:spark\\sample_data\\tmp\\cars2.csv")
val df = spark.read.option("header", "true").csv(paths: _*)

Ex4:

Reading multiple CSV files in a folder ignoring other files:

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\tmp\\*.csv")

Ex5:

Reading multiple CSV files from multiple folders:

val folders = List("C:spark\\sample_data\\tmp", "C:spark\\sample_data\\tmp1")
val df = spark.read.option("header", "true").csv(folders: _*)

How can I force input to uppercase in an ASP.NET textbox?

Use a CSS style on the text box. Your CSS should be something like this:

.uppercase
{
    text-transform: uppercase;
}

<asp:TextBox ID="TextBox1" runat="server" Text="" CssClass="uppercase"></asp:TextBox>;

Hide html horizontal but not vertical scrollbar

You can use css like this:

overflow-y: scroll;
overflow-x: hidden;

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

Can I get the name of the currently running function in JavaScript?

This should do it:

var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);

For the caller, just use caller.toString().

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Beginner Python Practice?

Try Project Euler:

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The problem is:

Add all the natural numbers below 1000 that are multiples of 3 or 5.

This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.

Angular 2 execute script after template render

I've used this method (reported here )

export class AppComponent {

  constructor() {
    if(document.getElementById("testScript"))
      document.getElementById("testScript").remove();
    var testScript = document.createElement("script");
    testScript.setAttribute("id", "testScript");
    testScript.setAttribute("src", "assets/js/test.js");
    document.body.appendChild(testScript);
  }
}

it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

The issue for me was calling get_text_noop in the LANGUAGES iterable.

Changing

LANGUAGES = (
    ('en-gb', get_text_noop('British English')),
    ('fr', get_text_noop('French')),
)

to

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en-gb', _('British English')),
    ('fr', _('French')),
)

in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty exception.

Error type 3 Error: Activity class {} does not exist

That might also happen if you have by mistake two launcher Activity in your AndroidManifest.xml like this:

    <activity android:name=".ActivityA">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".ActivityB">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

Just leave the correct one LAUNCHER Activity

How to link C++ program with Boost using CMake

Here is my take:

cmake_minimum_required(VERSION 3.15)

project(TryOuts LANGUAGES CXX)

find_package(Boost QUIET REQUIRED COMPONENTS program_options)

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
endif()

add_executable(helloworld main.cpp)

target_link_libraries(helloworld PUBLIC Boost::program_options)

Node.js + Nginx - What now?

We can easily setup a Nodejs app by Nginx acting as a reverse proxy.
The following configuration assumes the NodeJS application is running on 127.0.0.1:8080,

  server{
     server_name domain.com sub.domain.com; # multiple domains

     location /{ 
      proxy_pass http://127.0.0.1:8080;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }

     location /static/{
       alias /absolute/path/to/static/files; # nginx will handle js/css
     }
   } 

in above setup your Nodejs app will,

  • get HTTP_HOST header where you can apply domain specific logic to serve the response. '
  • Your Application must be managed by a process manager like pm2 or supervisor for handling situations/reusing sockets or resources etc.

  • Setup an error reporting service for getting production errors like sentry or rollbar

NOTE: you can setup logic for handing domain specific request routes, create a middleware for expressjs application

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

For me the solution was to replace

service mongod start

with

start mongod

Check if a key exists inside a json object

Type check also works :

if(typeof Obj.property == "undefined"){
    // Assign value to the property here
    Obj.property = someValue;
}

RestClientException: Could not extract response. no suitable HttpMessageConverter found

In my case @Ilya Dyoshin's solution didn't work: The mediatype "*" was not allowed. I fix this error by adding a new converter to the restTemplate this way during initialization of the MockRestServiceServer:

  MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = 
                      new MappingJackson2HttpMessageConverter();
  mappingJackson2HttpMessageConverter.setSupportedMediaTypes(
                                    Arrays.asList(
                                       MediaType.APPLICATION_JSON, 
                                       MediaType.APPLICATION_OCTET_STREAM));
  restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
  mockServer = MockRestServiceServer.createServer(restTemplate);

(Based on the solution proposed by Yashwant Chavan on the blog named technicalkeeda)

JN Gerbaux

Viewing full output of PS command

If you grep the command that you are looking for with a pipe from ps aux, it will wrap the text automatically. I used a lot of the other answers on here, but sometimes if you are looking for something specific, it is nice to just use grep and you know that it will wrap lines.

For instance ps aux | grep ffmpeg .