Programs & Examples On #Actionfilterattribute

ActionFilterAttribute is a hybrid abstract class that implements an Attribute, an IActionFilter, and an IResultFilter. It can be inherited to implement a custom attribute that provides a declarative means to add pre-action and post-action behavior to controller action methods.

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

Specify path to node_modules in package.json

I'm not sure if this is what you had in mind, but I ended up on this question because I was unable to install node_modules inside my project dir as it was mounted on a filesystem that did not support symlinks (a VM "shared" folder).

I found the following workaround:

  1. Copy the package.json file to a temp folder on a different filesystem
  2. Run npm install there
  3. Copy the resulting node_modules directory back into the project dir, using cp -r --dereference to expand symlinks into copies.

I hope this helps someone else who ends up on this question when looking for a way to move node_modules to a different filesystem.

Other options

There is another workaround, which I found on the github issue that @Charminbear linked to, but this doesn't work with grunt because it does not support NODE_PATH as per https://github.com/browserify/resolve/issues/136:

lets say you have /media/sf_shared and you can't install symlinks in there, which means you can't actually npm install from /media/sf_shared/myproject because some modules use symlinks.

  • $ mkdir /home/dan/myproject && cd /home/dan/myproject
  • $ ln -s /media/sf_shared/myproject/package.json (you can symlink in this direction, just can't create one inside of /media/sf_shared)
  • $ npm install
  • $ cd /media/sf_shared/myproject
  • $ NODE_PATH=/home/dan/myproject/node_modules node index.js

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.

<input [(ngModel)]="firstname" name="something">

Remove blank attributes from an Object in Javascript

If you don't want to modify the original object (using some ES6 operators):

const keys = Object.keys(objectWithNulls).filter(key => objectWithNulls[key]);
const pairs = keys.map(key => ({ [key]: objectWithNulls[key] }));

const objectWithoutNulls = pairs.reduce((val, acc) => ({ ...val, ...acc }));

The filter(key => objectWithNulls[key])returns anything that is truthy, so will reject any values such as0 or false, as well as undefined or null. Can be easily changed to filter(key => objectWithNulls[key] !== undefined)or something similar if this is unwanted behaviour.

Get index of selected option with jQuery

selectedIndex is a JavaScript Select Property. For jQuery you can use this code:

jQuery(document).ready(function($) {
  $("#dropDownMenuKategorie").change(function() {
    // I personally prefer using console.log(), but if you want you can still go with the alert().
    console.log($(this).children('option:selected').index());
  });
});

PHP multidimensional array search by value

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

How to generate UML diagrams (especially sequence diagrams) from Java code?

Using IntelliJ IDEA. To generate class diagram select package and press Ctrl + Alt + U:enter image description here

By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies: enter image description here

To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press Ctrl + Alt + U: enter image description here

The result: enter image description here

Also it is possible to generate more others diagrams. See documentation.

Get total number of items on Json object?

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

Why check both isset() and !empty()

Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy

* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

while isset check if the variable isset and not null which can also be found in the php doc(isset)

How can I quickly delete a line in VIM starting at the cursor position?

D or dd deletes and copies the line to the register. You can use Vx which only deletes the line and stays in the normal mode.

Capture characters from standard input without waiting for enter to be pressed

#include <conio.h>

if (kbhit() != 0) {
    cout << getch() << endl;
}

This uses kbhit() to check if the keyboard is being pressed and uses getch() to get the character that is being pressed.

Server Discovery And Monitoring engine is deprecated

I want to add to this thread that it may also have to do with other dependencies.

For instance, nothing I updated or set for NodeJS, MongoDB or Mongoose were the issue - however - connect-mongodb-session had been updated and starting slinging the same error. The solution, in this case, was to simply rollback the version of connect-mongodb-session from version 2.3.0 to 2.2.0.

enter image description here

Creating C formatted strings (not printing them)

If you have a POSIX-2008 compliant system (any modern Linux), you can use the safe and convenient asprintf() function: It will malloc() enough memory for you, you don't need to worry about the maximum string size. Use it like this:

char* string;
if(0 > asprintf(&string, "Formatting a number: %d\n", 42)) return error;
log_out(string);
free(string);

This is the minimum effort you can get to construct the string in a secure fashion. The sprintf() code you gave in the question is deeply flawed:

  • There is no allocated memory behind the pointer. You are writing the string to a random location in memory!

  • Even if you had written

    char s[42];
    

    you would be in deep trouble, because you can't know what number to put into the brackets.

  • Even if you had used the "safe" variant snprintf(), you would still run the danger that your strings gets truncated. When writing to a log file, that is a relatively minor concern, but it has the potential to cut off precisely the information that would have been useful. Also, it'll cut off the trailing endline character, gluing the next log line to the end of your unsuccessfully written line.

  • If you try to use a combination of malloc() and snprintf() to produce correct behavior in all cases, you end up with roughly twice as much code than I have given for asprintf(), and basically reprogram the functionality of asprintf().


If you are looking at providing a wrapper of log_out() that can take a printf() style parameter list itself, you can use the variant vasprintf() which takes a va_list as an argument. Here is a perfectly safe implementation of such a wrapper:

//Tell gcc that we are defining a printf-style function so that it can do type checking.
//Obviously, this should go into a header.
void log_out_wrapper(const char *format, ...) __attribute__ ((format (printf, 1, 2)));

void log_out_wrapper(const char *format, ...) {
    char* string;
    va_list args;

    va_start(args, format);
    if(0 > vasprintf(&string, format, args)) string = NULL;    //this is for logging, so failed allocation is not fatal
    va_end(args);

    if(string) {
        log_out(string);
        free(string);
    } else {
        log_out("Error while logging a message: Memory allocation failed.\n");
    }
}

VBA: Convert Text to Number

This can be used to find all the numeric values (even those formatted as text) in a sheet and convert them to single (CSng function).

For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants)
    If IsNumeric(r) Then
       r.Value = CSng(r.Value)
       r.NumberFormat = "0.00"
    End If
Next

How to set character limit on the_content() and the_excerpt() in wordpress

wp_trim_words() This function trims text to a certain number of words and returns the trimmed text.

$excerpt = wp_trim_words( get_the_content(), 40, '<a href="'.get_the_permalink().'">More Link</a>');

Get truncated string with specified width using mb_strimwidth() php function.

$excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );

Using add_filter() method of WordPress on the_content filter hook.

add_filter( "the_content", "limit_content_chr" );
function limit_content_chr( $content ){
    if ( 'post' == get_post_type() ) {
        return mb_strimwidth( strip_tags($content), 0, 100, '...' );
    } else {
        return $content;
    }
}

Using custom php function to limit content characters.

function limit_content_chr( $content, $limit=100 ) {
    return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
}

// using above function in template tags
echo limit_content_chr( get_the_content(), 50 );

How can I pass a parameter to a Java Thread?

Either write a class that implements Runnable, and pass whatever you need in a suitably defined constructor, or write a class that extends Thread with a suitably defined constructor that calls super() with appropriate parameters.

How to check if a specific key is present in a hash or not?

In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:

YourHash.has_key? :yourkey

Remove a character at a certain position in a string - javascript

Hi starbeamrainbowlabs ,

You can do this with the following:

var oldValue = "pic quality, hello" ;
var newValue =  "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);

I tested this in my javascript console so you can also check this out Thanks

How to style a JSON block in Github Wiki?

2019 Github Solution

```yaml
{
   "this-json": "looks awesome..."
}

Result

enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

How to Create a circular progressbar in Android which rotates on it?

With the Material Components Library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
    app:indicatorColor="@color/...."
    app:trackColor="@color/...."
    app:circularRadius="64dp"/>

You can use these attributes:

  • circularRadius: defines the radius of the circular progress indicator
  • trackColor: the color used for the progress track. If not defined, it will be set to the indicatorColor and apply the android:disabledAlpha from the theme.
  • indicatorColor: the single color used for the indicator in determinate/indeterminate mode. By default it uses theme primary color

enter image description here

Use progressIndicator.setProgressCompat((int) value, true); to update the value in the indicator.

Note: it requires at least the version 1.3.0-alpha04.

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

hibernate could not get next sequence value

The Database that we are using should be mentioned under search_path in Postgres SQL Configuration file. This can be done by editing Postgressql configuration file by setting search_path along with database name for example: TESTDB.

  1. Find postgressql.conf file under data folder of Postgres SQL datbase.
  2. Set search_path = "$user", public, TESTDB;
  3. Restart the Postgres SQL service to affect the change.

It worked for me after making the above change.

How to add minutes to my Date

The issue for you is that you are using mm. You should use MM. MM is for month and mm is for minutes. Try with yyyy-MM-dd HH:mm

Other approach:

It can be as simple as this (other option is to use joda-time)

static final long ONE_MINUTE_IN_MILLIS=60000;//millisecs

Calendar date = Calendar.getInstance();
long t= date.getTimeInMillis();
Date afterAddingTenMins=new Date(t + (10 * ONE_MINUTE_IN_MILLIS));

Sort array of objects by single key with date value

As This answer's states, you can use Array.sort.

arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)})

_x000D_
_x000D_
arr = [_x000D_
    {_x000D_
        "updated_at" : "2012-01-01T06:25:24Z",_x000D_
        "foo" : "bar"_x000D_
    },_x000D_
    {_x000D_
        "updated_at" : "2012-01-09T11:25:13Z",_x000D_
        "foo" : "bar"_x000D_
    },_x000D_
    {_x000D_
        "updated_at" : "2012-01-05T04:13:24Z",_x000D_
        "foo" : "bar"_x000D_
    }_x000D_
];_x000D_
arr.sort(function(a,b){return new Date(a.updated_at) - new Date(b.updated_at)});_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

default web page width - 1024px or 980px?

I use mostly 978px width for my designs. Adv. of 978px : can be divided by 2,3.

Get data from fs.readFile

As said, fs.readFile is an asynchronous action. It means that when you tell node to read a file, you need to consider that it will take some time, and in the meantime, node continued to run the following code. In your case it's: console.log(content);.

It's like sending some part of your code for a long trip (like reading a big file).

Take a look at the comments that I've written:

var content;

// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});

// in the meantime, please continue and run this console.log
console.log(content);

That's why content is still empty when you log it. node has not yet retrieved the file's content.

This could be resolved by moving console.log(content) inside the callback function, right after content = data;. This way you will see the log when node is done reading the file and after content gets a value.

Filter df when values matches part of a string in pyspark

Spark 2.2 onwards

df.filter(df.location.contains('google.com'))

Spark 2.2 documentation link


Spark 2.1 and before

You can use plain SQL in filter

df.filter("location like '%google.com%'")

or with DataFrame column methods

df.filter(df.location.like('%google.com%'))

Spark 2.1 documentation link

Show and hide divs at a specific time interval using jQuery

Loop through divs every 10 seconds.

$(function () {

    var counter = 0,
        divs = $('#div1, #div2, #div3');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 10 * 1000); // do this every 10 seconds    

});

JavaScript object: access variable property by name as string

Since I was helped with my project by the answer above (I asked a duplicate question and was referred here), I am submitting an answer (my test code) for bracket notation when nesting within the var:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    function displayFile(whatOption, whatColor) {_x000D_
      var Test01 = {_x000D_
        rectangle: {_x000D_
          red: "RectangleRedFile",_x000D_
          blue: "RectangleBlueFile"_x000D_
        },_x000D_
        square: {_x000D_
          red: "SquareRedFile",_x000D_
          blue: "SquareBlueFile"_x000D_
        }_x000D_
      };_x000D_
      var filename = Test01[whatOption][whatColor];_x000D_
      alert(filename);_x000D_
    }_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
  <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p>_x000D_
  <br/>_x000D_
  <p onclick="displayFile('square', 'red')">[ Sq Red ]</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Applying a single font to an entire website with CSS

As a different font is likely to be already defined by the browser for form elements, here are 2 ways to use this font everywhere:

body, input, textarea {
    font-family: Algerian;
}

body {
    font-family: Algerian !important;
}

There'll still have a monospace font on elements like pre/code, kbd, etc but, in case you use these elements, you'd better use a monospace font there.

Important note: if very few people has this font installed on their OS, then the second font in the list will be used. Here you defined no second font so the default serif font will be used, and it'll be Times, Times New Roman except maybe on Linux.
Two options there: use @font-face if your font is free of use as a downloadable font or add fallback(s): a second, a third, etc and finally a default family (sans-serif, cursive (*), monospace or serif). The first of the list that exists on the OS of the user will be used.

(*) default cursive on Windows is Comic Sans. Except if you want to troll Windows users, don't do that :) This font is terrible except for your children birthdays where it's welcome.

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

Assign static IP to Docker container

This works for me.

Create a network with docker network create --subnet=172.17.0.0/16 selnet

Run docker image docker run --net selnet --ip 172.18.0.2 hub

At first, I got

docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled

Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]

Invalid self signed SSL cert - "Subject Alternative Name Missing"

To fix this, you need to supply an extra parameter to openssl when you're creating the cert, basically

-sha256 -extfile v3.ext

where v3.ext is a file like so, with %%DOMAIN%% replaced with the same name you use as your Common Name. More info here and over here. Note that typically you'd set the Common Name and %%DOMAIN%% to the domain you're trying to generate a cert for. So if it was www.mysupersite.com, then you'd use that for both.

v3.ext

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%

Note: Scripts that address this issue, and create fully trusted ssl certs for use in Chrome, Safari and from Java clients can be found here

Another note: If all you're trying to do is stop chrome from throwing errors when viewing a self signed certificate, you can can tell Chrome to ignore all SSL errors for ALL sites by starting it with a special command line option, as detailed here on SuperUser

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Tank´s Yogihosting

I have in my database one goups of tables from Open Streep Maps and I tested successful.

Distance work fine in meters.

SET @orig_lat=-8.116137;
SET @orig_lon=-34.897488;
SET @dist=1000;

SELECT *,(((acos(sin((@orig_lat*pi()/180)) * sin((dest.latitude*pi()/180))+cos((@orig_lat*pi()/180))*cos((dest.latitude*pi()/180))*cos(((@orig_lon-dest.longitude)*pi()/180))))*180/pi())*60*1.1515*1609.344) as distance FROM nodes AS dest HAVING distance < @dist ORDER BY distance ASC LIMIT 100;

how to resolve DTS_E_OLEDBERROR. in ssis

I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.

Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008

http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx

http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx

http://blogs.msdn.com/b/psssql/archive/2008/10/01/windows-scalable-networking-pack-possible-performance-and-concurrency-impacts-to-sql-server-workloads.aspx

How do I change the title of the "back" button on a Navigation Bar

in Xcode 4.5 using storyboard, by far the easiest solution i've found when the value of the Back button doesn't have to change dynamically is to use the "Back Button" field associated with the Navigation Item of the View Controller to which you want the "Back" button to say something else.

e.g. in the screenshot below, i want the Back button for the view controller(s) that i push to have "Back" as the title of the Back button.

enter image description here

of course, this won't work if you need the back button to say something slightly different each time … there are all of the other solutions here for that.

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

sys.argv[1], IndexError: list index out of range

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

Although the code uses try/except to trap some errors, the offending statement occurs in the first line.

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv) and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0] always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

see also:

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

How to drop all stored procedures at once in SQL Server database?

DECLARE @sql VARCHAR(MAX)
SET @sql=''
SELECT @sql=@sql+'drop procedure ['+name +'];' FROM sys.objects
WHERE type = 'p' AND  is_ms_shipped = 0
exec(@sql);

Count the number occurrences of a character in a string

Python 3

Ther are two ways to achieve this:

1) With built-in function count()

sentence = 'Mary had a little lamb'
print(sentence.count('a'))`

2) Without using a function

sentence = 'Mary had a little lamb'    
count = 0

for i in sentence:
    if i == "a":
        count = count + 1

print(count)

AngularJS - difference between pristine/dirty and touched/untouched

$pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

Here's a CodePen that shows the difference in behavior.

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Make Sure the Select Run/Debug Configuration is wear or mobile as per your installation in android studio...

Using array map to filter results with if conditional

You're looking for the .filter() function:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  });

That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  }).map(function(obj) { return obj.id; });

Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

Latex - Change margins of only a few pages

Use the "geometry" package and write \newgeometry{left=3cm,bottom=0.1cm} where you want to change your margins. When you want to reset your margins, you write \restoregeometry.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

For those who are trying to use 3.1.0 but after installing python says "cv2 module not found".

You likely have python but not python-dev.

sudo apt-get install python-dev

then reinstall 3.1.0 and it'll work.

CSS flexbox not working in IE10

As Ennui mentioned, IE 10 supports the -ms prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:

  • You should have display: -ms-flexbox instead of display: -ms-flex
  • I think you should specify all 3 flex values, like flex: 0 1 auto to avoid ambiguity

So the final updated code is...

.flexbox form {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
    display: -o-flex;
    display: flex;

    /* Direction defaults to 'row', so not really necessary to specify */
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    -o-flex-direction: row;
    flex-direction: row;
}

.flexbox form input[type=submit] {
    width: 31px;
}

.flexbox form input[type=text] {
    width: auto;

    /* Flex should have 3 values which is shorthand for 
       <flex-grow> <flex-shrink> <flex-basis> */
    -webkit-flex: 1 1 auto;
    -moz-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    -o-flex: 1 1 auto;
    flex: 1 1 auto;

    /* I don't think you need 'display: flex' on child elements * /
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    /**/
}

Getting multiple keys of specified value of a generic Dictionary?

A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn @Cybis example into such a data structure.

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Simple 3x3 matrix inverse code (C++)

Why don't you try to code it yourself? Take it as a challenge. :)

For a 3×3 matrix

alt text
(source: wolfram.com)

the matrix inverse is

alt text
(source: wolfram.com)

I'm assuming you know what the determinant of a matrix |A| is.

Images (c) Wolfram|Alpha and mathworld.wolfram (06-11-09, 22.06)

How to concatenate multiple column values into a single column in Panda dataframe

The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:

Reduce does a lot better:

from functools import reduce

import pandas as pd

# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'


def reduce_join(df, columns):
    assert len(columns) > 1
    slist = [df[x].astype(str) for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])


def apply_join(df, columns):
    assert len(columns) > 1
    return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)

# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)

# profile
%timeit df1 = reduce_join(df, list('1234'))  # 733 ms
%timeit df2 = apply_join(df, list('1234'))   # 8.84 s

Background images: how to fill whole div if image is small and vice versa

Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/

Calling a phone number in swift

Many of the other answers don't work for Swift 5. Below is the code update to Swift 5:

let formattedNumber = phoneNumberVariable.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")

if let url = NSURL(string: ("tel:" + (formattedNumber)!)) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url as URL)
    }
}

PS:

  1. With most of the answers, I wasn't able to get the prompt on the device. The above code was successfully able to display the prompt.
  2. There is no // after tel: like most answers have. And it works fine.

JUnit Testing Exceptions

Though @Test(expected = MyException.class) and the ExpectedException rule are very good choices, there are some instances where the JUnit3-style exception catching is still the best way to go:

@Test public void yourTest() {
  try {
    systemUnderTest.doStuff();
    fail("MyException expected.");
  } catch (MyException expected) {

    // Though the ExpectedException rule lets you write matchers about
    // exceptions, it is sometimes useful to inspect the object directly.

    assertEquals(1301, expected.getMyErrorCode());
  }

  // In both @Test(expected=...) and ExpectedException code, the
  // exception-throwing line will be the last executed line, because Java will
  // still traverse the call stack until it reaches a try block--which will be
  // inside the JUnit framework in those cases. The only way to prevent this
  // behavior is to use your own try block.

  // This is especially useful to test the state of the system after the
  // exception is caught.

  assertTrue(systemUnderTest.isInErrorState());
}

Another library that claims to help here is catch-exception; however, as of May 2014, the project appears to be in maintenance mode (obsoleted by Java 8), and much like Mockito catch-exception can only manipulate non-final methods.

How to round up a number to nearest 10?

to nearest 10 , should be as below

$number = ceil($input * 0.1)/0.1 ;

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

UITableView with fixed section headers

to make UITableView sections header not sticky or sticky:

  1. change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)

  2. if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)

Adding Apostrophe in every field in particular column for excel

More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution

I want my android application to be only run in portrait mode?

Old post I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

   private void initActivityScreenOrientPortrait()
    {
        // Avoid screen rotations (use the manifests android:screenOrientation setting)
        // Set this to nosensor or potrait

        // Set window fullscreen
        this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        DisplayMetrics metrics = new DisplayMetrics();
        this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

         // Test if it is VISUAL in portrait mode by simply checking it's size
        boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 

        if( !bIsVisualPortrait )
        { 
            // Swap the orientation to match the VISUAL portrait mode
            if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
             { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
        }
        else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }

    }

Works like a charm!

NOTICE: Change this.activity by your activity or add it to the main activity and remove this.activity ;-)

Check if a class is derived from a generic class

Building on the excellent answer above by fir3rpho3nixx and David Schmitt, I have modified their code and added the ShouldInheritOrImplementTypedGenericInterface test (last one).

    /// <summary>
    /// Find out if a child type implements or inherits from the parent type.
    /// The parent type can be an interface or a concrete class, generic or non-generic.
    /// </summary>
    /// <param name="child"></param>
    /// <param name="parent"></param>
    /// <returns></returns>
    public static bool InheritsOrImplements(this Type child, Type parent)
    {
        var currentChild = parent.IsGenericTypeDefinition && child.IsGenericType ? child.GetGenericTypeDefinition() : child;

        while (currentChild != typeof(object))
        {
            if (parent == currentChild || HasAnyInterfaces(parent, currentChild))
                return true;

            currentChild = currentChild.BaseType != null && parent.IsGenericTypeDefinition && currentChild.BaseType.IsGenericType
                                ? currentChild.BaseType.GetGenericTypeDefinition()
                                : currentChild.BaseType;

            if (currentChild == null)
                return false;
        }
        return false;
    }

    private static bool HasAnyInterfaces(Type parent, Type child)
    {
        return child.GetInterfaces().Any(childInterface =>
            {
                var currentInterface = parent.IsGenericTypeDefinition && childInterface.IsGenericType
                    ? childInterface.GetGenericTypeDefinition()
                    : childInterface;

                return currentInterface == parent;
            });

    }

    [Test]
    public void ShouldInheritOrImplementNonGenericInterface()
    {
        Assert.That(typeof(FooImplementor)
            .InheritsOrImplements(typeof(IFooInterface)), Is.True);
    }

    [Test]
    public void ShouldInheritOrImplementGenericInterface()
    {
        Assert.That(typeof(GenericFooBase)
            .InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
    }

    [Test]
    public void ShouldInheritOrImplementGenericInterfaceByGenericSubclass()
    {
        Assert.That(typeof(GenericFooImplementor<>)
            .InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
    }

    [Test]
    public void ShouldInheritOrImplementGenericInterfaceByGenericSubclassNotCaringAboutGenericTypeParameter()
    {
        Assert.That(new GenericFooImplementor<string>().GetType()
            .InheritsOrImplements(typeof(IGenericFooInterface<>)), Is.True);
    }

    [Test]
    public void ShouldNotInheritOrImplementGenericInterfaceByGenericSubclassNotCaringAboutGenericTypeParameter()
    {
        Assert.That(new GenericFooImplementor<string>().GetType()
            .InheritsOrImplements(typeof(IGenericFooInterface<int>)), Is.False);
    }

    [Test]
    public void ShouldInheritOrImplementNonGenericClass()
    {
        Assert.That(typeof(FooImplementor)
            .InheritsOrImplements(typeof(FooBase)), Is.True);
    }

    [Test]
    public void ShouldInheritOrImplementAnyBaseType()
    {
        Assert.That(typeof(GenericFooImplementor<>)
            .InheritsOrImplements(typeof(FooBase)), Is.True);
    }

    [Test]
    public void ShouldInheritOrImplementTypedGenericInterface()
    {
        GenericFooImplementor<int> obj = new GenericFooImplementor<int>();
        Type t = obj.GetType();

        Assert.IsTrue(t.InheritsOrImplements(typeof(IGenericFooInterface<int>)));
        Assert.IsFalse(t.InheritsOrImplements(typeof(IGenericFooInterface<String>)));
    } 

Smooth scrolling when clicking an anchor link

The answer given works but disables outgoing links. Below a version with an added bonus ease out (swing) and respects outgoing links.

$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

SQL Query Multiple Columns Using Distinct on One Column Only

I needed to do the same and had to query a query to get the result

I set my first query up to bring in all IDs from the table and all other information needed to filter:

SELECT tMAIN.tLOTS.NoContract, tMAIN.ID
FROM tMAIN INNER JOIN tLOTS ON tMAIN.ID = tLOTS.id
WHERE (((tLOTS.NoContract)=False));

Save this as Q04_1 -0 this returned 1229 results (there are 63 unique records to query - soime with multiple LOTs)

SELECT DISTINCT ID
FROM q04_1;

Saved that as q04_2

I then wrote another query which brought in the required information linked to the ID

SELECT q04_2.ID, tMAIN.Customer, tMAIN.Category
FROM q04_2 INNER JOIN tMAIN ON q04_2.ID = tMAIN.ID;

Worked a treat and got me exactly what I needed - 63 unique records returned with customer and category details.

This is how I worked around it as I couldn't get the Group By working at all - although I am rather "wet behind the ears" weith SQL (so please be gentle and constructive with feedback)

Regex for remove everything after | (with | )

In a .txt file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+ in the space Find what
and let the space Replace with blank

Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

how to delete files from amazon s3 bucket?

Below is code snippet you can use to delete the bucket,

import boto3, botocore
from botocore.exceptions import ClientError

s3 = boto3.resource("s3",aws_access_key_id='Your-Access-Key',aws_secret_access_key='Your-Secret-Key')
s3.Object('Bucket-Name', 'file-name as key').delete()

How to get these two divs side-by-side?

Using the style

.child_div_1 {
    float:left
}

Select distinct values from a large DataTable column

Sorry to post answer for very old thread. my answer may help other in future.

string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

    //Following function will return Distinct records for Name, City and State column.
    public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
       {
           DataTable dtUniqRecords = new DataTable();
           dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
           return dtUniqRecords;
       }

Gmail: 530 5.5.1 Authentication Required. Learn more at

Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.

How to remove all line breaks from a string

If it happens that you don't need this htm characte &nbsp shile using str.replace(/(\r\n|\n|\r)/gm, "") you can use this str.split('\n').join('');

cheers

Android 5.0 - Add header/footer to a RecyclerView

I had to add a footer to my RecyclerView and here I'm sharing my code snippet as I thought it might be useful. Please check the comments inside the code for better understanding of the overall flow.

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;

public class RecyclerViewWithFooterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int FOOTER_VIEW = 1;
    private ArrayList<String> data; // Take any list that matches your requirement.
    private Context context;

    // Define a constructor
    public RecyclerViewWithFooterAdapter(Context context, ArrayList<String> data) {
        this.context = context;
        this.data = data;
    }

    // Define a ViewHolder for Footer view
    public class FooterViewHolder extends ViewHolder {
        public FooterViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the item
                }
            });
        }
    }

    // Now define the ViewHolder for Normal list item
    public class NormalViewHolder extends ViewHolder {
        public NormalViewHolder(View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Do whatever you want on clicking the normal items
                }
            });
        }
    }

    // And now in onCreateViewHolder you have to pass the correct view
    // while populating the list item.

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v;

        if (viewType == FOOTER_VIEW) {
            v = LayoutInflater.from(context).inflate(R.layout.list_item_footer, parent, false);
            FooterViewHolder vh = new FooterViewHolder(v);
            return vh;
        }

        v = LayoutInflater.from(context).inflate(R.layout.list_item_normal, parent, false);

        NormalViewHolder vh = new NormalViewHolder(v);

        return vh;
    }

    // Now bind the ViewHolder in onBindViewHolder
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        try {
            if (holder instanceof NormalViewHolder) {
                NormalViewHolder vh = (NormalViewHolder) holder;

                vh.bindView(position);
            } else if (holder instanceof FooterViewHolder) {
                FooterViewHolder vh = (FooterViewHolder) holder;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Now the critical part. You have return the exact item count of your list
    // I've only one footer. So I returned data.size() + 1
    // If you've multiple headers and footers, you've to return total count
    // like, headers.size() + data.size() + footers.size()

    @Override
    public int getItemCount() {
        if (data == null) {
            return 0;
        }

        if (data.size() == 0) {
            //Return 1 here to show nothing
            return 1;
        }

        // Add extra view to show the footer view
        return data.size() + 1;
    }

    // Now define getItemViewType of your own.

    @Override
    public int getItemViewType(int position) {
        if (position == data.size()) {
            // This is where we'll add footer.
            return FOOTER_VIEW;
        }

        return super.getItemViewType(position);
    }

    // So you're done with adding a footer and its action on onClick.
    // Now set the default ViewHolder for NormalViewHolder

    public class ViewHolder extends RecyclerView.ViewHolder {
        // Define elements of a row here
        public ViewHolder(View itemView) {
            super(itemView);
            // Find view by ID and initialize here
        }

        public void bindView(int position) {
            // bindView() method to implement actions
        }
    }
}

The above code snippet adds a footer to the RecyclerView. You can check this GitHub repository for checking the implementation of adding both header and a footer.

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

From documentation: https://docs.djangoproject.com/en/1.10/ref/settings/

if DEBUG is False, you also need to properly set the ALLOWED_HOSTS setting. Failing to do so will result in all requests being returned as “Bad Request (400)”.

And from here: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-ALLOWED_HOSTS

I am using something like this:

ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'www.mysite.com']

return string with first match Regex

If you only need the first match, then use re.search instead of re.findall:

>>> m = re.search('\d+', 'aa33bbb44')
>>> m.group()
'33'
>>> m = re.search('\d+', 'aazzzbbb')
>>> m.group()
Traceback (most recent call last):
  File "<pyshell#281>", line 1, in <module>
    m.group()
AttributeError: 'NoneType' object has no attribute 'group'

Then you can use m as a checking condition as:

>>> m = re.search('\d+', 'aa33bbb44')
>>> if m:
        print('First number found = {}'.format(m.group()))
    else:
        print('Not Found')


First number found = 33

Xcode 9 Swift Language Version (SWIFT_VERSION)

This can happen when you added Core Data to an existing project.
Check the:
<Name>/<Name>.xcdatamodeld/<Name>.xcdatamodel/contents
file.
This file contains an entry "sourceLanguage" that (by default) might have been set to "Swift". Change it to "Objective-C".

Executing multiple commands from a Windows cmd script

You can use the && symbol between commands to execute the second command only if the first succeeds. More info here http://commandwindows.com/command1.htm

What is the newline character in the C language: \r or \n?

'\r' = carriage return and '\n' = line feed.

In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.

passing JSON data to a Spring MVC controller

Add the following dependencies

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

Modify request as follows

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

Controller side

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody - Covert Json object to java
@ResponseBody- convert Java object to json

7-Zip command to create and extract a password-protected ZIP file on Windows?

General Syntax:

7z a archive_name target parameters

Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.

Parameters:

  • -p encrypt and prompt for PW.
  • -pPUT_PASSWORD_HERE (this replaces -p) if you want to preset the PW with no prompt.
  • -mhe=on to hide file structure, otherwise file structure and names will be visible by default.

Eg. This will prompt for a PW and hide file structures:

7z a archive_name target -p -mhe=on

Eg. No prompt, visible file structure:

7z a archive_name target -pPUT_PASSWORD_HERE

And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.

Referencing system.management.automation.dll in Visual Studio

if it is 64bit them - C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell**3.0**

and version could be different

How can I view live MySQL queries?

Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';

The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.

You can also add conditions to make it more specific just any SQL query.

e.g. Shows all queries running for 5 seconds or more:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;

e.g. Show all running UPDATEs:

SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';

For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html

Is it possible to get the current spark context settings in PySpark?

Simply running

sc.getConf().getAll()

should give you a list with all settings.

Remove white space below image

.youtube-thumb img {display:block;} or .youtube-thumb img {float:left;}

Outputting data from unit test in Python

I don't think this is quite what your looking for, there's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want.

You can use the TestResult object returned by the TestRunner.run() for results analysis and processing. Particularly, TestResult.errors and TestResult.failures

About the TestResults Object:

http://docs.python.org/library/unittest.html#id3

And some code to point you in the right direction:

>>> import random
>>> import unittest
>>>
>>> class TestSequenceFunctions(unittest.TestCase):
...     def setUp(self):
...         self.seq = range(5)
...     def testshuffle(self):
...         # make sure the shuffled sequence does not lose any elements
...         random.shuffle(self.seq)
...         self.seq.sort()
...         self.assertEqual(self.seq, range(10))
...     def testchoice(self):
...         element = random.choice(self.seq)
...         error_test = 1/0
...         self.assert_(element in self.seq)
...     def testsample(self):
...         self.assertRaises(ValueError, random.sample, self.seq, 20)
...         for element in random.sample(self.seq, 5):
...             self.assert_(element in self.seq)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)
testchoice (__main__.TestSequenceFunctions) ... ERROR
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... FAIL

======================================================================
ERROR: testchoice (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 11, in testchoice
ZeroDivisionError: integer division or modulo by zero

======================================================================
FAIL: testshuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 8, in testshuffle
AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

----------------------------------------------------------------------
Ran 3 tests in 0.031s

FAILED (failures=1, errors=1)
>>>
>>> testResult.errors
[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n  File "<stdin>"
, line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')]
>>>
>>> testResult.failures
[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n  File "<stdin>
", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')]
>>>

How to correctly use "section" tag in HTML5?

You can definitely use the section tag as a container. It is there to group content in a more semantically significant way than with a div or as the html5 spec says:

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. http://www.w3.org/TR/html5/sections.html#the-section-element

How to center icon and text in a android button with width set to "fill parent"

use this android:background="@drawable/ic_play_arrow_black_24dp"

just set the background to the icon you want to center

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

        import React, { useState } from "react"

    const inputTextValue = ({ initialValue }) => {
        const [value, setValue] = useState(initialValue);
        return {
            value,
            onChange: (e) => { setValue(e.target.value) }
        };
    };

    export default () => {
        const textValue = inputTextValue("");
        return (<>
            <input {...textValue} />
        </>
        );
    }

/*"Solution I Tired Changed Name of Funtion in Captial "*/

    import React, { useState } from "react"

const InputTextValue = ({ initialValue }) => {
    const [value, setValue] = useState(initialValue);
    return {
        value,
        onChange: (e) => { setValue(e.target.value) }
    };
};

export default () => {
    const textValue = InputTextValue("");
    return (<>
        <input {...textValue} />
    </>
    );
}

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

How can I get a Unicode character's code?

In Java, char is technically a "16-bit integer", so you can simply cast it to int and you'll get it's code. From Oracle:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

So you can simply cast it to int.

char registered = '®';
System.out.println(String.format("This is an int-code: %d", (int) registered));
System.out.println(String.format("And this is an hexa code: %x", (int) registered));

Programmatically navigate using react router V4

I had a similar issue when migrating over to React-Router v4 so I'll try to explain my solution below.

Please do not consider this answer as the right way to solve the problem, I imagine there's a good chance something better will arise as React Router v4 becomes more mature and leaves beta (It may even already exist and I just didn't discover it).

For context, I had this problem because I occasionally use Redux-Saga to programmatically change the history object (say when a user successfully authenticates).

In the React Router docs, take a look at the <Router> component and you can see you have the ability to pass your own history object via a prop. This is the essence of the solution - we supply the history object to React-Router from a global module.

Steps:

  1. Install the history npm module - yarn add history or npm install history --save
  2. create a file called history.js in your App.js level folder (this was my preference)

    // src/history.js
    
    import createHistory from 'history/createBrowserHistory';
    export default createHistory();`
    
  3. Add this history object to your Router component like so

    // src/App.js
    
    import history from '../your/path/to/history.js;'
    <Router history={history}>
    // Route tags here
    </Router>
    
  4. Adjust the URL just like before by importing your global history object:

    import history from '../your/path/to/history.js;'
    history.push('new/path/here/');
    

Everything should stay synced up now, and you also have access to a way of setting the history object programmatically and not via a component/container.

VIM Disable Automatic Newline At End Of File

I have not tried this option, but the following information is given in the vim help system (i.e. help eol):

'endofline' 'eol'   boolean (default on)
            local to buffer
            {not in Vi}

When writing a file and this option is off and the 'binary' option
is on, no <EOL> will be written for the last line in the file.  This
option is automatically set when starting to edit a new file, unless
the file does not have an <EOL> for the last line in the file, in
which case it is reset.  

Normally you don't have to set or reset this option. When 'binary' is off the value is not used when writing the file. When 'binary' is on it is used to remember the presence of a for the last line in the file, so that when you write the file the situation from the original file can be kept. But you can change it if you want to.

You may be interested in the answer to a previous question as well: "Why should files end with a newline".

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

How can I change or remove HTML5 form validation default error messages?

you can remove this alert by doing following:

<input type="text" pattern="[a-zA-Z]+"
    oninvalid="setCustomValidity(' ')"
/>

just set the custom message to one blank space

How do I check out a remote Git branch?

The git remote show <origin name> command will list all branches (including un-tracked branches). Then you can find the remote branch name that you need to fetch.

Example:

$ git remote show origin

Use these steps to fetch remote branches:

git fetch <origin name> <remote branch name>:<local branch name>
git checkout <local branch name > (local branch name should the name that you given fetching)

Example:

$ git fetch origin test:test
$ git checkout test

Reading from text file until EOF repeats last line

int x;
ifile >> x

while (!iFile.eof())
{  
    cerr << x << endl;        
    iFile >> x;      
}

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Mailto on submit button

In HTML you can specify a mailto: address in the <form> element's [action] attribute.

<form action="mailto:[email protected]" method="GET">
    <input name="subject" type="text" />
    <textarea name="body"></textarea>
    <input type="submit" value="Send" />
</form>

What this will do is allow the user's email client to create an email prepopulated with the fields in the <form>.

What this will not do is send an email.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Remove the following hot fixes and updates

  • Update KB972221
  • Hotfix KB973674
  • Hotfix KB971091

Restart the PC and try to uninstall now. This worked for me without problems.

Order data frame rows according to vector with specific order

If you don't want to use any libraries and you have reoccurrences in your data, you can use which with sapply as well.

new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df        <- df[new_order,]

How to get all the AD groups for a particular user?

Just query the "memberOf" property and iterate though the return, example:

            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder(); //stuff them in | delimited

                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                String dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount;
                    propertyCounter++)
                {
                    dn = (String)result.Properties["memberOf"][propertyCounter];

                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1),
                                (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }

            return groupNames.ToString();

This just stuffs the group names into the groupNames string, pipe delimited, but when you spin through you can do whatever you want with them

Difference between Math.Floor() and Math.Truncate()

Math.Floor() rounds toward negative infinity

Math.Truncate rounds up or down towards zero.

For example:

Math.Floor(-3.4)     = -4
Math.Truncate(-3.4)  = -3

while

Math.Floor(3.4)     = 3
Math.Truncate(3.4)  = 3

What's the best way to convert a number to a string in JavaScript?

If you are curious as to which is the most performant check this out where I compare all the different Number -> String conversions.

Looks like 2+'' or 2+"" are the fastest.

https://jsperf.com/int-2-string

Download file and automatically save it to folder

A much simpler solution would be to download the file using Chrome. In this manner you don't have to manually click on the save button.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
    class MyProcess
    {
        public static void Main()
        {
            Process myProcess = new Process();
            myProcess.Start("chrome.exe","http://www.com/newfile.zip");
        }
    }
}

Prevent HTML5 video from being downloaded (right-click saved)?

First of all realise it is impossible to completely prevent a video being downloaded, all you can do is make it more difficult. I.e. you hide the source of the video.

A web browser temporarily downloads the video in a buffer, so if could prevent download you would also be preventing the video being viewed as well.

You should also know that <1% of the total population of the world will be able to understand the source code making it rather safe anyway. That does not mean you should not hide it in the source as well - you should.

You should not disable right click, and even less you should display a message saying "You cannot save this video for copyright reasons. Sorry about that.". As suggested in this answer.

This can be very annoying and confusing for the user. Apart from that; if they disable JavaScript on their browser they will be able to right click and save anyway.

Here is a CSS trick you could use:

video {
    pointer-events: none;
}

CSS cannot be turned off in browser, protecting your video without actually disabling right click. However one problem is that controls cannot be enabled either, in other words they must be set to false. If you are going to inplament your own Play/Pause function or use an API that has buttons separate to the video tag then this is a feasible option.

controls also has a download button so using it is not such a good idea either.

Here is a JSFiddle example.


If you are going to disable right click using JavaScript then also store the source of the video in JavaScript as well. That way if the user disables JavaScript (allowing right click) the video will not load (it also hides the video source a little better).

From TxRegex answer:

<video oncontextmenu="return false;" controls>
    <source type="video/mp4" id="video">
</video>

Now add the video via JavaScript:

document.getElementById("video").src = "https://www.w3schools.com/html/mov_bbb.mp4";

Functional JSFiddle


Another way to prevent right click involves using the embed tag. This is does not however provide the controls to run the video so they would need to be inplamented in JavaScript:

<embed src="https://www.w3schools.com/html/mov_bbb.mp4"></embed>

Service Reference Error: Failed to generate code for the service reference

As stated above, there are a couple of different problems possible. What we found is that the .DLL for the WCF library had been added as a reference to the client project. This, in turn, created problems with resolving the objects and thus caused the files to be "emptied" by code generation steps. While unchecking the use "Reuse Types..." can seem like an answer, it creates extra definitions of object types, which are proxies to the real types, in a new name space, which then causes all kinds of "compatibility" issues with the use of those types. Only if you really want to "hide" a type should you check this option.

Hiding the type would be appropriate when you don't want a "DLL" type dependency to "leak" into a project that you are trying to keep segregated from another. If the DLL for the WCF library project creeps into the client project references, then you will have this problem with all kinds of strange side effects since the type definitions are also in the DLL.

len() of a numpy array in python

What is the len of the equivalent nested list?

len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])

With the more general concept of shape, numpy developers choose to implement __len__ as the first dimension. Python maps len(obj) onto obj.__len__.

X.shape returns a tuple, which does have a len - which is the number of dimensions, X.ndim. X.shape[i] selects the ith dimension (a straight forward application of tuple indexing).

MySQL: Set user variable from result of query

Use this way so that result will not be displayed while running stored procedure.

The query:

SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;

asp.net validation to make sure textbox has integer values

<script language="javascript" type="text/javascript">
        function fixedlength(textboxID, keyEvent, maxlength) {
            //validation for digits upto 'maxlength' defined by caller function
            if (textboxID.value.length > maxlength) {
                textboxID.value = textboxID.value.substr(0, maxlength);
            }
            else if (textboxID.value.length < maxlength || textboxID.value.length == maxlength) {
                textboxID.value = textboxID.value.replace(/[^\d]+/g, '');
                return true;
            }
            else
                return false;
        }
 </script>

<asp:TextBox ID="txtNextVisit" runat="server" MaxLength="2" onblur="return fixedlength(this, event, 2);" onkeypress="return fixedlength(this, event, 2);" onkeyup="return fixedlength(this, event, 2);"></asp:TextBox> 

Git copy file preserving history

All you have to do is:

  1. move the file to two different locations,
  2. merge the two commits that do the above, and
  3. move one copy back to the original location.

You will be able to see historical attributions (using git blame) and full history of changes (using git log) for both files.

Suppose you want to create a copy of file foo called bar. In that case the workflow you'd use would look like this:

git mv foo bar
git commit

SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit

git merge $SAVED     # This will generate conflicts
git commit -a        # Trivially resolved like this

git mv copy foo
git commit

Why this works

After you execute the above commands, you end up with a revision history that looks like this:

( revision history )            ( files )

    ORIG_HEAD                      foo
     /     \                      /   \
SAVED       ALTERNATE          bar     copy
     \     /                      \   /
      MERGED                     bar,copy
        |                           |
     RESTORED                    bar,foo

When you ask Git about the history of foo, it will:

  1. detect the rename from copy between MERGED and RESTORED,
  2. detect that copy came from the ALTERNATE parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and ALTERNATE.

From there it will dig into the history of foo.

When you ask Git about the history of bar, it will:

  1. notice no change between MERGED and RESTORED,
  2. detect that bar came from the SAVED parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and SAVED.

From there it will dig into the history of foo.

It's that simple. :)

You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).

How to change the name of an iOS app?

  1. Go to Targets in Xcode.
  2. Get Info on your project's target (your current development name).
  3. Search for Product Name under Packaging. Change its value to what you want your new project name to be.

Count all occurrences of a string in lots of files with grep

You can use a simple grep to capture the number of occurrences effectively. I will use the -i option to make sure STRING/StrING/string get captured properly.

Command line that gives the files' name:

grep -oci string * | grep -v :0

Command line that removes the file names and prints 0 if there is a file without occurrences:

grep -ochi string *

Is there an "if -then - else " statement in XPath?

Personally, I would use XSLT to transform the XML and remove the trailing colons. For example, suppose I have this input:

<?xml version="1.0" encoding="UTF-8"?>
<Document>
    <Paragraph>This paragraph ends in a period.</Paragraph>
    <Paragraph>This one ends in a colon:</Paragraph>
    <Paragraph>This one has a : in the middle.</Paragraph>
</Document>

If I wanted to strip out trailing colons in my paragraphs, I would use this XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    version="2.0">
    <!-- identity -->
    <xsl:template match="/|@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <!-- strip out colons at the end of paragraphs -->
    <xsl:template match="Paragraph">
        <xsl:choose>
            <!-- if it ends with a : -->
            <xsl:when test="fn:ends-with(.,':')">
                <xsl:copy>
                    <!-- copy everything but the last character -->
                    <xsl:value-of select="substring(., 1, string-length(.)-1)"></xsl:value-of>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet> 

Determining image file size + dimensions via Javascript?

You can find dimension of an image on the page using something like

document.getElementById('someImage').width

file size, however, you will have to use something server-side

Proper way to handle multiple forms on one page in Django

view:

class AddProductView(generic.TemplateView):
template_name = 'manager/add_product.html'

    def get(self, request, *args, **kwargs):
    form = ProductForm(self.request.GET or None, prefix="sch")
    sub_form = ImageForm(self.request.GET or None, prefix="loc")
    context = super(AddProductView, self).get_context_data(**kwargs)
    context['form'] = form
    context['sub_form'] = sub_form
    return self.render_to_response(context)

def post(self, request, *args, **kwargs):
    form = ProductForm(request.POST,  prefix="sch")
    sub_form = ImageForm(request.POST, prefix="loc")
    ...

template:

{% block container %}
<div class="container">
    <br/>
    <form action="{% url 'manager:add_product' %}" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        {{ sub_form.as_p }}
        <p>
            <button type="submit">Submit</button>
        </p>
    </form>
</div>
{% endblock %}

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

I wrote this answer about four years ago and my opinion hasn't changed. But since then there have been significant developments on the micro-services front. I added micro-services specific notes at the end...

I'll weigh in against the idea, with real-world experience to back up my vote.

I was brought on to a large application that had five contexts for a single database. In the end, we ended up removing all of the contexts except for one - reverting back to a single context.

At first the idea of multiple contexts seems like a good idea. We can separate our data access into domains and provide several clean lightweight contexts. Sounds like DDD, right? This would simplify our data access. Another argument is for performance in that we only access the context that we need.

But in practice, as our application grew, many of our tables shared relationships across our various contexts. For example, queries to table A in context 1 also required joining table B in context 2.

This left us with a couple poor choices. We could duplicate the tables in the various contexts. We tried this. This created several mapping problems including an EF constraint that requires each entity to have a unique name. So we ended up with entities named Person1 and Person2 in the different contexts. One could argue this was poor design on our part, but despite our best efforts, this is how our application actually grew in the real world.

We also tried querying both contexts to get the data we needed. For example, our business logic would query half of what it needed from context 1 and the other half from context 2. This had some major issues. Instead of performing one query against a single context, we had to perform multiple queries across different contexts. This has a real performance penalty.

In the end, the good news is that it was easy to strip out the multiple contexts. The context is intended to be a lightweight object. So I don't think performance is a good argument for multiple contexts. In almost all cases, I believe a single context is simpler, less complex, and will likely perform better, and you won't have to implement a bunch of work-arounds to get it to work.

I thought of one situation where multiple contexts could be useful. A separate context could be used to fix a physical issue with the database in which it actually contains more than one domain. Ideally, a context would be one-to-one to a domain, which would be one-to-one to a database. In other words, if a set of tables are in no way related to the other tables in a given database, they should probably be pulled out into a separate database. I realize this isn't always practical. But if a set of tables are so different that you would feel comfortable separating them into a separate database (but you choose not to) then I could see the case for using a separate context, but only because there are actually two separate domains.

Regarding micro-services, one single context still makes sense. However, for micro-services, each service would have its own context which includes only the database tables relevant to that service. In other words, if service x accesses tables 1 and 2, and service y accesses tables 3 and 4, each service would have its own unique context which includes tables specific to that service.

I'm interested in your thoughts.

Forcing anti-aliasing using css: Is this a myth?

I found a fix...

.text {
            font-size: 15px;  /* for firefox */
            *font-size: 90%; /* % restart the antialiasing for ie, note the * hack */
            font-weight: bold; /* needed, don't know why! */
        }  

AppSettings get value from .config file

This works for me:

string value = System.Configuration.ConfigurationManager.AppSettings[key];

How to change UINavigationBar background color from the AppDelegate

You can set UINavigation Background color by using this code in any view controller

self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:10.0f/255.0f green:30.0f/255.0f blue:200.0f/255.0f alpha:1.0f];

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

Microsoft Excel mangles Diacritics in .csv files?

Check the encoding in which you are generating the file, to make excel display the file correctly you must use the system default codepage.

Wich language are you using? if it's .Net you only need to use Encoding.Default while generating the file.

How to update Ruby to 1.9.x on Mac?

This command actually works

\curl -L https://get.rvm.io | bash -s stable --ruby

How to show code but hide output in RMarkdown?

To hide warnings, you can also do {r, warning=FALSE}

How to run JUnit test cases from the command line

Actually you can also make the Junit test a runnable Jar and call the runnable jar as java -jar

expected assignment or function call: no-unused-expressions ReactJS

In my case, I got the error on the setState line:

increment(){
  this.setState(state => {
    count: state.count + 1
  });
}

I changed it to this, now it works

increment(){
  this.setState(state => {
    const count = state.count + 1

    return {
      count
    };
  });
}

JavaScript blob filename without link

Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.

function saveFile(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0)
  }
}

jsfiddle example

Django CSRF check failing with an Ajax POST request

The {% csrf_token %} put in html templates inside <form></form>

translates to something like:

<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />

so why not just grep it in your JS like this:

token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()

and then pass it e.g doing some POST, like:

$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
    console.log(data);
});

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

File loading by getClass().getResource()

The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

How do I fire an event when a iframe has finished loading in jQuery?

Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>, so we can do the check like this:

    window.onload = function () {


    //creating an iframe element
    var ifr = document.createElement('iframe');
    document.body.appendChild(ifr);

    // making the iframe fill the viewport
    ifr.width  = '100%';
    ifr.height = window.innerHeight;

    // continuously checking to see if the pdf file has been loaded
     self.interval = setInterval(function () {
        if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
            clearInterval(self.interval);

            console.log("loaded");
            //You can do print here: ifr.contentWindow.print();
        }
    }, 100); 

    ifr.src = src;
}

What is tail recursion?

The recursive function is a function which calls by itself

It allows programmers to write efficient programs using a minimal amount of code.

The downside is that they can cause infinite loops and other unexpected results if not written properly.

I will explain both Simple Recursive function and Tail Recursive function

In order to write a Simple recursive function

  1. The first point to consider is when should you decide on coming out of the loop which is the if loop
  2. The second is what process to do if we are our own function

From the given example:

public static int fact(int n){
  if(n <=1)
     return 1;
  else 
     return n * fact(n-1);
}

From the above example

if(n <=1)
     return 1;

Is the deciding factor when to exit the loop

else 
     return n * fact(n-1);

Is the actual processing to be done

Let me the break the task one by one for easy understanding.

Let us see what happens internally if I run fact(4)

  1. Substituting n=4
public static int fact(4){
  if(4 <=1)
     return 1;
  else 
     return 4 * fact(4-1);
}

If loop fails so it goes to else loop so it returns 4 * fact(3)

  1. In stack memory, we have 4 * fact(3)

    Substituting n=3

public static int fact(3){
  if(3 <=1)
     return 1;
  else 
     return 3 * fact(3-1);
}

If loop fails so it goes to else loop

so it returns 3 * fact(2)

Remember we called ```4 * fact(3)``

The output for fact(3) = 3 * fact(2)

So far the stack has 4 * fact(3) = 4 * 3 * fact(2)

  1. In stack memory, we have 4 * 3 * fact(2)

    Substituting n=2

public static int fact(2){
  if(2 <=1)
     return 1;
  else 
     return 2 * fact(2-1);
}

If loop fails so it goes to else loop

so it returns 2 * fact(1)

Remember we called 4 * 3 * fact(2)

The output for fact(2) = 2 * fact(1)

So far the stack has 4 * 3 * fact(2) = 4 * 3 * 2 * fact(1)

  1. In stack memory, we have 4 * 3 * 2 * fact(1)

    Substituting n=1

public static int fact(1){
  if(1 <=1)
     return 1;
  else 
     return 1 * fact(1-1);
}

If loop is true

so it returns 1

Remember we called 4 * 3 * 2 * fact(1)

The output for fact(1) = 1

So far the stack has 4 * 3 * 2 * fact(1) = 4 * 3 * 2 * 1

Finally, the result of fact(4) = 4 * 3 * 2 * 1 = 24

enter image description here

The Tail Recursion would be

public static int fact(x, running_total=1) {
    if (x==1) {
        return running_total;
    } else {
        return fact(x-1, running_total*x);
    }
}

  1. Substituting n=4
public static int fact(4, running_total=1) {
    if (x==1) {
        return running_total;
    } else {
        return fact(4-1, running_total*4);
    }
}

If loop fails so it goes to else loop so it returns fact(3, 4)

  1. In stack memory, we have fact(3, 4)

    Substituting n=3

public static int fact(3, running_total=4) {
    if (x==1) {
        return running_total;
    } else {
        return fact(3-1, 4*3);
    }
}

If loop fails so it goes to else loop

so it returns fact(2, 12)

  1. In stack memory, we have fact(2, 12)

    Substituting n=2

public static int fact(2, running_total=12) {
    if (x==1) {
        return running_total;
    } else {
        return fact(2-1, 12*2);
    }
}

If loop fails so it goes to else loop

so it returns fact(1, 24)

  1. In stack memory, we have fact(1, 24)

    Substituting n=1

public static int fact(1, running_total=24) {
    if (x==1) {
        return running_total;
    } else {
        return fact(1-1, 24*1);
    }
}

If loop is true

so it returns running_total

The output for running_total = 24

Finally, the result of fact(4,1) = 24

enter image description here

adding 30 minutes to datetime php/mysql

Use DATE_ADD function

DATE_ADD(datecolumn, INTERVAL 30 MINUTE);

Android Studio SDK location

Android Studio on Windows 8:

C:\Users\username\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm-android.exe

(in username : please enter valid username)

Install it and restart your Android Studio.

The above steps are similar for win 7 and also same for eclipse.

Update: Windows 10 (similar steps) - pointed out by RBT

Video streaming over websockets using JavaScript

To answer the question:

What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes, Websocket can be used to transmit over 30 fps and even 60 fps.

The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.

where is gacutil.exe?

gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe included. But first check it here

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

you might have it installed.

As @devi mentioned

If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

iOS 6 apps - how to deal with iPhone 5 screen size?

No.

if ([[UIScreen mainScreen] bounds].size.height > 960)

on iPhone 5 is wrong

if ([[UIScreen mainScreen] bounds].size.height == 568)

How to get cookie's expire time

You can set your cookie value containing expiry and get your expiry from cookie value.

// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);

// get
if (isset($_COOKIE["mycookie"])) {
  list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}

// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee

Pandas percentage of total with groupby

You need to make a second groupby object that groups by the states, and then use the div method:

import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)]})

state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100


                     sales
state office_id           
AZ    2          16.981365
      4          19.250033
      6          63.768601
CA    1          19.331879
      3          33.858747
      5          46.809373
CO    1          36.851857
      3          19.874290
      5          43.273852
WA    2          34.707233
      4          35.511259
      6          29.781508

the level='state' kwarg in div tells pandas to broadcast/join the dataframes base on the values in the state level of the index.

Unable to verify leaf signature

You can also try by setting strictSSL to false, like this:

{  
   url: "https://...",
   method: "POST",
   headers: {
        "Content-Type": "application/json"},
   strictSSL: false
}

Converting java.util.Properties to HashMap<String,String>

How about this?

   Map properties = new Properties();
   Map<String, String> map = new HashMap<String, String>(properties);

Will cause a warning, but works without iterations.

MongoDB Show all contents from all collections

var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){    
   print('Collection: ' + collections[i]); // print the name of each collection
   db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}

I think this script might get what you want. It prints the name of each collection and then prints its elements in json.

Adding placeholder attribute using Jquery

This line of code might not work in IE 8 because of native support problems.

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.

$('input, textarea').placeholder();

Getting "type or namespace name could not be found" but everything seems ok?

I know its old, but I've found the same issue. My project did build, I then updated Visual Studio to the latest & the project wouldnt build as it couldnt find a type definition from a separate assembly. The other assembly built OK, the main project referenced it correctly & nothing had changed since it built OK.

I cleaned the whole solution & rebuilt it, it failed. I built the assembly on its own, it built OK. The project didnt build. I cleaned & built multiple times, and it failed. I then called a colleague to look at it, when I built with him watching, it all built OK.

I think Visual Studio tooling is the problem, especially as I just updated it.

Search for all occurrences of a string in a mysql database

I was looking for this myself when we changed domain on our Wordpress website. It can't be done without some programming so this is what I did.

<?php  
  header("Content-Type: text/plain");

  $host = "localhost";
  $username = "root";
  $password = "";
  $database = "mydatabase";
  $string_to_replace  = 'old.example.com';
  $new_string = 'new.example.com';

  // Connect to database server
  mysql_connect($host, $username, $password);

  // Select database
  mysql_select_db($database);

  // List all tables in database
  $sql = "SHOW TABLES FROM ".$database;
  $tables_result = mysql_query($sql);

  if (!$tables_result) {
    echo "Database error, could not list tables\nMySQL error: " . mysql_error();
    exit;
  }

  echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
  while ($table = mysql_fetch_row($tables_result)) {
    echo "Table: {$table[0]}\n";
    $fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
    if (!$fields_result) {
      echo 'Could not run query: ' . mysql_error();
      exit;
    }
    if (mysql_num_rows($fields_result) > 0) {
      while ($field = mysql_fetch_assoc($fields_result)) {
        if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
          echo "  ".$field['Field']."\n";
          $sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
          mysql_query($sql);
        }
      }
      echo "\n";
    }
  }

  mysql_free_result($tables_result);  
?>

Hope it helps anyone who's stumbling into this problem in the future :)

How to test valid UUID/GUID?

Currently, UUID's are as specified in RFC4122. An often neglected edge case is the NIL UUID, noted here. The following regex takes this into account and will return a match for a NIL UUID. See below for a UUID which only accepts non-NIL UUIDs. Both of these solutions are for versions 1 to 5 (see the first character of the third block).

Therefore to validate a UUID...

/^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i

...ensures you have a canonically formatted UUID that is Version 1 through 5 and is the appropriate Variant as per RFC4122.

NOTE: Braces { and } are not canonical. They are an artifact of some systems and usages.

Easy to modify the above regex to meet the requirements of the original question.

HINT: regex group/captures

To avoid matching NIL UUID:

/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

git returns http error 407 from proxy after CONNECT

Had the 407 error from Android Studio. Tried adding the proxy, but nothing happened. Found out that it was related to company certificate, so I exported the one from my browser and added it to Git.

Export From Web Browser

Internet Options > Content > Certificates > Export (Follow wizard, I chose format "Base 64 encoded X.509(.CER))

In Git Bash

git config --global http.sslCAInfo c:\Utilities\Certificates\my_certificate

The following page was useful https://blogs.msdn.microsoft.com/phkelley/2014/01/20/adding-a-corporate-or-self-signed-certificate-authority-to-git-exes-store/

To add the proxy, like the other threads I used

git config --global http.proxy proxy.company.net:8080
git config --global https.proxy proxy.company.net:8080

How to initialize a list of strings (List<string>) with many string values

List<string> mylist = new List<string>(new string[] { "element1", "element2", "element3" });

How to add external fonts to android application

Create a folder named fonts in the assets folder and add the snippet from the below link.

Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);

Javascript call() & apply() vs bind()?

They all attach this into function (or object) and the difference is in the function invocation (see below).

call attaches this into function and executes the function immediately:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

person.hello("world");  // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"

bind attaches this into function and it needs to be invoked separately like this:

var person = {  
  name: "James Smith",
  hello: function(thing) {
    console.log(this.name + " says hello " + thing);
  }
}

person.hello("world");  // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world");  // output: Jim Smith says hello world"

or like this:

...    
var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
helloFunc();  // output: Jim Smith says hello world"

apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:

function personContainer() {
  var person = {  
     name: "James Smith",
     hello: function() {
       console.log(this.name + " says hello " + arguments[1]);
     }
  }
  person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"                                     

Adjust icon size of Floating action button (fab)

Make this entry in dimens

<!--Floating action button-->
<dimen name="design_fab_image_size" tools:override="true">36dp</dimen>

Here 36dp is icon size on floating point button. This will set 36dp size for all icons for floating action button.

Updates As Per Comments

If you want to set icon size to particular Floating Action Button just go with Floating action button attributes like app:fabSize="normal" and android:scaleType="center".

  <!--app:fabSize decides size of floating action button You can use normal, auto or mini as per need-->
  app:fabSize="normal" 

  <!--android:scaleType decides how the icon drawable will be scaled on Floating action button. You can use center(to show scr image as original), fitXY, centerCrop, fitCenter, fitEnd, fitStart, centerInside.-->
  android:scaleType="center"

Table with fixed header and fixed column on pure css

Pure CSS Example:

<div id="cntnr">
    <div class="tableHeader">
        <table class="table-header table table-striped table-bordered">
            <thead>
                <tr>
                    <th>this</th>
                    <th>transmission</th>
                    <th>is</th>
                    <th>coming</th>
                    <th>to</th>
                    <th>you</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                </tr>
            </tbody>
        </table>
    </div>


    <div class="tableBody">
        <table class="table-body table table-striped table-bordered">
            <thead>
                <tr>
                    <th>this</th>
                    <th>transmission</th>
                    <th>is</th>
                    <th>coming</th>
                    <th>to</th>
                    <th>you</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                    <td>we've got it...</td>
                    <td>alright you are go</td>
                    <td>uh, we see the Earth now</td>
                </tr>
            </tbody>
        </table>
    </div>

</div>

#cntnr {
    width: auto;
    height: 200px;
    border: solid 1px #444;
    overflow: auto;
}

.tableHeader {
    position: fixed;
    height: 40px;
    overflow: hidden;
    margin-right: 18px;
    background: white;
}

.table-header tbody {
    height: 0;
    visibility: hidden;
}

.table-body thead {
    height: 0;
    visibility: hidden;
}

http://jsfiddle.net/cCarlson/L98m854d/

Drawback: The fixed header structure/logic is fairly dependent upon specific dimensions, so abstraction is probably not a viable option.

How can I completely uninstall nodejs, npm and node in Ubuntu

It bothered me too much while updating node version from 8.1.0 to 10.14.0

Here is what worked for me:

  1. Open terminal (Ctrl+Alt+T).

  2. Type which node, which will give a path something like /usr/local/bin/node

  3. Run the command sudo rm /usr/local/bin/node to remove the binary (adjust the path according to what you found in step 2). Now node -v shows you have no node version

  4. Download a script and run it to set up the environment:

    curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
    
  5. Install using sudo apt-get install nodejs

    Note: If you are getting error like

    node /usr/bin/env: node: No such file or directory
    

    just run

    ln -s /usr/bin/nodejs /usr/bin/node
    

    Source

  6. Now node -v will give v10.14.0

Worked for me.

jquery: $(window).scrollTop() but no $(window).scrollBottom()

var scrollBottom = $(window).scrollTop() + $(window).height();

SQL Not Like Statement not working

Is the value of your particular COMMENT column null?

Sometimes NOT LIKE doesn't know how to behave properly around nulls.

PHP Warning: Invalid argument supplied for foreach()

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

ls command: how can I get a recursive full-path listing, one line per file?

If the directory is passed as a relative path and you will need to convert it to an absolute path before calling find. In the following example, the directory is passed as the first parameter to the script:

#!/bin/bash

# get absolute path
directory=`cd $1; pwd`
# print out list of files and directories
find $directory

Remove scrollbars from textarea

Hide scroll bar, but while still being able to scroll using CSS

To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:

    -webkit- (Chrome, Safari, newer versions of Opera):
    .element::-webkit-scrollbar { width: 0 !important }
    -moz- (Firefox):
    .element { overflow: -moz-scrollbars-none; }
    -ms- (Internet Explorer +10):
    .element { -ms-overflow-style: none; }

ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

Is HTML considered a programming language?

If you're going to say that HTML is a programming language, then you might as well include things such as word documents, as they too are based on ML, or 'Markup Language'.

So, no, HTML is a not a programming language. It is called "markup" for that reason.

Simply put--HTML defines content!

How do I specify unique constraint for multiple columns in MySQL?

If You are creating table in mysql then use following :

create table package_template_mapping (
mapping_id  int(10) not null auto_increment  ,
template_id int(10) NOT NULL ,
package_id  int(10) NOT NULL ,
remark      varchar(100),
primary key (mapping_id) ,
UNIQUE KEY template_fun_id (template_id , package_id)
);

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

jQuery: Currency Format Number

There is a plugin for that, jquery-formatcurrency.

You can set the decimal separator (default .) and currency symbol (default $) for custom formatting or use the built in International Support. The format for Bahasa Indonesia (Indonesia) - Indonesian (Indonesia) coded id-ID looks closest to what you have provided.

Get value from a string after a special character

Here's a way:

<html>
    <head>
        <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var value = $('input[type="hidden"]')[0].value;
                alert(value.split(/\?/)[1]);
            });
        </script>
    </head>
    <body>
        <input type="hidden" value="/TEST/Name?3" />
    </body>
</html>

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

Adding an onclicklistener to listview (android)

If your Activity extends ListActivity, you can simply override the OnListItemClick() method like so:

/** {@inheritDoc} */
@Override  
protected void onListItemClick(ListView l, View v, int pos, long id) {  
    super.onListItemClick(l, v, pos, id);

    // TODO : Logic
}  

Declare a const array

Arrays are probably one of those things that can only be evaluated at runtime. Constants must be evaluated at compile time. Try using "readonly" instead of "const".

Regular expression to match URLs in Java

((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+

check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output

It sorts out theses entries correctly

How can I tell gcc not to inline a function?

You want the gcc-specific noinline attribute.

This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put asm ("");

Use it like this:

void __attribute__ ((noinline)) foo() 
{
  ...
}

How to connect HTML Divs with Lines?

You can use SVGs to connect two divs using only HTML and CSS:

<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>
<div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>

(please use seperate css file for styling)

Create a svg line and use this line to connect above divs

<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>

where,

x1,y1 indicates center of first div and
x2,y2 indicates center of second div

You can check how it looks in the snippet below

_x000D_
_x000D_
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>_x000D_
<div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>_x000D_
_x000D_
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>
_x000D_
_x000D_
_x000D_

C# delete a folder and all files and folders within that folder

Err, what about just calling Directory.Delete(path, true); ?

List tables in a PostgreSQL schema

Alternatively to information_schema it is possible to use pg_tables:

select * from pg_tables where schemaname='public';

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

Get the current year in JavaScript

Such is how I have it embedded and outputted to my HTML web page:

<div class="container">
    <p class="text-center">Copyright &copy; 
        <script>
            var CurrentYear = new Date().getFullYear()
            document.write(CurrentYear)
        </script>
    </p>
</div>

Output to HTML page is as follows:

Copyright © 2018

How to display a list using ViewBag

Just put a

 List<Person>

into the ViewBag and in the View cast it back to List

Check if a column contains text using SQL

Try LIKE construction, e.g. (assuming StudentId is of type Char, VarChar etc.)

  select * 
    from Students
   where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain

Find an item in List by LINQ?

Do you want the item in the list or the actual item itself (would assume the item itself).

Here are a bunch of options for you:

string result = _list.First(s => s == search);

string result = (from s in _list
                 where s == search
                 select s).Single();

string result = _list.Find(search);

int result = _list.IndexOf(search);

How to make a div center align in HTML

I think that the the align="center" aligns the content, so if you wanted to use that method, you would need to use it in a 'wraper' div - a div that just wraps the rest.

text-align is doing a similar sort of thing.

left:50% is ignored unless you set the div's position to be something like relative or absolute.

The generally accepted methods is to use the following properties

width:500px; // this can be what ever unit you want, you just have to define it
margin-left:auto;
margin-right:auto;

the margins being auto means they grow/shrink to match the browser window (or parent div)

UPDATE

Thanks to Meo for poiting this out, if you wanted to you could save time and use the short hand propery for the margin.

margin:0 auto;

this defines the top and bottom as 0 (as it is zero it does not matter about lack of units) and the left and right get defined as 'auto' You can then, if you wan't override say the top margin as you would with any other CSS rules.

How can I get color-int from color resource?

Most Recent working method:

getColor(R.color.snackBarAction)

What's the difference between lists and tuples?

Lists are mutable. whereas tuples are immutable. Accessing an offset element with index makes more sense in tuples than lists, Because the elements and their index cannot be changed.

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

use this method before show

public static ViewGroup getActivityFirstLayout(Context ctx)
{
    return (ViewGroup)((ViewGroup) ActivityMaster.getActivity(ctx).findViewById(android.R.id.content)).getChildAt(0);
}

private boolean activityIsOk(Activity activity)
{
    boolean s1 = !(activity == null || activity.isFinishing());

    if(s1)
    {
        View v = LayoutMaster.getActivityFirstLayout(activity);
        return v.isShown() && ViewCompat.isLaidOut(v);
    }

    return false;
}

Rollback a Git merge

From here:

http://www.christianengvall.se/undo-pushed-merge-git/

git revert -m 1 <merge commit hash>

Git revert adds a new commit that rolls back the specified commit.

Using -m 1 tells it that this is a merge and we want to roll back to the parent commit on the master branch. You would use -m 2 to specify the develop branch.

What's the difference between identifying and non-identifying relationships?

Like well explained in the link below, an identifying relation is somewhat like a weak entity type relation to its parent in the ER conceptual model. UML style CADs for data modeling do not use ER symbols or concepts, and the kind of relations are: identifying, non-identifying and non-specific.

Identifying ones are relations parent/child where the child is kind of a weak entity (even at the traditional ER model its called identifying relationship), which does not have a real primary key by its own attributes and therefore cannot be identified uniquely by its own. Every access to the child table, on the physical model, will be dependent (inclusive semantically) on the parent's primary key, which turns into part or total of the child's primary key (also being a foreign key), generally resulting in a composite key on the child side. The eventual existing keys of the child itself are only pseudo or partial-keys, not sufficient to identify any instance of that type of Entity or Entity Set, without the parent's PK.

Non-identifying relationship are the ordinary relations (partial or total), of completely independent entity sets, whose instances do not depend on each others' primary keys to be uniquely identified, although they might need foreign keys for partial or total relationships, but not as the primary key of the child. The child has its own primary key. The parent idem. Both independently. Depending on the cardinality of the relationship, the PK of one goes as a FK to the other (N side), and if partial, can be null, if total, must be not null. But, at a relationship like this, the FK will never be also the PK of the child, as when an identifying relationship is the case.

http://docwiki.embarcadero.com/ERStudioDA/XE7/en/Creating_and_Editing_Relationships

Get img src with PHP

I have done that the more simple way, not as clean as it should be but it was a quick hack

$htmlContent = file_get_contents('pageURL');

// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags); 

for ($i = 0; $i < count($imgTags[0]); $i++) {
  // get the source string
  preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);

  // remove opening 'src=' tag, can`t get the regex right
  $origImageSrc[] = str_ireplace( 'src="', '',  $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);

JavaScript: Get image dimensions

var img = new Image();

img.onload = function(){
  var height = img.height;
  var width = img.width;

  // code here to use the dimensions
}

img.src = url;

calling another method from the main method in java

If you want to use do() in your main method there are 2 choices because one is static but other (do()) not

  1. Create new instance and invoke do() like new Foo().do();
  2. make static do() method

Have a look at this sun tutorial

Extracting double-digit months and days from a Python date

you can use a string formatter to pad any integer with zeros. It acts just like C's printf.

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

Updated for py36: Use f-strings! For general ints you can use the d formatter and explicitly tell it to pad with zeros:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

But datetimes are special and come with special formatters that are already zero padded:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

"java.lang.OutOfMemoryError : unable to create new native Thread"

I would recommend to also look at the Thread Stack Size and see if you get more threads created. The default Thread Stack Size for JRockit 1.5/1.6 is 1 MB for 64-bit VM on Linux OS. 32K threads will require a significant amount of physical and virtual memory to honor this requirement.

Try to reduce the Stack Size to 512 KB as a starting point and see if it helps creating more threads for your application. I also recommend to explore horizontal scaling e.g. splitting your application processing across more physical or virtual machines.

When using a 64-bit VM, the true limit will depend on the OS physical and virtual memory availability and OS tuning parameters such as ulimitc. I also recommend the following article as a reference:

OutOfMemoryError: unable to create new native thread – Problem Demystified

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

instead of localhost of '0.0.0.0', use local network address as host in case of both - the server and the client - code.

host = '192.168.12.12' port = 12345

use this host address when binding and connecting to the socket.

server.bind((host, port)) client.connect((host, port))

this change solved the issue for me.

Finishing current activity from a fragment

Well actually...

I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html

Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.

How to set a time zone (or a Kind) of a DateTime value?

If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();

If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);

List of available timezones

TimeZoneInfo class on MSDN

JPA: unidirectional many-to-one and cascading delete

@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Given annotation worked for me. Can have a try

For Example :-

     public class Parent{
            @Id
            @GeneratedValue(strategy=GenerationType.AUTO)
            @Column(name="cct_id")
            private Integer cct_id;
            @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
            @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
            private List<Child> childs;
        }
            public class Child{
            @ManyToOne(fetch=FetchType.EAGER)
            @JoinColumn(name="cct_id")
            private Parent parent;
    }

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

pop/remove items out of a python tuple

As DSM mentions, tuple's are immutable, but even for lists, a more elegant solution is to use filter:

tupleX = filter(str.isdigit, tupleX)

or, if condition is not a function, use a comprehension:

tupleX = [x for x in tupleX if x > 5]

if you really need tupleX to be a tuple, use a generator expression and pass that to tuple:

tupleX = tuple(x for x in tupleX if condition)

Change Bootstrap input focus blue glow

In Bootstrap 3.3.7 you can change the @input-border-focus value in the Forms section of the customizer: enter image description here

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

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

Bootstrap 3 modal responsive

You should be able to adjust the width using the .modal-dialog class selector (in conjunction with media queries or whatever strategy you're using for responsive design):

.modal-dialog {
    width: 400px;
}

How to get named excel sheets while exporting from SSRS

There is no direct way. You either export XML and then right an XSLT to format it properly (this is the hard way). An easier way is to write multiple reports with no explicit page breaks so each exports into one sheet only in excel and then write a script that would merge for you. Either way it requires a postprocessing step.

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


In Chrome or Opera, open a new tab and navigate to chrome://view-http-cache/

Click on whichever file you want to view. You should then see a page with a bunch of text and numbers. Copy all the text on that page. Paste it in the text box below.

Press "Go". The cached data will appear in the Results section below.