Programs & Examples On #Matcher

Matchers are objects used among other things by testing libraries to check, if an object matches an abstract description of an expected state. Do not use this tag for use of the Matcher class for regular expression matching, use [regex] instead.

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

Mockito match any class argument

If you have no idea which Package you need to import:

import static org.mockito.ArgumentMatchers.any;
any(SomeClass.class)

OR

import org.mockito.ArgumentMatchers;
ArgumentMatchers.any(SomeClass.class)

How to create a directory if it doesn't exist using Node.js?

The best solution would be to use the npm module called node-fs-extra. It has a method called mkdir which creates the directory you mentioned. If you give a long directory path, it will create the parent folders automatically. The module is a super set of npm module fs, so you can use all the functions in fs also if you add this module.

What is the behavior difference between return-path, reply-to and from?

I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.

Cross-Origin Request Headers(CORS) with PHP headers

add this code in .htaccess

add custom authentication key's in header like app_key,auth_key..etc

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers: "customKey1,customKey2, headers, Origin, X-Requested-With, Content-Type, Accept, Authorization"

How to install Java SDK on CentOS?

If you want the Oracle JDK and are willing not to use yum/rpm, see this answer here:

Downloading Java JDK on Linux via wget is shown license page instead

As per that post, you can automate the download of the tarball using curl and specifying a cookie header.

Then you can put the tarball contents in the right place and add java to your PATH, for example:

curl -v -j -k -L -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.tar.gz > jdk.tar.gz

tar xzvf jdk.tar.gz
sudo mkdir /usr/local/java
sudo mv jdk1.8.0_45 /usr/local/java/
sudo ln -s /usr/local/java/jdk1.8.0_45 /usr/local/java/jdk

sudo vi /etc/profile.d/java.sh
export PATH="$PATH:/usr/local/java/jdk/bin"
export JAVA_HOME=/usr/local/java/jdk

source /etc/profile.d/java.sh

How to write a large buffer into a binary file in C++, fast?

I see no difference between std::stream/FILE/device. Between buffering and non buffering.

Also note:

  • SSD drives "tend" to slow down (lower transfer rates) as they fill up.
  • SSD drives "tend" to slow down (lower transfer rates) as they get older (because of non working bits).

I am seeing the code run in 63 secondds.
Thus a transfer rate of: 260M/s (my SSD look slightly faster than yours).

64 * 1024 * 1024 * 8 /*sizeof(unsigned long long) */ * 32 /*Chunks*/

= 16G
= 16G/63 = 260M/s

I get a no increase by moving to FILE* from std::fstream.

#include <stdio.h>

using namespace std;

int main()
{
    
    FILE* stream = fopen("binary", "w");

    for(int loop=0;loop < 32;++loop)
    {
         fwrite(a, sizeof(unsigned long long), size, stream);
    }
    fclose(stream);

}

So the C++ stream are working as fast as the underlying library will allow.

But I think it is unfair comparing the OS to an application that is built on-top of the OS. The application can make no assumptions (it does not know the drives are SSD) and thus uses the file mechanisms of the OS for transfer.

While the OS does not need to make any assumptions. It can tell the types of the drives involved and use the optimal technique for transferring the data. In this case a direct memory to memory transfer. Try writing a program that copies 80G from 1 location in memory to another and see how fast that is.

Edit

I changed my code to use the lower level calls:
ie no buffering.

#include <fcntl.h>
#include <unistd.h>


const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    int data = open("test", O_WRONLY | O_CREAT, 0777);
    for(int loop = 0; loop < 32; ++loop)
    {   
        write(data, a, size * sizeof(unsigned long long));
    }   
    close(data);
}

This made no diffference.

NOTE: My drive is an SSD drive if you have a normal drive you may see a difference between the two techniques above. But as I expected non buffering and buffering (when writting large chunks greater than buffer size) make no difference.

Edit 2:

Have you tried the fastest method of copying files in C++

int main()
{
    std::ifstream  input("input");
    std::ofstream  output("ouptut");

    output << input.rdbuf();
}

How to redirect single url in nginx?

location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}

Removing carriage return and new-line from the end of a string in c#

If you are using multiple platforms you are safer using this method.

value.TrimEnd(System.Environment.NewLine.ToCharArray());

It will account for different newline and carriage-return characters.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The problem has been resolved by running the following in elevated command prompt:

command :

cd C:\Windows\System32\
regtlib msdatsrc.tlb

or

cd C:\Windows\SysWOW64\
regtlib msdatsrc.tlb

I hope this helps.

Inner join with count() on three tables

Your solution is nearly correct. You could add DISTINCT:

SELECT
    people.pe_name,
    COUNT(distinct orders.ord_id) AS num_orders,
    COUNT(items.item_id) AS num_items
FROM
    people
    INNER JOIN orders ON (orders.pe_id = people.pe_id)
    INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
    people.pe_id;

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

By default, np.genfromtxt uses dtype=float: that's why you string columns are converted to NaNs because, after all, they're Not A Number...

You can ask np.genfromtxt to try to guess the actual type of your columns by using dtype=None:

>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])

You can access the columns by using their name, like a['f0']...

Using dtype=None is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use

>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)], 
      dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])

Using an explicit dtype is much more efficient than using dtype=None and is the recommended way.

In both cases (dtype=None or explicit, non-homogeneous dtype), you end up with a structured array.

[Note: With dtype=None, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

Android open pdf file

Kotlin version below (Updated version of @paul-burke response:

fun openPDFDocument(context: Context, filename: String) {
    //Create PDF Intent
    val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
    val pdfIntent = Intent(Intent.ACTION_VIEW)
    pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    //Create Viewer Intent
    val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
    context.startActivity(viewerIntent)
}

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

Show/Hide Div on Scroll

Here is my answer when you want to animate it and start fading it out after couple of seconds. I used opacity because first of all i didn't want to fade it out completely, second, it does not go back and force after many scrolls.

$(window).scroll(function () {
    var elem = $('div');
    setTimeout(function() {
        elem.css({"opacity":"0.2","transition":"2s"});
    },4000);            
    elem.css({"opacity":"1","transition":"1s"});    
});

Angular JS Uncaught Error: [$injector:modulerr]

The problem was caused by missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>

var app = angular.module('myapp', ['ngRoute']);

This is getting reference from: AngularJS 1.2 $injector:modulerr David answer

"Repository does not have a release file" error

If a sudo apt-get update did not do it for you, it might be that some packages have failed to updated to repository-related errors.

For me all of those happened to reside in (Software Updates --> Other Software). You could remove them with "Remove", the cache will be refreshed successfully. Otherwise

sudo apt-get clean
apt-get autoremove 

is something to try.

CLEAR SCREEN - Oracle SQL Developer shortcut?

Use the following command to clear screen in sqlplus.

SQL > clear scr 

Vlookup referring to table data in a different sheet

Copy =VLOOKUP(M3,A$2:Q$47,13,FALSE) to other sheets, then search for ! replace by !$, search for : replace by :$ one time for all sheets

Get JSON data from external URL and display it in a div as plain text

Here is one without using JQuery with pure JavaScript. I used javascript promises and XMLHttpRequest You can try it here on this fiddle

HTML

<div id="result" style="color:red"></div>

JavaScript

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

getJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan').then(function(data) {
    alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
  alert('Something went wrong.');
});

How to git clone a specific tag

Cloning a specific tag, might return 'detached HEAD' state.

As a workaround, try to clone the repo first, and then checkout a specific tag. For example:

repo_url=https://github.com/owner/project.git
repo_dir=$(basename $repo_url .git)
repo_tag=0.5

git clone --single-branch $repo_url # using --depth 1 can show no tags
git --work-tree=$repo_dir --git-dir=$repo_dir/.git checkout tags/$repo_tag

Note: Since Git 1.8.5, you can use -C <path>, instead of --work-tree and --git-dir.

How to get Selected Text from select2 when using <input>

As of Select2 4.x, it always returns an array, even for non-multi select lists.

var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);

For Select2 3.x and lower

Single select:

var data = $('your-original-element').select2('data');
if(data) {
  alert(data.text);
}

Note that when there is no selection, the variable 'data' will be null.

Multi select:

var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
alert(data[1].text);
alert(data[1].id);

From the 3.x docs:

data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.

data method invoked on a single-select with an unset value will return null, while a data method invoked on an empty multi-select will return [].

File size exceeds configured limit (2560000), code insight features not available

PhpStorm 2020

  1. Help -> Edit Custom Properties.
  2. File will open in Editor. Paste the section below to the file.
 #---------------------------------------------------------------------
 # Maximum file size (kilobytes) IDE should provide code assistance for.
 # The larger file is the slower its editor works and higher overall system memory 
 requirements are
 # if code assistance is enabled. Remove this property or set to very large number 
 if you need
 # code assistance for any files available regardless their size.
 #---------------------------------------------------------------------
 idea.max.intellisense.filesize=2500
  1. File -> Invalidate / Restart -> Restart

This might not update sometimes and you might need to edit the root idea.properties file.

To edit this file for any version of Idea

  1. Go to application location i.e linux => /opt/PhpStorm[version]/bin
  2. Find file called idea.properties Make backup of file i.e idea.properties.old
  3. Open original with any txt editor.
  4. Find idea.max.intellisense.filesize=
  5. Replace with idea.max.intellisense.filesize=your_required_size i.e idea.max.intellisense.filesize=10480 NB by default this size is in kb
  6. Save and restart the IDE.

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

HRESULT E_FAIL has been returned from a call to a COM component

In my case, it was because i had differents projects with same GUID in my solution. (Project was created by copy/paste)

"Thinking in AngularJS" if I have a jQuery background?

AngularJS vs. jQuery

AngularJS and jQuery adopt very different ideologies. If you're coming from jQuery you may find some of the differences surprising. Angular may make you angry.

This is normal, you should push through. Angular is worth it.

The big difference (TLDR)

jQuery gives you a toolkit for selecting arbitrary bits of the DOM and making ad-hoc changes to them. You can do pretty much anything you like piece by piece.

AngularJS instead gives you a compiler.

What this means is that AngularJS reads your entire DOM from top to bottom and treats it as code, literally as instructions to the compiler. As it traverses the DOM, It looks for specific directives (compiler directives) that tell the AngularJS compiler how to behave and what to do. Directives are little objects full of JavaScript which can match against attributes, tags, classes or even comments.

When the Angular compiler determines that a piece of the DOM matches a particular directive, it calls the directive function, passing it the DOM element, any attributes, the current $scope (which is a local variable store), and some other useful bits. These attributes may contain expressions which can be interpreted by the Directive, and which tell it how to render, and when it should redraw itself.

Directives can then in turn pull in additional Angular components such as controllers, services, etc. What comes out the bottom of the compiler is a fully formed web application, wired up and ready to go.

This means that Angular is Template Driven. Your template drives the JavaScript, not the other way around. This is a radical reversal of roles, and the complete opposite of the unobtrusive JavaScript we have been writing for the last 10 years or so. This can take some getting used to.

If this sounds like it might be over-prescriptive and limiting, nothing could be farther from the truth. Because AngularJS treats your HTML as code, you get HTML level granularity in your web application. Everything is possible, and most things are surprisingly easy once you make a few conceptual leaps.

Let's get down to the nitty gritty.

First up, Angular doesn't replace jQuery

Angular and jQuery do different things. AngularJS gives you a set of tools to produce web applications. jQuery mainly gives you tools for modifying the DOM. If jQuery is present on your page, AngularJS will use it automatically. If it isn't, AngularJS ships with jQuery Lite, which is a cut down, but still perfectly usable version of jQuery.

Misko likes jQuery and doesn't object to you using it. However you will find as you advance that you can get a pretty much all of your work done using a combination of scope, templates and directives, and you should prefer this workflow where possible because your code will be more discrete, more configurable, and more Angular.

If you do use jQuery, you shouldn't be sprinkling it all over the place. The correct place for DOM manipulation in AngularJS is in a directive. More on these later.

Unobtrusive JavaScript with Selectors vs. Declarative Templates

jQuery is typically applied unobtrusively. Your JavaScript code is linked in the header (or the footer), and this is the only place it is mentioned. We use selectors to pick out bits of the page and write plugins to modify those parts.

The JavaScript is in control. The HTML has a completely independent existence. Your HTML remains semantic even without JavaScript. Onclick attributes are very bad practice.

One of the first things your will notice about AngularJS is that custom attributes are everywhere. Your HTML will be littered with ng attributes, which are essentially onClick attributes on steroids. These are directives (compiler directives), and are one of the main ways in which the template is hooked to the model.

When you first see this you might be tempted to write AngularJS off as old school intrusive JavaScript (like I did at first). In fact, AngularJS does not play by those rules. In AngularJS, your HTML5 is a template. It is compiled by AngularJS to produce your web page.

This is the first big difference. To jQuery, your web page is a DOM to be manipulated. To AngularJS, your HTML is code to be compiled. AngularJS reads in your whole web page and literally compiles it into a new web page using its built in compiler.

Your template should be declarative; its meaning should be clear simply by reading it. We use custom attributes with meaningful names. We make up new HTML elements, again with meaningful names. A designer with minimal HTML knowledge and no coding skill can read your AngularJS template and understand what it is doing. He or she can make modifications. This is the Angular way.

The template is in the driving seat.

One of the first questions I asked myself when starting AngularJS and running through the tutorials is "Where is my code?". I've written no JavaScript, and yet I have all this behaviour. The answer is obvious. Because AngularJS compiles the DOM, AngularJS is treating your HTML as code. For many simple cases it's often sufficient to just write a template and let AngularJS compile it into an application for you.

Your template drives your application. It's treated as a DSL. You write AngularJS components, and AngularJS will take care of pulling them in and making them available at the right time based on the structure of your template. This is very different to a standard MVC pattern, where the template is just for output.

It's more similar to XSLT than Ruby on Rails for example.

This is a radical inversion of control that takes some getting used to.

Stop trying to drive your application from your JavaScript. Let the template drive the application, and let AngularJS take care of wiring the components together. This also is the Angular way.

Semantic HTML vs. Semantic Models

With jQuery your HTML page should contain semantic meaningful content. If the JavaScript is turned off (by a user or search engine) your content remains accessible.

Because AngularJS treats your HTML page as a template. The template is not supposed to be semantic as your content is typically stored in your model which ultimately comes from your API. AngularJS compiles your DOM with the model to produce a semantic web page.

Your HTML source is no longer semantic, instead, your API and compiled DOM are semantic.

In AngularJS, meaning lives in the model, the HTML is just a template, for display only.

At this point you likely have all sorts of questions concerning SEO and accessibility, and rightly so. There are open issues here. Most screen readers will now parse JavaScript. Search engines can also index AJAXed content. Nevertheless, you will want to make sure you are using pushstate URLs and you have a decent sitemap. See here for a discussion of the issue: https://stackoverflow.com/a/23245379/687677

Separation of concerns (SOC) vs. MVC

Separation of concerns (SOC) is a pattern that grew up over many years of web development for a variety of reasons including SEO, accessibility and browser incompatibility. It looks like this:

  1. HTML - Semantic meaning. The HTML should stand alone.
  2. CSS - Styling, without the CSS the page is still readable.
  3. JavaScript - Behaviour, without the script the content remains.

Again, AngularJS does not play by their rules. In a stroke, AngularJS does away with a decade of received wisdom and instead implements an MVC pattern in which the template is no longer semantic, not even a little bit.

It looks like this:

  1. Model - your models contains your semantic data. Models are usually JSON objects. Models exist as attributes of an object called $scope. You can also store handy utility functions on $scope which your templates can then access.
  2. View - Your views are written in HTML. The view is usually not semantic because your data lives in the model.
  3. Controller - Your controller is a JavaScript function which hooks the view to the model. Its function is to initialise $scope. Depending on your application, you may or may not need to create a controller. You can have many controllers on a page.

MVC and SOC are not on opposite ends of the same scale, they are on completely different axes. SOC makes no sense in an AngularJS context. You have to forget it and move on.

If, like me, you lived through the browser wars, you might find this idea quite offensive. Get over it, it'll be worth it, I promise.

Plugins vs. Directives

Plugins extend jQuery. AngularJS Directives extend the capabilities of your browser.

In jQuery we define plugins by adding functions to the jQuery.prototype. We then hook these into the DOM by selecting elements and calling the plugin on the result. The idea is to extend the capabilities of jQuery.

For example, if you want a carousel on your page, you might define an unordered list of figures, perhaps wrapped in a nav element. You might then write some jQuery to select the list on the page and restyle it as a gallery with timeouts to do the sliding animation.

In AngularJS, we define directives. A directive is a function which returns a JSON object. This object tells AngularJS what DOM elements to look for, and what changes to make to them. Directives are hooked in to the template using either attributes or elements, which you invent. The idea is to extend the capabilities of HTML with new attributes and elements.

The AngularJS way is to extend the capabilities of native looking HTML. You should write HTML that looks like HTML, extended with custom attributes and elements.

If you want a carousel, just use a <carousel /> element, then define a directive to pull in a template, and make that sucker work.

Lots of small directives vs. big plugins with configuration switches

The tendency with jQuery is to write great big plugins like lightbox which we then configure by passing in numerous values and options.

This is a mistake in AngularJS.

Take the example of a dropdown. When writing a dropdown plugin you might be tempted to code in click handlers, perhaps a function to add in a chevron which is either up or down, perhaps change the class of the unfolded element, show hide the menu, all helpful stuff.

Until you want to make a small change.

Say you have a menu that you want to unfold on hover. Well now we have a problem. Our plugin has wired in our click handler for us, we're going to need to add a configuration option to make it behave differently in this specific case.

In AngularJS we write smaller directives. Our dropdown directive would be ridiculously small. It might maintain the folded state, and provide methods to fold(), unfold() or toggle(). These methods would simply update $scope.menu.visible which is a boolean holding the state.

Now in our template we can wire this up:

<a ng-click="toggle()">Menu</a>
<ul ng-show="menu.visible">
  ...
</ul>

Need to update on mouseover?

<a ng-mouseenter="unfold()" ng-mouseleave="fold()">Menu</a>
<ul ng-show="menu.visible">
  ...
</ul>

The template drives the application so we get HTML level granularity. If we want to make case by case exceptions, the template makes this easy.

Closure vs. $scope

JQuery plugins are created in a closure. Privacy is maintained within that closure. It's up to you to maintain your scope chain within that closure. You only really have access to the set of DOM nodes passed in to the plugin by jQuery, plus any local variables defined in the closure and any globals you have defined. This means that plugins are quite self contained. This is a good thing, but can get restrictive when creating a whole application. Trying to pass data between sections of a dynamic page becomes a chore.

AngularJS has $scope objects. These are special objects created and maintained by AngularJS in which you store your model. Certain directives will spawn a new $scope, which by default inherits from its wrapping $scope using JavaScript prototypical inheritance. The $scope object is accessible in the controller and the view.

This is the clever part. Because the structure of $scope inheritance roughly follows the structure of the DOM, elements have access to their own scope, and any containing scopes seamlessly, all the way up to the global $scope (which is not the same as the global scope).

This makes it much easier to pass data around, and to store data at an appropriate level. If a dropdown is unfolded, only the dropdown $scope needs to know about it. If the user updates their preferences, you might want to update the global $scope, and any nested scopes listening to the user preferences would automatically be alerted.

This might sound complicated, in fact, once you relax into it, it's like flying. You don't need to create the $scope object, AngularJS instantiates and configures it for you, correctly and appropriately based on your template hierarchy. AngularJS then makes it available to your component using the magic of dependency injection (more on this later).

Manual DOM changes vs. Data Binding

In jQuery you make all your DOM changes by hand. You construct new DOM elements programatically. If you have a JSON array and you want to put it to the DOM, you must write a function to generate the HTML and insert it.

In AngularJS you can do this too, but you are encouraged to make use of data binding. Change your model, and because the DOM is bound to it via a template your DOM will automatically update, no intervention required.

Because data binding is done from the template, using either an attribute or the curly brace syntax, it's super easy to do. There's little cognitive overhead associated with it so you'll find yourself doing it all the time.

<input ng-model="user.name" />

Binds the input element to $scope.user.name. Updating the input will update the value in your current scope, and vice-versa.

Likewise:

<p>
  {{user.name}}
</p>

will output the user name in a paragraph. It's a live binding, so if the $scope.user.name value is updated, the template will update too.

Ajax all of the time

In jQuery making an Ajax call is fairly simple, but it's still something you might think twice about. There's the added complexity to think about, and a fair chunk of script to maintain.

In AngularJS, Ajax is your default go-to solution and it happens all the time, almost without you noticing. You can include templates with ng-include. You can apply a template with the simplest custom directive. You can wrap an Ajax call in a service and create yourself a GitHub service, or a Flickr service, which you can access with astonishing ease.

Service Objects vs Helper Functions

In jQuery, if we want to accomplish a small non-dom related task such as pulling a feed from an API, we might write a little function to do that in our closure. That's a valid solution, but what if we want to access that feed often? What if we want to reuse that code in another application?

AngularJS gives us service objects.

Services are simple objects that contain functions and data. They are always singletons, meaning there can never be more than one of them. Say we want to access the Stack Overflow API, we might write a StackOverflowService which defines methods for doing so.

Let's say we have a shopping cart. We might define a ShoppingCartService which maintains our cart and contains methods for adding and removing items. Because the service is a singleton, and is shared by all other components, any object that needs to can write to the shopping cart and pull data from it. It's always the same cart.

Service objects are self-contained AngularJS components which we can use and reuse as we see fit. They are simple JSON objects containing functions and Data. They are always singletons, so if you store data on a service in one place, you can get that data out somewhere else just by requesting the same service.

Dependency injection (DI) vs. Instatiation - aka de-spaghettification

AngularJS manages your dependencies for you. If you want an object, simply refer to it and AngularJS will get it for you.

Until you start to use this, it's hard to explain just what a massive time boon this is. Nothing like AngularJS DI exists inside jQuery.

DI means that instead of writing your application and wiring it together, you instead define a library of components, each identified by a string.

Say I have a component called 'FlickrService' which defines methods for pulling JSON feeds from Flickr. Now, if I want to write a controller that can access Flickr, I just need to refer to the 'FlickrService' by name when I declare the controller. AngularJS will take care of instantiating the component and making it available to my controller.

For example, here I define a service:

myApp.service('FlickrService', function() {
  return {
    getFeed: function() { // do something here }
  }
});

Now when I want to use that service I just refer to it by name like this:

myApp.controller('myController', ['FlickrService', function(FlickrService) {
  FlickrService.getFeed()
}]);

AngularJS will recognise that a FlickrService object is needed to instantiate the controller, and will provide one for us.

This makes wiring things together very easy, and pretty much eliminates any tendency towards spagettification. We have a flat list of components, and AngularJS hands them to us one by one as and when we need them.

Modular service architecture

jQuery says very little about how you should organise your code. AngularJS has opinions.

AngularJS gives you modules into which you can place your code. If you're writing a script that talks to Flickr for example, you might want to create a Flickr module to wrap all your Flickr related functions in. Modules can include other modules (DI). Your main application is usually a module, and this should include all the other modules your application will depend on.

You get simple code reuse, if you want to write another application based on Flickr, you can just include the Flickr module and voila, you have access to all your Flickr related functions in your new application.

Modules contain AngularJS components. When we include a module, all the components in that module become available to us as a simple list identified by their unique strings. We can then inject those components into each other using AngularJS's dependency injection mechanism.

To sum up

AngularJS and jQuery are not enemies. It's possible to use jQuery within AngularJS very nicely. If you're using AngularJS well (templates, data-binding, $scope, directives, etc.) you will find you need a lot less jQuery than you might otherwise require.

The main thing to realise is that your template drives your application. Stop trying to write big plugins that do everything. Instead write little directives that do one thing, then write a simple template to wire them together.

Think less about unobtrusive JavaScript, and instead think in terms of HTML extensions.

My little book

I got so excited about AngularJS, I wrote a short book on it which you're very welcome to read online http://nicholasjohnson.com/angular-book/. I hope it's helpful.

How to find a user's home directory on linux or unix?

If you want to find a specific user's home directory, I don't believe you can do it directly.

When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX() family of calls.

How do I fill arrays in Java?

Arrays.fill(arrayName,value);

in java

int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
  System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
  System.out.println(arrnum[i]+" ");
}

Output

5 6 9 2 10
0 0 0 0 0

How to install a Notepad++ plugin offline?

  • Download and extract .zip file having all .dll plugin files under the path

    C:\ProgramData\Notepad++\plugins\

  • Make sure to create a separated folder for each plugin

  • Plugin (.dll) must be compatible with installed Notepad++ version (32 bit or 64 bit)

Forcing to download a file using PHP

A previous answer on this page describes how to use .htaccess to force all files of a certain type to download. However, the solution does not work with all file types across all browsers. This is a more reliable way:

<FilesMatch "\.(?i:csv)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

You might need to flush your browser cache to see this working correctly.

Explain the different tiers of 2 tier & 3 tier architecture?

The general explanation is provided in the link from Dan.


For specific questions your ask :

They can reside on the same machine, even in the same process (JVM for Java). It is a logical distinction (what they do?), not a physical one (where they are?).

How to input a string from user into environment variable from batch file

You can use set with the /p argument:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

So, simply use something like

set /p Input=Enter some text: 

Later you can use that variable as argument to a command:

myCommand %Input%

Be careful though, that if your input might contain spaces it's probably a good idea to quote it:

myCommand "%Input%"

CSS technique for a horizontal line with words in the middle

Solution for IE8 and newer...

Issues worth noting:

Using background-color to mask a border might not be the best solution. If you have a complex (or unknown) background color (or image), masking will ultimately fail. Also, if you resize the text, you'll notice that white background color (or whatever you set) will start covering up the text on the line above (or below).

You also don't want to "guesstimate" how wide the the sections are either, because it makes the styles very inflexible and almost impossible to implement on a responsive site where the width of the content is changing.

Solution:

(View JSFiddle)

Instead of "masking" a border with a background-color, use your display property.

HTML

<div class="group">
    <div class="item line"></div>
    <div class="item text">This is a test</div>
    <div class="item line"></div>
</div>

CSS

.group { display: table; width: 100%; }
.item { display: table-cell; }
.text { white-space: nowrap; width: 1%; padding: 0 10px; }
.line { border-bottom: 1px solid #000; position: relative; top: -.5em; }

Resize your text by placing your font-size property on the .group element.

Limitations:

  • No multi-line text. Single lines only.
  • HTML markup isn't as elegant
  • top property on .line element needs to be half of line-height. So, if you have a line-height of 1.5em, then the top should be -.75em. This is a limitation because it's not automated, and if you are applying these styles on elements with different line-heights, then you might need to reapply your line-height style.

For me, these limitations outweigh the "issues" I noted at the beginning of my answer for most implementations.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

The bug has been fixed in the latest androidx version. And the famous workaround will cause crash now. so we need not it now.

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

This question is a few years old, and there are some good suggestions for workarounds, but I didn't really notice any answers that address the core of the original question head-on. So:

  • Providing a "universal" method for viewing source in a feature phone browser (or even arbitrary third-party smartphone browser) is impossible because "view source" — via any method — is a feature implemented in the browser. So how it's accessed, or even if it can be accessed, is up to the developers of the browser. I'm sure there are plenty of browsers that intentionally prevent the user from viewing page source, and if so then you're out of luck, except maybe for workarounds like the ones offered here.

  • Workarounds such as "view source" apps external to the browser, while useful in some cases, are at best an imperfect partial solution to the original request. It's never certain that any such app will display the source of the page in the same form as it's loaded by the phone's browser.

    Modern web content changes itself in all manner of ways through browser detection, session management, etc. so that the source loaded by any external app can never be relied on to represent the source as loaded by a different app. If you're going to use an external app to load a page because you want to see the source, you might as well just use Chrome (or, on an iOS device, Safari) instead.

Java - how do I write a file to a specified directory

You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.

Sample code:

String dirName = /* something to pull specified dir from input */;

String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);

/* rest is the same */

Hope it helps.

How to compare character ignoring case in primitive types

You can change the case of String before using it, like this

String name1 = fname.getText().toString().toLowerCase(); 
String name2 = sname.getText().toString().toLowerCase();

Then continue with rest operation.

HTML Drag And Drop On Mobile Devices

Jquery Touch Punch is great but what it also does is disable all the controls on the draggable div so to prevent this you have to alter the lines... (at the time of writing - line 75)

change

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])){

to read

if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0]) || event.originalEvent.target.localName === 'textarea'
        || event.originalEvent.target.localName === 'input' || event.originalEvent.target.localName === 'button' || event.originalEvent.target.localName === 'li'
        || event.originalEvent.target.localName === 'a'
        || event.originalEvent.target.localName === 'select' || event.originalEvent.target.localName === 'img') {

add as many ors as you want for each of the elements you want to 'unlock'

Hope that helps someone

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

How can I get the image url in a Wordpress theme?

src="<?php echo base_url()?>your_theme_dir/image_dir/img.ext"

As well

src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"

Printing integer variable and string on same line in SQL

You may try this one,

declare @Number INT = 5                            
print 'There are ' + CONVERT(VARCHAR, @Number) + ' alias combinations did not match a record'

Chart.js v2 - hiding grid lines

options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

Difference between == and ===

Just a minor contribution related to the Any object.

I was working with unit tests around NotificationCenter, which makes use of Any as a parameter that I wanted to compare for equality.

However, since Any cannot be used in an equality operation, it was necessary to change it. Ultimately, I settled on the following approach, which allowed me to get equality in my specific situation, shown here with a simplistic example:

func compareTwoAny(a: Any, b: Any) -> Bool {
    return ObjectIdentifier(a as AnyObject) == ObjectIdentifier(b as AnyObject)
}

This function takes advantage of ObjectIdentifier, which provides a unique address for the object, allowing me to test.

One item to note though about ObjectIdentifier per Apple at the above link:

In Swift, only class instances and metatypes have unique identities. There is no notion of identity for structs, enums, functions, or tuples.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.

From the Oracle 10g SQL Reference:

Notes on Updatable Views

An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.

To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:

  • Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.
  • The view must not contain any of the following constructs:
    • A set operator
    • a DISTINCT operator
    • An aggregate or analytic function
    • A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause
    • A collection expression in a SELECT list
    • A subquery in a SELECT list
    • A subquery designated WITH READ ONLY
    • Joins, with some exceptions, as documented in Oracle Database Administrator's Guide

In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following conditions must be true:

  • The DML statement must affect only one table underlying the join.
  • For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.
  • For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.
  • For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.

Easy way to test a URL for 404 in PHP?

If your running php5 you can use:

$url = 'http://www.example.com';
print_r(get_headers($url, 1));

Alternatively with php4 a user has contributed the following:

/**
This is a modified version of code from "stuart at sixletterwords dot com", at 14-Sep-2005 04:52. This version tries to emulate get_headers() function at PHP4. I think it works fairly well, and is simple. It is not the best emulation available, but it works.

Features:
- supports (and requires) full URLs.
- supports changing of default port in URL.
- stops downloading from socket as soon as end-of-headers is detected.

Limitations:
- only gets the root URL (see line with "GET / HTTP/1.1").
- don't support HTTPS (nor the default HTTPS port).
*/

if(!function_exists('get_headers'))
{
    function get_headers($url,$format=0)
    {
        $url=parse_url($url);
        $end = "\r\n\r\n";
        $fp = fsockopen($url['host'], (empty($url['port'])?80:$url['port']), $errno, $errstr, 30);
        if ($fp)
        {
            $out  = "GET / HTTP/1.1\r\n";
            $out .= "Host: ".$url['host']."\r\n";
            $out .= "Connection: Close\r\n\r\n";
            $var  = '';
            fwrite($fp, $out);
            while (!feof($fp))
            {
                $var.=fgets($fp, 1280);
                if(strpos($var,$end))
                    break;
            }
            fclose($fp);

            $var=preg_replace("/\r\n\r\n.*\$/",'',$var);
            $var=explode("\r\n",$var);
            if($format)
            {
                foreach($var as $i)
                {
                    if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$i,$parts))
                        $v[$parts[1]]=$parts[2];
                }
                return $v;
            }
            else
                return $var;
        }
    }
}

Both would have a result similar to:

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Therefore you could just check to see that the header response was OK eg:

$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.1 200 OK') {
//valid 
}

if ($headers[0] == 'HTTP/1.1 301 Moved Permanently') {
//moved or redirect page
}

W3C Codes and Definitions

Creating an XmlNode/XmlElement in C# without an XmlDocument?

Another option is to pass a delegate to method, which will create an XmlElement. This way the target method won't get access to whole XmlDocument, but will be able to create new elements.

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

How to connect Android app to MySQL database?

Can i use pHp to develop an android app?
Yes . for web development you can use Phonegap. "PHP , HTML"etc.
What are the ways this can be done:?
you can check couple of examples on the internet here is one of them "an easy way" Connect Android To MySQL

How do you get/set media volume (not ringtone volume) in Android?

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 0.7f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);

Where is the default log location for SharePoint/MOSS?

By default they are stored here:
%commonprogramfiles%/Microsoft Shared/web server extensions/12/Logs

Using %commonprogramfiles% make it works in non-english systems.

Apply function to pandas groupby

As of Pandas version 0.22, there exists also an alternative to apply: pipe, which can be considerably faster than using apply (you can also check this question for more differences between the two functionalities).

For your example:

df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})

  my_label
0        A
1        B
2        A
3        C
4        D
5        D
6        E

The apply version

df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])

gives

          my_label
my_label          
A         0.285714
B         0.142857
C         0.142857
D         0.285714
E         0.142857

and the pipe version

df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())

yields

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):

%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop

and

%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop

Wrapping it into a function is then also straightforward:

def get_perc(grp_obj):
    gr_size = grp_obj.size()
    return gr_size / gr_size.sum()

Now you can call

df.groupby('my_label').pipe(get_perc)

yielding

my_label
A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

However, for this particular case, you do not even need a groupby, but you can just use value_counts like this:

df['my_label'].value_counts(sort=False) / df.shape[0]

yielding

A    0.285714
C    0.142857
B    0.142857
E    0.142857
D    0.285714
Name: my_label, dtype: float64

For this small dataframe it is quite fast

%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop

As pointed out by @anmol, the last statement can also be simplified to

df['my_label'].value_counts(sort=False, normalize=True)

SQL Update Multiple Fields FROM via a SELECT Statement

You should be able to do something along the lines of the following

UPDATE s
SET
    OrgAddress1 = bd.OrgAddress1,
    OrgAddress2 = bd.OrgAddress2,
    ...
    DestZip = bd.DestZip
FROM
    Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
    bd.MyID = @MyId AND s.MyID2 = @MyID2

FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET to read SELECT! You will then see that data as it would appear if the update had taken place.

How to concatenate strings in windows batch file for loop?

In batch you could do it like this:

@echo off

setlocal EnableDelayedExpansion

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do (
  set "var=%%sxyz"
  svn co "!var!"
)

If you don't need the variable !var! elsewhere in the loop, you could simplify that to

@echo off

setlocal

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do svn co "%%sxyz"

However, like C.B. I'd prefer PowerShell if at all possible:

$string_list = 'str1', 'str2', 'str3', ... 'str10'

$string_list | ForEach-Object {
  $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
  svn co $var
}

Again, this could be simplified if you don't need $var elsewhere in the loop:

$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }

How do I compare strings in GoLang?

The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

Why doesn't TFS get latest get the latest?

Go with right click: Advanced > Get Specific Version. Select "Letest Version" and now, important, mark two checks: enter image description here

The checks are:
Overwrite writeable files that are not checked

Overwrite all files even if the local version matches the specified version

Refresh DataGridView when updating data source

Alexander Abakumov's answer is the correct one. It solved every binding issue I had updating the underlying data and having the grid update.

Its easy to implement and modify any existing source code you have.

grdDetails.DataSource = new System.Windows.Forms.BindingSource { DataSource = OrderDetails };

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

Add spaces between the characters of a string in Java?

  • Create a char array from your string
  • Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
  • BOOM...done!!

Checking if a string can be converted to float in Python

Python method to check for float:

def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False

Don't get bit by the goblins hiding in the float boat! DO UNIT TESTING!

What is, and is not a float may surprise you:

Command to parse                        Is it a float?  Comment
--------------------------------------  --------------- ------------
print(isfloat(""))                      False
print(isfloat("1234567"))               True 
print(isfloat("NaN"))                   True            nan is also float
print(isfloat("NaNananana BATMAN"))     False
print(isfloat("123.456"))               True
print(isfloat("123.E4"))                True
print(isfloat(".1"))                    True
print(isfloat("1,234"))                 False
print(isfloat("NULL"))                  False           case insensitive
print(isfloat(",1"))                    False           
print(isfloat("123.EE4"))               False           
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777"))              True            This is same as Inf
print(isfloat("-iNF"))                  True
print(isfloat("1.797693e+308"))         True
print(isfloat("infinity"))              True
print(isfloat("infinity and BEYOND"))   False
print(isfloat("12.34.56"))              False           Two dots not allowed.
print(isfloat("#56"))                   False
print(isfloat("56%"))                   False
print(isfloat("0E0"))                   True
print(isfloat("x86E0"))                 False
print(isfloat("86-5"))                  False
print(isfloat("True"))                  False           Boolean is not a float.   
print(isfloat(True))                    True            Boolean is a float
print(isfloat("+1e1^5"))                False
print(isfloat("+1e1"))                  True
print(isfloat("+1e1.3"))                False
print(isfloat("+1.3P1"))                False
print(isfloat("-+1"))                   False
print(isfloat("(1)"))                   False           brackets not interpreted

Best way to compare two complex objects

Implement IEquatable<T> (typically in conjunction with overriding the inherited Object.Equals and Object.GetHashCode methods) on all your custom types. In the case of composite types, invoke the contained types’ Equals method within the containing types. For contained collections, use the SequenceEqual extension method, which internally calls IEquatable<T>.Equals or Object.Equals on each element. This approach will obviously require you to extend your types’ definitions, but its results are faster than any generic solutions involving serialization.

Edit: Here is a contrived example with three levels of nesting.

For value types, you can typically just call their Equals method. Even if the fields or properties were never explicitly assigned, they would still have a default value.

For reference types, you should first call ReferenceEquals, which checks for reference equality – this would serve as an efficiency boost when you happen to be referencing the same object. It would also handle cases where both references are null. If that check fails, confirm that your instance's field or property is not null (to avoid NullReferenceException) and call its Equals method. Since our members are properly typed, the IEquatable<T>.Equals method gets called directly, bypassing the overridden Object.Equals method (whose execution would be marginally slower due to the type cast).

When you override Object.Equals, you’re also expected to override Object.GetHashCode; I didn’t do so below for the sake of conciseness.

public class Person : IEquatable<Person>
{
    public int Age { get; set; }
    public string FirstName { get; set; }
    public Address Address { get; set; }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as Person);
    }

    public bool Equals(Person other)
    {
        if (other == null)
            return false;

        return this.Age.Equals(other.Age) &&
            (
                object.ReferenceEquals(this.FirstName, other.FirstName) ||
                this.FirstName != null &&
                this.FirstName.Equals(other.FirstName)
            ) &&
            (
                object.ReferenceEquals(this.Address, other.Address) ||
                this.Address != null &&
                this.Address.Equals(other.Address)
            );
    }
}

public class Address : IEquatable<Address>
{
    public int HouseNo { get; set; }
    public string Street { get; set; }
    public City City { get; set; }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as Address);
    }

    public bool Equals(Address other)
    {
        if (other == null)
            return false;

        return this.HouseNo.Equals(other.HouseNo) &&
            (
                object.ReferenceEquals(this.Street, other.Street) ||
                this.Street != null &&
                this.Street.Equals(other.Street)
            ) &&
            (
                object.ReferenceEquals(this.City, other.City) ||
                this.City != null &&
                this.City.Equals(other.City)
            );
    }
}

public class City : IEquatable<City>
{
    public string Name { get; set; }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as City);
    }

    public bool Equals(City other)
    {
        if (other == null)
            return false;

        return
            object.ReferenceEquals(this.Name, other.Name) ||
            this.Name != null &&
            this.Name.Equals(other.Name);
    }
}

Update: This answer was written several years ago. Since then, I've started to lean away from implementing IEquality<T> for mutable types for such scenarios. There are two notions of equality: identity and equivalence. At a memory representation level, these are popularly distinguished as “reference equality” and “value equality” (see Equality Comparisons). However, the same distinction can also apply at a domain level. Suppose that your Person class has a PersonId property, unique per distinct real-world person. Should two objects with the same PersonId but different Age values be considered equal or different? The answer above assumes that one is after equivalence. However, there are many usages of the IEquality<T> interface, such as collections, that assume that such implementations provide for identity. For example, if you're populating a HashSet<T>, you would typically expect a TryGetValue(T,T) call to return existing elements that share merely the identity of your argument, not necessarily equivalent elements whose contents are completely the same. This notion is enforced by the notes on GetHashCode:

In general, for mutable reference types, you should override GetHashCode() only if:

  • You can compute the hash code from fields that are not mutable; or
  • You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

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

If only the columns are required then DataTable.Clone() can be used. With Clone function only the schema will be copied. But DataTable.Copy() copies both the structure and data

E.g.

DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();

dt1 will have only the one column but dt2 will have one column with one row.

R data formats: RData, Rda, Rds etc

Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.

Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.

So, answering your questions:

  • The difference is not about the compression, but serialization (See this page)
  • Like shown in the manual page, you may wanna use it to restore a certain object with a different name, for instance.
  • You may readRDS() and save(), or load() and saveRDS() selectively.

Manually Triggering Form Validation using jQuery

_x000D_
_x000D_
var field = $("#field")_x000D_
field.keyup(function(ev){_x000D_
    if(field[0].value.length < 10) {_x000D_
        field[0].setCustomValidity("characters less than 10")_x000D_
        _x000D_
    }else if (field[0].value.length === 10) {_x000D_
        field[0].setCustomValidity("characters equal to 10")_x000D_
        _x000D_
    }else if (field[0].value.length > 10 && field[0].value.length < 20) {_x000D_
        field[0].setCustomValidity("characters greater than 10 and less than 20")_x000D_
        _x000D_
    }else if(field[0].validity.typeMismatch) {_x000D_
     field[0].setCustomValidity("wrong email message")_x000D_
        _x000D_
    }else {_x000D_
     field[0].setCustomValidity("") // no more errors_x000D_
        _x000D_
    }_x000D_
    field[0].reportValidity()_x000D_
    _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="email" id="field">
_x000D_
_x000D_
_x000D_

Gunicorn worker timeout error

We had the same problem using Django+nginx+gunicorn. From Gunicorn documentation we have configured the graceful-timeout that made almost no difference.

After some testings, we found the solution, the parameter to configure is: timeout (And not graceful timeout). It works like a clock..

So, Do:

1) open the gunicorn configuration file

2) set the TIMEOUT to what ever you need - the value is in seconds

NUM_WORKERS=3
TIMEOUT=120

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=127.0.0.1:9000 \
--pid=$PIDFILE

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

Setting a max character length in CSS

There is a CSS 'length value' of ch.

From MDN

This unit represents the width, or more precisely the advance measure, of the glyph '0' (zero, the Unicode character U+0030) in the element's font.

This may approximate what you are after.

_x000D_
_x000D_
p {_x000D_
  overflow: hidden;_x000D_
  max-width: 75ch;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!Lorem ipsum dolor sit amet, consectetur_x000D_
  adipisicing elit. Dolorem voluptates vel dolorum autem ex repudiandae iste quasi. Minima explicabo qui necessitatibus porro nihil aliquid deleniti ullam repudiandae dolores corrupti eaque.</p>
_x000D_
_x000D_
_x000D_

How to copy and paste code without rich text formatting?

Look for a little clipboard icon that pops up at the end of the material you pasted. Click on this and choose "keep text only".

HTML combo box with option to type an entry

Given that the HTML datalist tag is still not fully supported, an alternate approach that I used is the Dojo Toolkit ComboBox. It was easier to implement and better documented than other options I've explored. It also plays nicely with existing frameworks. In my case, I added this combobox to an existing website that's based on Codeigniter and Bootstrap with no problems You just need to be sure to apply the Dojo theme (e.g. class="claro") to the combo's parent element instead of the body tag to avoid styling conflicts.

First, include the CSS for one of the Dojo themes (such as 'Claro'). It's important that the CSS file is included prior to the JS files below.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.9.6/dijit/themes/claro/claro.css" />

Next, include jQuery and Dojo Toolkit via CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>

Next, you can just follow Dojo's sample code or use the sample below to get a working combobox.

<body>
    <!-- Dojo Dijit ComboBox with 'Claro' theme -->
    <div class="claro"><input id="item_name_1" class=""/></div>

    <script type="text/javascript">
        $(document).ready(function () {
            //In this example, dataStore is simply an array of JSON-encoded id/name pairs
            dataStore = [{"id":"43","name":"Domain Name Renewal"},{"id":"42","name":"Hosting Renewal"}];

            require(
                [ "dojo/store/Memory", "dijit/form/ComboBox", "dojo/domReady!"], 
                function (Memory, ComboBox) {
                    var stateStore = new Memory({
                        data: dataStore
                    });

                    var combo = new ComboBox({
                        id: "item_name_1",
                        name: "desc_1",
                        store: stateStore,
                        searchAttr: "name"},                        
                        "item_name_1"
                        ).startup();

                });

        });

    </script>
</body>

Why Doesn't C# Allow Static Methods to Implement an Interface?

My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.

For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):

...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.

Note that Lippert does leave room for a so-called type method:

That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).

but is yet to be convinced of its usefulness.

How can I make an "are you sure" prompt in a Windows batchfile?

First, open the terminal.

Then, type

cd ~
touch .sure
chmod 700 .sure

Next, open .sure and paste this inside.

#!/bin/bash --init-file
PS1='> '
alias y='
    $1
    exit
'
alias n='Taskkill /IM %Terminal% /f'
echo ''
echo 'Are you sure? Answer y or n.'
echo ''

After that, close the file.

~/.sure ; ENTER COMMAND HERE

This will give you a prompt of are you sure before continuing the command.

How to query DATETIME field using only date in Microsoft SQL Server?

select *, cast ([col1] as date) <name of the column> from test where date = 'mm/dd/yyyy'

"col1" is name of the column with date and time
<name of the column> here you can change name as desired

.gitignore after commit

I had to remove .idea and target folders and after reading all comments this worked for me:

git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'

and then push to master

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Use the Take method:

var foo = (from t in MyTable
           select t.Foo).Take(10);

In VB LINQ has a take expression:

Dim foo = From t in MyTable _
          Take 10 _
          Select t.Foo

From the documentation:

Take<TSource> enumerates source and yields elements until count elements have been yielded or source contains no more elements. If count exceeds the number of elements in source, all elements of source are returned.

What is RSS and VSZ in Linux memory management

They are not managed, but measured and possibly limited (see getrlimit system call, also on getrlimit(2)).

RSS means resident set size (the part of your virtual address space sitting in RAM).

You can query the virtual address space of process 1234 using proc(5) with cat /proc/1234/maps and its status (including memory consumption) thru cat /proc/1234/status

Set an empty DateTime variable

The .addwithvalue needs dbnull. You could do something like this:

DateTime? someDate = null;
//...
if (someDate == null)
    myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);

or use a method extension...

  public static class Extensions
    {
        public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
        {
            if (value == null)
                return collection.AddWithValue(parameterName, DBNull.Value);
            else
                return collection.AddWithValue(parameterName, value);
        }
    }

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

App crashing when trying to use RecyclerView on android 5.0

Since LinearLayoutManager is vertical by default, an easier way to do this is:

recyclerView.setLayoutManager(new LinearLayoutManager(context));

If you want to change the orientation you could use this constructor:

public LinearLayoutManager(Context context, int orientation, boolean reverseLayout);

<> And Not In VB.NET

I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:

<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>

Cannot open output file, permission denied

FOR LINUX OS... go to file where u r created file.then usually ......project_name/bin/Debug/project_name.executable here for this executable file you wont be having execute permission then the execute permission.Either by right click if you are unable to change permission then use use open terminal(command promt) to change permission. first go to that executable file using 'cd' command then use "chmod u+x" then permission is going to change.then go to c::b open and execute you will get output.

only thing for all file u need to do it.

How to convert an OrderedDict into a regular dict in python3

Here is what seems simplest and works in python 3.7

from collections import OrderedDict

d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d)  # Now a normal dict

Now to check this:

>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True

NOTE: This also works, and gives same result -

>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True

As well as this -

>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True

Cheers

How to get the Power of some Integer in Swift language?

An Int-based pow function that computes the value directly via bit shift for base 2 in Swift 5:

func pow(base: Int, power: UInt) -> Int {
    if power == 0 { return 1 }
    // for base 2, use a bit shift to compute the value directly
    if base == 2 { return 2 << Int(power - 1) }
    // otherwise multiply base repeatedly to compute the value
    return repeatElement(base, count: Int(power)).reduce(1, *)
}

(Make sure the result is within the range of Int - this does not check for the out of bounds case)

Why extend the Android Application class?

Application class is the object that has the full lifecycle of your application. It is your highest layer as an application. example possible usages:

  • You can add what you need when the application is started by overriding onCreate in the Application class.

  • store global variables that jump from Activity to Activity. Like Asynctask.

    etc

Using ConfigurationManager to load config from an arbitrary location

This should do the trick :

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "newAppConfig.config);

Source : https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files

How can I interrupt a running code in R with a keyboard command?

Self Answer (pretty much summary of other's comments and answers):

  • In RStudio, Esc works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).

  • If the process is ran in say ubuntu shell (and this is not R specific), for example using:

    Rscript my_file.R
    

    Ctrl + c kills the process

    Ctrl + z suspends the process

  • Within R shell, Ctrl + C kills helps you escape it

How do I define a method in Razor?

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>

Angular no provider for NameService

In Angular v2 and up it is now:

@Component({ selector:'my-app', providers: [NameService], template: ... })

How do I load the contents of a text file into a javascript variable?

If you only want a constant string from the text file, you could include it as JavaScript:

_x000D_
_x000D_
// This becomes the content of your foo.txt file_x000D_
let text = `_x000D_
My test text goes here!_x000D_
`;
_x000D_
<script src="foo.txt"></script>_x000D_
<script>_x000D_
  console.log(text);_x000D_
</script>
_x000D_
_x000D_
_x000D_

The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a template literal, allowing for both " and ' characters in your text block.

This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the file:// scheme.

JBoss default password

I just had to uncomment the line in jboss-eap-5.0\jboss-as\server\default\conf\props\jmx-console-users.properties

admin=admin

Thats it. Restart Jboss and I was about to get in to JBOSS JMX. Magically this even fixed the error that I used to get while shutting down Jboss from Eclipse.

Dynamically Add Images React Webpack

UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.

With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:

This will NOT work. :

const myImg = './cute.jpg'
<img src={require(myImg)} />

To fix this, just use template strings instead :

const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />

webpack.config.js :

var HtmlWebpackPlugin =  require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry : './src/app.js',
  output : {
    path : './dist',
    filename : 'app.bundle.js'
  },
  plugins : [
  new ExtractTextWebpackPlugin('app.bundle.css')],
  module : {
    rules : [{
      test : /\.css$/,
      use : ExtractTextWebpackPlugin.extract({
        fallback : 'style-loader',
        use: 'css-loader'
      })
    },{
      test: /\.js$/,
      exclude: /(node_modules)/,
      loader: 'babel-loader',
      query: {
        presets: ['react','es2015']
      }
    },{
      test : /\.jpg$/,
      exclude: /(node_modules)/,
      loader : 'file-loader'
    }]
  }
}

How to print number with commas as thousands separators?

this is baked into python per PEP -> https://www.python.org/dev/peps/pep-0378/

just use format(1000, ',d') to show an integer with thousands separator

there are more formats described in the PEP, have at it

Fastest way to zero out a 2d array in C?

You can try this

int array[20,30] = {{0}};

Changing background color of ListView items on Android

Did you mean to change the background color of the custom listitems when you click on it?

If so:

You just add the following code to your listview layout in xml.


android:drawSelectorOnTop="true" android:listSelector="@android:drawable/list_selector_background"


The list selector here uses default selector which has a dark grey color. You can make your own drawable and assign it to the list selector as above.

Hope this is what you wanted.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

queryForList returns a List of LinkedHashMap objects.

You need to cast it first like this:


    List list = jdbcTemplate.queryForList(...);
    for (Object o : list) {
       Map m = (Map) o;
       ...
    }

how to automatically scroll down a html page?

You can use .scrollIntoView() for this. It will bring a specific element into the viewport.

Example:

document.getElementById( 'bottom' ).scrollIntoView();

Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/

Script:

function top() {
    document.getElementById( 'top' ).scrollIntoView();    
};

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );
};

bottom();

HTML:

<div id="top">top</div>
<div id="bottom">bottom</div>

CSS:

#top {
    border: 1px solid black;
    height: 3000px;
}

#bottom {
    border: 1px solid red;
}

Event handler not working on dynamic content

You are missing the selector in the .on function:

.on(eventType, selector, function)

This selector is very important!

http://api.jquery.com/on/

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler

See jQuery 1.9 .live() is not a function for more details.

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to script FTP upload and download?

I know this is an old question, but I wanted to add something to the answers already here in hopes of helping someone else.

You can script the ftp command with the -s:filename option. The syntax is just a list of commands to pass to the ftp shell, each terminated by a newline. This page has a nice reference to the commands that can be performed with ftp.

Upload/Download Entire Directory Structure

Using the normal ftp doesn't work very well when you need to have an entire directory tree copied to or from a ftp site. So you could use something like these to handle those situations.

These scripts works with the Windows ftp command and allows for uploading and downloading of entire directories from a single command. This makes it pretty self reliant when using on different systems.

Basically what they do is map out the directory structure to be up/downloaded, dump corresponding ftp commands to a file, then execute those commands when the mapping has finished.

ftpupload.bat

@echo off

SET FTPADDRESS=%1
SET FTPUSERNAME=%2
SET FTPPASSWORD=%3
SET LOCALDIR=%~f4
SET REMOTEDIR=%5

if "%FTPADDRESS%" == "" goto FTP_UPLOAD_USAGE
if "%FTPUSERNAME%" == "" goto FTP_UPLOAD_USAGE
if "%FTPPASSWORD%" == "" goto FTP_UPLOAD_USAGE
if "%LOCALDIR%" == "" goto FTP_UPLOAD_USAGE
if "%REMOTEDIR%" == "" goto FTP_UPLOAD_USAGE

:TEMP_NAME
set TMPFILE=%TMP%\%RANDOM%_ftpupload.tmp
if exist "%TMPFILE%" goto TEMP_NAME 

SET INITIALDIR=%CD%

echo user %FTPUSERNAME% %FTPPASSWORD% > %TMPFILE%
echo bin >> %TMPFILE%
echo lcd %LOCALDIR% >> %TMPFILE%

cd %LOCALDIR%

setlocal EnableDelayedExpansion
echo mkdir !REMOTEDIR! >> !TMPFILE!
echo cd %REMOTEDIR% >> !TMPFILE!
echo mput * >> !TMPFILE!
for /d /r %%d in (*) do (
    set CURRENT_DIRECTORY=%%d
    set RELATIVE_DIRECTORY=!CURRENT_DIRECTORY:%LOCALDIR%=!
    echo mkdir "!REMOTEDIR!/!RELATIVE_DIRECTORY:~1!" >> !TMPFILE!
    echo cd "!REMOTEDIR!/!RELATIVE_DIRECTORY:~1!" >> !TMPFILE!
    echo mput "!RELATIVE_DIRECTORY:~1!\*" >> !TMPFILE!
)

echo quit >> !TMPFILE!

endlocal EnableDelayedExpansion

ftp -n -i "-s:%TMPFILE%" %FTPADDRESS%

del %TMPFILE%

cd %INITIALDIR%

goto FTP_UPLOAD_EXIT

:FTP_UPLOAD_USAGE

echo Usage: ftpupload [address] [username] [password] [local directory] [remote directory]
echo.

:FTP_UPLOAD_EXIT

set INITIALDIR=
set FTPADDRESS=
set FTPUSERNAME=
set FTPPASSWORD=
set LOCALDIR=
set REMOTEDIR=
set TMPFILE=
set CURRENT_DIRECTORY=
set RELATIVE_DIRECTORY=

@echo on

ftpget.bat

@echo off

SET FTPADDRESS=%1
SET FTPUSERNAME=%2
SET FTPPASSWORD=%3
SET LOCALDIR=%~f4
SET REMOTEDIR=%5
SET REMOTEFILE=%6

if "%FTPADDRESS%" == "" goto FTP_UPLOAD_USAGE
if "%FTPUSERNAME%" == "" goto FTP_UPLOAD_USAGE
if "%FTPPASSWORD%" == "" goto FTP_UPLOAD_USAGE
if "%LOCALDIR%" == "" goto FTP_UPLOAD_USAGE
if not defined REMOTEDIR goto FTP_UPLOAD_USAGE
if not defined REMOTEFILE goto FTP_UPLOAD_USAGE

:TEMP_NAME
set TMPFILE=%TMP%\%RANDOM%_ftpupload.tmp
if exist "%TMPFILE%" goto TEMP_NAME 

echo user %FTPUSERNAME% %FTPPASSWORD% > %TMPFILE%
echo bin >> %TMPFILE%
echo lcd %LOCALDIR% >> %TMPFILE%

echo cd "%REMOTEDIR%" >> %TMPFILE%
echo mget "%REMOTEFILE%" >> %TMPFILE%
echo quit >> %TMPFILE%

ftp -n -i "-s:%TMPFILE%" %FTPADDRESS%

del %TMPFILE%

goto FTP_UPLOAD_EXIT

:FTP_UPLOAD_USAGE

echo Usage: ftpget [address] [username] [password] [local directory] [remote directory] [remote file pattern]
echo.

:FTP_UPLOAD_EXIT

set FTPADDRESS=
set FTPUSERNAME=
set FTPPASSWORD=
set LOCALDIR=
set REMOTEFILE=
set REMOTEDIR=
set TMPFILE=
set CURRENT_DIRECTORY=
set RELATIVE_DIRECTORY=

@echo on

Including JavaScript class definition from another file in Node.js

If you append this to user.js:

exports.User = User;

then in server.js you can do:

var userFile = require('./user.js');
var User = userFile.User;

http://nodejs.org/docs/v0.4.10/api/globals.html#require

Another way is:

global.User = User;

then this would be enough in server.js:

require('./user.js');

Multiple aggregations of the same column using pandas GroupBy.agg()

TLDR; Pandas groupby.agg has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use

df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))

           Mean       Sum
dummy                    
1      0.036901  0.369012

OR

df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')

           Mean       Sum
dummy                    
1      0.036901  0.369012

Pandas >= 0.25: Named Aggregation

Pandas has changed the behavior of GroupBy.agg in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.

From the documentation,

To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in GroupBy.agg(), known as “named aggregation”, where

  • The keywords are the output column names
  • The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.

You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>).

import pandas as pd

pd.__version__                                                                                                                            
# '0.25.0.dev0+840.g989f912ee'

# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                   'height': [9.1, 6.0, 9.5, 34.0],
                   'weight': [7.9, 7.5, 9.9, 198.0]
})

df.groupby('kind').agg(
    max_height=('height', 'max'), min_weight=('weight', 'min'),)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

Alternatively, you can use pd.NamedAgg (essentially a namedtuple) which makes things more explicit.

df.groupby('kind').agg(
    max_height=pd.NamedAgg(column='height', aggfunc='max'), 
    min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)

      max_height  min_weight
kind                        
cat          9.5         7.9
dog         34.0         7.5

It is even simpler for Series, just pass the aggfunc to a keyword argument.

df.groupby('kind')['height'].agg(max_height='max', min_height='min')    

      max_height  min_height
kind                        
cat          9.5         9.1
dog         34.0         6.0       

Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:

df.groupby('kind')['height'].agg(**{'max height': 'max', ...})

Pandas < 0.25

In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning:

df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed 
# in a future version

Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.

df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})

        returns          
            op1       op2
dummy                    
1      0.328953  0.032895

Or,

df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])

            op1       op2
dummy                    
1      0.328953  0.032895

How the single threaded non blocking IO model works in Node.js

Node.js is based on the event loop programming model. The event loop runs in single thread and repeatedly waits for events and then runs any event handlers subscribed to those events. Events can be for example

  • timer wait is complete
  • next chunk of data is ready to be written to this file
  • theres a fresh new HTTP request coming our way

All of this runs in single thread and no JavaScript code is ever executed in parallel. As long as these event handlers are small and wait for yet more events themselves everything works out nicely. This allows multiple request to be handled concurrently by a single Node.js process.

(There's a little bit magic under the hood as where the events originate. Some of it involve low level worker threads running in parallel.)

In this SQL case, there's a lot of things (events) happening between making the database query and getting its results in the callback. During that time the event loop keeps pumping life into the application and advancing other requests one tiny event at a time. Therefore multiple requests are being served concurrently.

event loop high level view

According to: "Event loop from 10,000ft - core concept behind Node.js".

How to check whether a string is Base64 encoded or not

This works in Python:

import base64

def IsBase64(str):
    try:
        base64.b64decode(str)
        return True
    except Exception as e:
        return False

if IsBase64("ABC"):
    print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
else:
    print("ABC is NOT Base64-encoded.")

if IsBase64("QUJD"):
    print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
else:
    print("QUJD is NOT Base64-encoded.")

Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded.

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

Detect Browser Language in PHP

I think the cleanest way is this!

 <?php
  $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  $supportedLanguages=['en','fr','gr'];
  if(!in_array($lang,$supportedLanguages)){
     $lang='en';
  }
    require("index_".$lang.".php");

How can building a heap be O(n) time complexity?

It would be O(n log n) if you built the heap by repeatedly inserting elements. However, you can create a new heap more efficiently by inserting the elements in arbitrary order and then applying an algorithm to "heapify" them into the proper order (depending on the type of heap of course).

See http://en.wikipedia.org/wiki/Binary_heap, "Building a heap" for an example. In this case you essentially work up from the bottom level of the tree, swapping parent and child nodes until the heap conditions are satisfied.

How to set label size in Bootstrap

You'll have to do 2 things to make a Bootstrap label (or anything really) adjust sizes based on screen size:

  • Use a media query per display size range to adjust the CSS.
  • Override CSS sizing set by Bootstrap. You do this by making your CSS rules more specific than Bootstrap's. By default, Bootstrap sets .label { font-size: 75% }. So any extra selector on your CSS rule will make it more specific.

Here's an example CSS listing to accomplish what you are asking, using the default 4 sizes in Bootstrap:

@media (max-width: 767) {
    /* your custom css class on a parent will increase specificity */
    /* so this rule will override Bootstrap's font size setting */
    .autosized .label { font-size: 14px; }
}

@media (min-width: 768px) and (max-width: 991px) {
    .autosized .label { font-size: 16px; }
}

@media (min-width: 992px) and (max-width: 1199px) {
    .autosized .label { font-size: 18px; }
}

@media (min-width: 1200px) {
    .autosized .label { font-size: 20px; }
}

Here is how it could be used in the HTML:

<!-- any ancestor could be set to autosized -->
<div class="autosized">
    ...
        ...
            <span class="label label-primary">Label 1</span>
</div>

Indirectly referenced from required .class file

Add spring-tx jar file and it should settle it.

How do I do an OR filter in a Django query?

There is Q objects that allow to complex lookups. Example:

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))

Get IP address of visitors using Flask for Python

The user's IP address can be retrieved using the following snippet:

from flask import request
print(request.remote_addr)

"Fatal error: Unable to find local grunt." when running "grunt" command

You have to install grunt in your project folder

  1. create your package.json

    $ npm init
    
  2. install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json

    $ npm install grunt --save-dev
    
  3. then create gruntfile.js and run

    $ grunt 
    

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

Ahah! Checkout the previous commit, then checkout the master.

git checkout HEAD^
git checkout -f master

C char array initialization

The relevant part of C11 standard draft n1570 6.7.9 initialization says:

14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

and

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c; would be initialized within a function.

Finally,

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

[--]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

[--]

Thus, char being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.

Android lollipop change navigation bar color

You can change it directly in styles.xml file \app\src\main\res\values\styles.xml

This work on older versions, I was changing it in KitKat and come here.

receiving json and deserializing as List of object at spring mvc controller

Here is the code that works for me. The key is that you need a wrapper class.

public class Person {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

A PersonWrapper class

public class PersonWrapper {

    private List<Person> persons;

    /**
     * @return the persons
     */
    public List<Person> getPersons() {
        return persons;
    }

    /**
     * @param persons the persons to set
     */
    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

My Controller methods

@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
    @ResponseBody
    public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
        List<String> response = new ArrayList<String>();
        for (Person person: wrapper.getPersons()){
        personService.save(person);
         response.add("Saved person: " + person.toString());
    }
        return response;
    }

The request sent is json in POST

{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}

And the response is

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]

What is the 'new' keyword in JavaScript?

For beginners to understand it better

try out the following code in the browser console.

function Foo() { 
    return this; 
}

var a = Foo();       //returns window object
var b = new Foo();   //returns empty object of foo

a instanceof Window;  // true
a instanceof Foo;     // false

b instanceof Window;  // false
b instanceof Foo;     // true

Now you can read the community wiki answer :)

Find and replace string values in list

In case you're wondering about the performance of the different approaches, here are some timings:

In [1]: words = [str(i) for i in range(10000)]

In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop

In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop

In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop

In [5]: import re

In [6]: r = re.compile('1')

In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop

as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:

In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop

In [9]: r = re.compile('(1|324|567)')

In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop

This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.

How to duplicate a git repository? (without forking)

You can also use git-copy.

Install it with Gem,

gem install git-copy

Then

git copy https://github.com/exampleuser/old-repository.git \
    https://github.com/exampleuser/new-repository.git

What's the difference between commit() and apply() in SharedPreferences

  • commit() is synchronously, apply() is asynchronous

  • apply() is void function.

  • commit() returns true if the new values were successfully written to persistent storage.

  • apply() guarantees complete before switching states , you don't need to worry about Android component lifecycles

If you dont use value returned from commit() and you're using commit() from main thread, use apply() instead of commit()

ASP.Net MVC: Calling a method from a view

You should create custom helper for just changing string format except using controller call.

Download and save PDF file with Python requests module

In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.

from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

How can I build multiple submit buttons django form?

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

How to get a value from the last inserted row?

Don't use SELECT currval('MySequence') - the value gets incremented on inserts that fail.

UITextField text change event

Swift 3 Version

yourTextField.addTarget(self, action: #selector(YourControllerName.textChanges(_:)), for: UIControlEvents.editingChanged)

And get the changes in here

func textChanges(_ textField: UITextField) {
    let text = textField.text! // your desired text here
    // Now do whatever you want.
}

Hope it helps.

SASS - use variables across multiple files

This answer shows how I ended up using this and the additional pitfalls I hit.

I made a master SCSS file. This file must have an underscore at the beginning for it to be imported:

// assets/_master.scss 
$accent: #6D87A7;           
$error: #811702;

Then, in the header of all of my other .SCSS files, I import the master:

// When importing the master, you leave out the underscore, and it
// will look for a file with the underscore. This prevents the SCSS
// compiler from generating a CSS file from it.
@import "assets/master";

// Then do the rest of my CSS afterwards:
.text { color: $accent; }

IMPORTANT

Do not include anything but variables, function declarations and other SASS features in your _master.scss file. If you include actual CSS, it will duplicate this CSS across every file you import the master into.

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

How to upgrade docker container after its image changed

I would like to add that if you want to do this process automatically (download, stop and restart a new container with the same settings as described by @Yaroslav) you can use WatchTower. A program that auto updates your containers when they are changed https://github.com/v2tec/watchtower

How do I call a dynamically-named method in Javascript?

you can do it like this:

function MyClass() {
    this.abc = function() {
        alert("abc");
    }
}

var myObject = new MyClass();
myObject["abc"]();

Pandas - Plotting a stacked Bar Chart

If you want to change the size of plot the use arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))

How to add constraints programmatically using Swift

Try this elegant UIView extension for constraints. You can do constraints easy as:


 - firstView.coverWholeSuperview()
 - firstView.constraints(size: CGSize(width: 44, height: 44), centerX: view.centerXAnchor, centerY: view.centerXAnchor)
 - firstView.constraints(top: view.topAnchor, 
                         leading: secondView.leadingAnchor, 
                         bottom: view.bottomAnchor, 
                         trailing: secondView.trailingAnchor, 
                         padding: UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12))

Here is extension, just copy it to your project.

extension UIView {
    /// Attaches all sides of the receiver to its parent view
    func coverWholeSuperview(margin: CGFloat = 0.0) {
        let view = superview
        layoutAttachTop(to: view, margin: margin)
        layoutAttachBottom(to: view, margin: margin)
        layoutAttachLeading(to: view, margin: margin)
        layoutAttachTrailing(to: view, margin: margin)

    }

    /// Attaches the top of the current view to the given view's top if it's a superview of the current view
    /// or to it's bottom if it's not (assuming this is then a sibling view).
    @discardableResult
    func layoutAttachTop(to: UIView? = nil, margin: CGFloat = 0.0) -> NSLayoutConstraint {

        let view: UIView? = to ?? superview
        let isSuperview = view == superview
        let constraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal,
                                            toItem: view, attribute: isSuperview ? .top : .bottom, multiplier: 1.0,
                                            constant: margin)
        superview?.addConstraint(constraint)

        return constraint
    }

    /// Attaches the bottom of the current view to the given view
    @discardableResult
    func layoutAttachBottom(to: UIView? = nil, margin: CGFloat = 0.0, priority: UILayoutPriority? = nil) -> NSLayoutConstraint {

        let view: UIView? = to ?? superview
        let isSuperview = (view == superview) || false
        let constraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal,
                                            toItem: view, attribute: isSuperview ? .bottom : .top, multiplier: 1.0,
                                            constant: -margin)
        if let priority = priority {
            constraint.priority = priority
        }
        superview?.addConstraint(constraint)

        return constraint
    }

    /// Attaches the leading edge of the current view to the given view
    @discardableResult
    func layoutAttachLeading(to: UIView? = nil, margin: CGFloat = 0.0) -> NSLayoutConstraint {

        let view: UIView? = to ?? superview
        let isSuperview = (view == superview) || false
        let constraint = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal,
                                            toItem: view, attribute: isSuperview ? .leading : .trailing, multiplier: 1.0,
                                            constant: margin)
        superview?.addConstraint(constraint)

        return constraint
    }

    /// Attaches the trailing edge of the current view to the given view
    @discardableResult
    func layoutAttachTrailing(to: UIView? = nil, margin: CGFloat = 0.0, priority: UILayoutPriority? = nil) -> NSLayoutConstraint {

        let view: UIView? = to ?? superview
        let isSuperview = (view == superview) || false
        let constraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal,
                                            toItem: view, attribute: isSuperview ? .trailing : .leading, multiplier: 1.0,
                                            constant: -margin)
        if let priority = priority {
            constraint.priority = priority
        }
        superview?.addConstraint(constraint)

        return constraint
    }

    // For anchoring View
    struct AnchoredConstraints {
        var top, leading, bottom, trailing, width, height, centerX, centerY: NSLayoutConstraint?
    }

    @discardableResult
    func constraints(top: NSLayoutYAxisAnchor? = nil, leading: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil,
                trailing: NSLayoutXAxisAnchor? = nil, padding: UIEdgeInsets = .zero, size: CGSize = .zero,
                centerX: NSLayoutXAxisAnchor? = nil, centerY: NSLayoutYAxisAnchor? = nil,
                centerXOffset: CGFloat = 0, centerYOffset: CGFloat = 0) -> AnchoredConstraints {

        translatesAutoresizingMaskIntoConstraints = false
        var anchoredConstraints = AnchoredConstraints()

        if let top = top {
            anchoredConstraints.top = topAnchor.constraint(equalTo: top, constant: padding.top)
        }

        if let leading = leading {
            anchoredConstraints.leading = leadingAnchor.constraint(equalTo: leading, constant: padding.left)
        }

        if let bottom = bottom {
            anchoredConstraints.bottom = bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom)
        }

        if let trailing = trailing {
            anchoredConstraints.trailing = trailingAnchor.constraint(equalTo: trailing, constant: -padding.right)
        }

        if size.width != 0 {
            anchoredConstraints.width = widthAnchor.constraint(equalToConstant: size.width)
        }

        if size.height != 0 {
            anchoredConstraints.height = heightAnchor.constraint(equalToConstant: size.height)
        }

        if let centerX = centerX {
            anchoredConstraints.centerX = centerXAnchor.constraint(equalTo: centerX, constant: centerXOffset)
        }

        if let centerY = centerY {
            anchoredConstraints.centerY = centerYAnchor.constraint(equalTo: centerY, constant: centerYOffset)
        }

        [anchoredConstraints.top, anchoredConstraints.leading, anchoredConstraints.bottom,
         anchoredConstraints.trailing, anchoredConstraints.width,
         anchoredConstraints.height, anchoredConstraints.centerX,
         anchoredConstraints.centerY].forEach { $0?.isActive = true }

        return anchoredConstraints
    }
}

Difference between innerText, innerHTML and value?

InnerText property html-encodes the content, turning <p> to &lt;p&gt;, etc. If you want to insert HTML tags you need to use InnerHTML.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

@NotNull is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. As Hibernate is the reference implementation of JSR 303, however, it intelligently picks up on these constraints and translates them into database constraints for you, so you get two for the price of one. @Column(nullable = false) is the JPA way of declaring a column to be not-null. I.e. the former is intended for validation and the latter for indicating database schema details. You're just getting some extra (and welcome!) help from Hibernate on the validation annotations.

Set date input field's max date to today

A short but may be less readable version of one of the previous answers.

   <script type="text/javascript">
    $(document).ready(DOM_Load);

    function DOM_Load (e) {
        $("#datefield").on("click", dateOfBirth_Click);
    }

    function dateOfBirth_Click(e) {
        let today = new Date();
        $("#datefield").prop("max", `${today.getUTCFullYear()}-${(today.getUTCMonth() + 1).toString().padStart(2, "0")}-${today.getUTCDate().toString().padStart(2, "0")}`);
    }

</script>

Get characters after last / in url

Two one liners - I suspect the first one is faster but second one is prettier and unlike end() and array_pop(), you can pass the result of a function directly to current() without generating any notice or warning since it doesn't move the pointer or alter the array.

$var = 'http://www.vimeo.com/1234567';

// VERSION 1 - one liner simmilar to DisgruntledGoat's answer above
echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0));

// VERSION 2 - explode, reverse the array, get the first index.
echo current(array_reverse(explode('/',$var)));

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

replace

implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

with

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Since the version with jre is absolute , just replace and sync the project

Official Documentation here Thanks for the link @ ROMANARMY

Happy Coding :)

"Missing return statement" within if / for / while

Try with, as if if condition returns false, so it will return empty otherwise nothing to return.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
return ""
}

Because the compiler doesn't know if any of those if blocks will ever be reached, so it's giving you an error.

Vertically center text in a 100% height div?

I disagree, here's a JS free solution, which works:

<html style="height: 100%;">
    <body style="vertical-align: middle; margin: 0px; height: 100%;">
        <div style="height: 100%; width: 100%; display: table; background-color: #ccc;">
            <div style="display: table-cell; width: 100%; vertical-align: middle;">
                <div style="height: 300px; width: 600px; background-color: wheat; margin-left: auto; margin-right: auto;">A</div>
            </div>
        </div>
    </body>
</html>

How to retrieve all keys (or values) from a std::map and put them into a vector?

The best non-sgi, non-boost STL solution is to extend map::iterator like so:

template<class map_type>
class key_iterator : public map_type::iterator
{
public:
    typedef typename map_type::iterator map_iterator;
    typedef typename map_iterator::value_type::first_type key_type;

    key_iterator(const map_iterator& other) : map_type::iterator(other) {} ;

    key_type& operator *()
    {
        return map_type::iterator::operator*().first;
    }
};

// helpers to create iterators easier:
template<class map_type>
key_iterator<map_type> key_begin(map_type& m)
{
    return key_iterator<map_type>(m.begin());
}
template<class map_type>
key_iterator<map_type> key_end(map_type& m)
{
    return key_iterator<map_type>(m.end());
}

and then use them like so:

        map<string,int> test;
        test["one"] = 1;
        test["two"] = 2;

        vector<string> keys;

//      // method one
//      key_iterator<map<string,int> > kb(test.begin());
//      key_iterator<map<string,int> > ke(test.end());
//      keys.insert(keys.begin(), kb, ke);

//      // method two
//      keys.insert(keys.begin(),
//           key_iterator<map<string,int> >(test.begin()),
//           key_iterator<map<string,int> >(test.end()));

        // method three (with helpers)
        keys.insert(keys.begin(), key_begin(test), key_end(test));

        string one = keys[0];

How to read a file in other directory in python

For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

should actually be

x_file = open(os.path.join('direct', "5_1.txt"), "r")   

Adding two Java 8 streams, or an extra element to a stream

If you add static imports for Stream.concat and Stream.of, the first example could be written as follows:

Stream<Foo> stream = concat(stream1, concat(stream2, of(element)));

Importing static methods with generic names can result in code that becomes difficult to read and maintain (namespace pollution). So, it might be better to create your own static methods with more meaningful names. However, for demonstration I will stick with this name.

public static <T> Stream<T> concat(Stream<? extends T> lhs, Stream<? extends T> rhs) {
    return Stream.concat(lhs, rhs);
}
public static <T> Stream<T> concat(Stream<? extends T> lhs, T rhs) {
    return Stream.concat(lhs, Stream.of(rhs));
}

With these two static methods (optionally in combination with static imports), the two examples could be written as follows:

Stream<Foo> stream = concat(stream1, concat(stream2, element));

Stream<Foo> stream = concat(
                         concat(stream1.filter(x -> x!=0), stream2).filter(x -> x!=1),
                         element)
                     .filter(x -> x!=2);

The code is now significantly shorter. However, I agree that the readability hasn't improved. So I have another solution.


In a lot of situations, Collectors can be used to extend the functionality of streams. With the two Collectors at the bottom, the two examples could be written as follows:

Stream<Foo> stream = stream1.collect(concat(stream2)).collect(concat(element));

Stream<Foo> stream = stream1
                     .filter(x -> x!=0)
                     .collect(concat(stream2))
                     .filter(x -> x!=1)
                     .collect(concat(element))
                     .filter(x -> x!=2);

The only difference between your desired syntax and the syntax above is, that you have to replace concat(...) with collect(concat(...)). The two static methods can be implemented as follows (optionally used in combination with static imports):

private static <T,A,R,S> Collector<T,?,S> combine(Collector<T,A,R> collector, Function<? super R, ? extends S> function) {
    return Collector.of(
        collector.supplier(),
        collector.accumulator(),
        collector.combiner(),
        collector.finisher().andThen(function));
}
public static <T> Collector<T,?,Stream<T>> concat(Stream<? extends T> other) {
    return combine(Collectors.toList(),
        list -> Stream.concat(list.stream(), other));
}
public static <T> Collector<T,?,Stream<T>> concat(T element) {
    return concat(Stream.of(element));
}

Of course there is a drawback with this solution that should be mentioned. collect is a final operation that consumes all elements of the stream. On top of that, the collector concat creates an intermediate ArrayList each time it is used in the chain. Both operations can have a significant impact on the behaviour of your program. However, if readability is more important than performance, it might still be a very helpful approach.

lexical or preprocessor issue file not found occurs while archiving?

In my case I was developing a framework and had a test application inside it, what was missing is inside the test application target -> build settings -> Framework Search Paths:

  • The value needed to be the framework path (the build output - .framework) which is in my case: "../FrameworkNameFolder/" - the 2 points indicates to go one folder up.

Also, inside the test application target -> Build Phases -> Link Binary With Libraries:

  • I had to remove the framework file, clean the project, add the framework file again, compile and this also solved the issue.

indexOf Case Sensitive?

Converting both strings to lower-case is usually not a big deal but it would be slow if some of the strings is long. And if you do this in a loop then it would be really bad. For this reason, I would recommend indexOfIgnoreCase.

Checking if an input field is required using jQuery

A little bit of a more complete answer, inspired by the accepted answer:

$( '#form_id' ).submit( function( event ) {
        event.preventDefault();

        //validate fields
        var fail = false;
        var fail_log = '';
        var name;
        $( '#form_id' ).find( 'select, textarea, input' ).each(function(){
            if( ! $( this ).prop( 'required' )){

            } else {
                if ( ! $( this ).val() ) {
                    fail = true;
                    name = $( this ).attr( 'name' );
                    fail_log += name + " is required \n";
                }

            }
        });

        //submit if fail never got set to true
        if ( ! fail ) {
            //process form here.
        } else {
            alert( fail_log );
        }

});

In this case we loop all types of inputs and if they are required, we check if they have a value, and if not, a notice that they are required is added to the alert that will run.

Note that this, example assumes the form will be proceed inside the positive conditional via AJAX or similar. If you are submitting via traditional methods, move the second line, event.preventDefault(); to inside the negative conditional.

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

How to change screen resolution of Raspberry Pi

After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.enter image description here

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Either of these methods may be "better", i.e. more suitable, depending on what you want to do.

A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.

A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.

How to execute a MySQL command from a shell script?

Use

echo "your sql script;" | mysql -u -p -h db_name

Convert form data to JavaScript object with jQuery

This function should handle multidimensional arrays along with multiple elements with the same name.

I've been using it for a couple years so far:

jQuery.fn.serializeJSON=function() {
  var json = {};
  jQuery.map(jQuery(this).serializeArray(), function(n, i) {
    var _ = n.name.indexOf('[');
    if (_ > -1) {
      var o = json;
      _name = n.name.replace(/\]/gi, '').split('[');
      for (var i=0, len=_name.length; i<len; i++) {
        if (i == len-1) {
          if (o[_name[i]]) {
            if (typeof o[_name[i]] == 'string') {
              o[_name[i]] = [o[_name[i]]];
            }
            o[_name[i]].push(n.value);
          }
          else o[_name[i]] = n.value || '';
        }
        else o = o[_name[i]] = o[_name[i]] || {};
      }
    }
    else {
      if (json[n.name] !== undefined) {
        if (!json[n.name].push) {
          json[n.name] = [json[n.name]];
        }
        json[n.name].push(n.value || '');
      }
      else json[n.name] = n.value || '';      
    }
  });
  return json;
};

UTF-8 encoded html pages show ? (questions marks) instead of characters

Tell PDO your charset initially.... something like

PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);

Notice the: charset=utf8; part.

hope it helps!

Where does this come from: -*- coding: utf-8 -*-

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

Combine [NgStyle] With Condition (if..else)

The previous answers did not work for me, so I decided to improve this.

You should work with url(''), and not with value.

<li *ngFor="let item of items">
  <div
    class="img-wrapper"
    [ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
  </div>
</li>

Deleting an element from an array in PHP

It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [3]=>
  int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

How to stop an unstoppable zombie job on Jenkins without restarting the server?

I usually use jenkins-cli in such cases. You can download the jar from a page http://your-jenkins-host:PORT/cli . Then run

java -jar jenkins-cli.jar delete-builds name_of_job_to_delete hanging_job_number

Auxiliary info:

You may also pass a range of builds like 350:400. General help available by running

java -jar jenkins-cli.jar help

Context command help for delete-builds by

java -jar jenkins-cli.jar delete-builds

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

Base64 encoding in SQL Server 2005 T-SQL

You can use just:

Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)

then after encoding you'll receive text 'MjE4Nqk5'

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Change the project theme in Android Studio?

Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles

Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.enter image description here

Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

  • Theme.Holo for a "dark" theme.
  • Theme.Holo.Light for a "light" theme.

When using the Support Library, you must instead use the Theme.AppCompat themes:

  • Theme.AppCompat for the "dark" theme.
  • Theme.AppCompat.Light for the "light" theme.
  • Theme.AppCompat.Light.DarkActionBar for the light theme with a dark action bar.

Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x

Python Hexadecimal

Another solution is:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

C#: Waiting for all threads to complete

With .NET 4.0 I find System.Threading.Tasks a lot easier to work with. Here's spin-wait loop which works reliably for me. It blocks the main thread until all the tasks complete. There's also Task.WaitAll, but that hasn't always worked for me.

        for (int i = 0; i < N; i++)
        {
            tasks[i] = Task.Factory.StartNew(() =>
            {               
                 DoThreadStuff(localData);
            });
        }
        while (tasks.Any(t => !t.IsCompleted)) { } //spin wait

How to get the 'height' of the screen using jquery

$(window).height();

To set anything in the middle you can use CSS.

<style>
#divCentre 
{ 
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 400px;
    margin-left: -150px;
    margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Some great help found here. However, I still could not make it to work despite loading JAR properly. I found out later that I accidentally created module in the file structure instead of regular folder and this very module was pre-selected in the project setting.

Here is the footprint:

File -> Project Structure -> Modules -> (select proper module if you have more) -> Dependencies -> + -> JAR or Libraries

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

If you need to allow html input for action-method parameter (opposed to "model property") there's no built-in way to do that but you can easily achieve this using a custom model binder:

public ActionResult AddBlogPost(int userId,
    [ModelBinder(typeof(AllowHtmlBinder))] string htmlBody)
{
    //...
}

The AllowHtmlBinder code:

public class AllowHtmlBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        var name = bindingContext.ModelName;
        return request.Unvalidated[name]; //magic happens here
    }
}

Find the complete source code and the explanation in my blog post: https://www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-particular-action-parameters/

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

How to check if a double value has no decimal part

Compare two values: the normal double, and the double after flooring it. If they are the same value, there is no decimal component.

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

Git: Remove committed file after push

You can revert only one file to a specified revision.

First you can check on which commits the file was changed.

git log path/to/file.txt

Then you can checkout the file with the revision number.

git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt

After that you can commit and push it again.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Employees.objects.values_list('eng_name', flat=True)

That creates a flat list of all eng_names. If you want more than one field per row, you can't do a flat list: this will create a list of tuples:

Employees.objects.values_list('eng_name', 'rank')

Open Sublime Text from Terminal in macOS

There is a easy way to do this. It only takes a couple steps and you don't need to use the command line too much. If you new to the command line this is the way to do it.

Step 1 : Finding the bin file to put the subl executable file in

  1. Open up the terminal
  2. type in cd .. ---------------------this should go back a directory
  3. type in ls ------------------------to see a list of files in the directory
  4. type in cd .. ---------------------until you get a folder that contains usr
  5. type in open usr ---------------this should open the finder and you should see some folders
  6. open up the bin folder -------this is where you will copy your sublime executable file.

Step 2: Finding the executable file

  1. open up the finder
  2. Under file open up a new finder window (CMD + N)
  3. Navigate to applications folder
  4. find Sublime Text and right click so you get a pulldown menu
  5. Click on Show Package Content
  6. Open up Content/SharedSupport/bin
  7. Copy the subl file
  8. Paste it in the bin folder in the usr folder we found earlier
  9. In the terminal type in subl --------------this should open Sublime Text

Make sure that it gets copied and it's not a shortcut. If you do have a problem, view the usr/bin folder as icons and paste the subl in a empty area in the folder. It should not have a shortcut arrow in the icon image.

Get the (last part of) current directory name in C#

This works perfectly fine with me :)

Path.GetFileName(path.TrimEnd('\\')

What causing this "Invalid length for a Base-64 char array"

As others have mentioned this can be caused when some firewalls and proxies prevent access to pages containing a large amount of ViewState data.

ASP.NET 2.0 introduced the ViewState Chunking mechanism which breaks the ViewState up into manageable chunks, allowing the ViewState to pass through the proxy / firewall without issue.

To enable this feature simply add the following line to your web.config file.

<pages maxPageStateFieldLength="4000">

This should not be used as an alternative to reducing your ViewState size but it can be an effective backstop against the "Invalid length for a Base-64 char array" error resulting from aggressive proxies and the like.

Launch custom android application from android browser

The following link gives information on launching the app (if installed) directly from browser. Otherwise it directly opens up the app in play store so that user can seamlessly download.

https://developer.chrome.com/multidevice/android/intents

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

Make an Installation program for C# applications and include .NET Framework installer into the setup

WiX is the way to go for new installers. If WiX alone is too complicated or not flexible enough on the GUI side consider using SharpSetup - it allows you to create installer GUI in WinForms of WPF and has other nice features like translations, autoupdater, built-in prerequisites, improved autocompletion in VS and more.

(Disclaimer: I am the author of SharpSetup.)

How to view Plugin Manager in Notepad++

Notepad v7.6 includes a Plugin Admin and from this you can install Plugin Manager(note1) but it doesn't work fine with npp v7.6(note2)

On the other hand Plugin Admin is only available on NPP "Setup version" and after following conditions

  • on Custom installation, "Plugin Admin" checkbox is enabled
  • on Choose Components "Don't use %APPDATA%" checkbox is disabled

Plugin Admin will place plugins at C:\ProgramData\Notepad++\plugins

(note1)Installation from Plugin Admin is not complete and \updater\gpup.exe is missing (note2) Plugin manager is not using new plugins path and folder structure; from version 7.6 npp Plugins will be stored in individual folders (having same name than file.dll)

If you want to use npp7.6 portable, you can copy updater folder from Setup version, copy plugins from Setup version, or copy Plugins from npp v<7.6 and place each one in a individual folder.

![Plugin Admin feature Installation npp76 Install Plugin manager from Plugin Admin

Passing Objects By Reference or Value in C#

One more code sample to showcase this:

void Main()
{


    int k = 0;
    TestPlain(k);
    Console.WriteLine("TestPlain:" + k);

    TestRef(ref k);
    Console.WriteLine("TestRef:" + k);

    string t = "test";

    TestObjPlain(t);
    Console.WriteLine("TestObjPlain:" +t);

    TestObjRef(ref t);
    Console.WriteLine("TestObjRef:" + t);
}

public static void TestPlain(int i)
{
    i = 5;
}

public static void TestRef(ref int i)
{
    i = 5;
}

public static void TestObjPlain(string s)
{
    s = "TestObjPlain";
}

public static void TestObjRef(ref string s)
{
    s = "TestObjRef";
}

And the output:

TestPlain:0

TestRef:5

TestObjPlain:test

TestObjRef:TestObjRef

How can I remove leading and trailing quotes in SQL Server?

Some UDFs for re-usability.

Left Trimming by character (any number)

CREATE FUNCTION [dbo].[LTRIMCHAR] (@Input NVARCHAR(max), @TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
      RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(@Input,' ','¦'), @TrimChar, ' ')), ' ', @TrimChar),'¦',' ')
END

Right Trimming by character (any number)

CREATE FUNCTION [dbo].[RTRIMCHAR] (@Input NVARCHAR(max), @TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
     RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(@Input,' ','¦'), @TrimChar, ' ')), ' ', @TrimChar),'¦',' ')
END

Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).

Largest and smallest number in an array

   static void PrintSmallestLargest(int[] arr)
    {
        if (arr.Length > 0)
        {
            int small = arr[0];
            int large = arr[0];
            for (int i = 0; i < arr.Length; i++)
            {
                if (large < arr[i])
                {
                    int tmp = large;
                    large = arr[i];
                    arr[i] = large;
                }
                if (small > arr[i])
                {
                    int tmp = small;
                    small = arr[i];
                    arr[i] = small;
                }
            }
            Console.WriteLine("Smallest is {0}", small);
            Console.WriteLine("Largest is {0}", large);
        }
    }

This way you can have smallest and largest number in a single loop.

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

Stopping Excel Macro executution when pressing Esc won't work

My laptop did not have Break nor Scr Lock, so I somehow managed to make it work by pressing Ctrl + Function + Right Shift (to activate 'pause').

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

Static linking vs dynamic linking

Another consideration is the number of object files (translation units) that you actually consume in a library vs the total number available. If a library is built from many object files, but you only use symbols from a few of them, this might be an argument for favoring static linking, since you only link the objects that you use when you static link (typically) and don't normally carry the unused symbols. If you go with a shared lib, that lib contains all translation units and could be much larger than what you want or need.

Unit Testing C Code

Michael Feather's book "Working Effectively with Legacy Code" presents a lot of techniques specific to unit testing during C development.

There are techniques related to dependency injection that are specific to C which I haven't seen anywhere else.

Find Item in ObservableCollection without using a loop

I Don't know what do you mean exactly, but technially speaking, this is not possible without a loop.

May be you mean using a LINQ, like for example:

list.Where(x=>x.Title == title)

It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.

Hope this helps.

EDIT

In other words if you really concerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.

Loop through all the resources in a .resx file

The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.

Alternatively, you can use reflection to loop through these names.

Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
    BindingFlags.NonPublic | 
    BindingFlags.Static | 
    BindingFlags.GetProperty);

foreach (PropertyInfo info in resourceProps)
{
    string name = info.Name;
    object value = info.GetValue(null, null);  // object can be an image, a string whatever
    // do something with name and value
}

This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".

The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.

Which is faster: Stack allocation or Heap allocation

Probably the biggest problem of heap allocation versus stack allocation, is that heap allocation in the general case is an unbounded operation, and thus you can't use it where timing is an issue.

For other applications where timing isn't an issue, it may not matter as much, but if you heap allocate a lot, this will affect the execution speed. Always try to use the stack for short lived and often allocated memory (for instance in loops), and as long as possible - do heap allocation during application startup.