Programs & Examples On #Plugins

A plug-in (or plugin) is a set of software components that adds specific abilities to a larger software application. If supported, plug-ins enable customizing the functionality of an application.

"Gradle Version 2.10 is required." Error

If the problem persist, add the following code in the build.gradle of the top project.

buildscript {
System.properties['com.android.build.gradle.overrideVersionCheck'] = 'true'

...
}

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

How to install plugins to Sublime Text 2 editor?

Installation code chunks for vanilla Sublime may change in the future.

This link would be the safest place to install plugin support to Sublime Text 2.

For Sublime Text 3 this link works has the code.

enter image description here

Embedding VLC plugin on HTML page

Unfortunately, IE and VLC don't really work right now... I found this on the vlc forums:

VLC included activex support up until version 0.8.6, I believe. At that time, you could
access a cab on the videolan and therefore 'automatic' installation into IE and Firefox
family browsers was fine. Thereafter support for activex seemed to stop; no cab, no
activex component.

VLC 1.0.* once again contains activex support, and that's brilliant. A good decision in
my opinion. What's lacking is a cab installer for the latest version.

This basically means that even if you found a way to make it work, anyone trying to view the video on your site in IE would have to download and install the entire VLC player program to have it work in IE, and users probably don't want to do that. I can't get your code to work in firefox or IE8 on my boyfriends computer, although I might not have been putting the video address in properly... I get some message about no video output...

I'll take a guess and say it probably works for you locally because you have VLC installed, but your server doesn't. Unfortunately you'll probably have to use Windows media player or something similar (Microsoft is great at forcing people to use their stuff!)

And if you're wondering, it appears that the reason there is no cab file is because of the cost of having an active-x control signed.

It's rather simple to have your page use VLC for firefox and chrome users, and Windows Media Player for IE users, if that would work for you.

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

Just start your browser with superuser rights, and don't forget to set Java's JRE security to medium.

How to: Install Plugin in Android Studio

  1. Launch Android Studio application
  2. Choose Project Settings
  3. Choose Plugin from disk, if on disk then choose that location of *.jar, in my case is GenyMotion jar
  4. Click on Apply and OK.
  5. Then Android studio will ask for Restart.

That's all Folks! enter image description here

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

How to download PDF automatically using js?

Please try this

_x000D_
_x000D_
(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
_x000D_
_x000D_
_x000D_

Or use download attribute to tag in HTML5

How to get the current plugin directory in WordPress?

This will actually get the result you want:

<?php plugin_dir_url(__FILE__); ?>

http://codex.wordpress.org/Function_Reference/plugin_dir_url

How do I make CMake output into a 'bin' dir?

As in Oleg's answer, I believe the correct variable to set is CMAKE_RUNTIME_OUTPUT_DIRECTORY. We use the following in our root CMakeLists.txt:

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

You can also specify the output directories on a per-target basis:

set_target_properties( targets...
    PROPERTIES
    ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

In both cases you can append _[CONFIG] to the variable/property name to make the output directory apply to a specific configuration (the standard values for configuration are DEBUG, RELEASE, MINSIZEREL and RELWITHDEBINFO).

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

How to view Plugin Manager in Notepad++

The way to install plugins seems to have changed, the previous answers here did not work for me.

The current (checked with 7.8.1) way to install plugins is to install it in a sub folder:

The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension. For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path: %PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll

from https://npp-user-manual.org/docs/plugins/

So PluginManager.dll goes into PluginManager sub folder.

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

How can I simulate mobile devices and debug in Firefox Browser?

You can use tools own browser (Firefox, IE, Chrome...) to debug your JavaScript.

As for resizing, Firefox/Chrome has own resources accessible via Ctrl + Shift + I OR F12. Going tab "style editor" and clicking "adaptive/responsive design" icon.

Old Firefox versions

Old Firefox

New Firefox/Firebug

Firefox

Chrome

Chrome

*Another way is to install an addon like "Web Developer"

JUnit Eclipse Plugin?

It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").

Installing Apache Maven Plugin for Eclipse

m2eclipse has moved from sonatype to eclipse.

The correct update site is http://download.eclipse.org/technology/m2e/releases/

If this is not working, one possibility is you have an older version of Eclipse (< 3.6). The other - if you see timeout related errors - could be that you are behind a proxy server.

DLL Load Library - Error Code 126

This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

Adding <script> to WordPress in <head> element

I believe that codex.wordpress.org is your best reference to handle this task very well depends on your needs

check out these two pages on WordPress Codex:

wp_enqueue_script

wp_enqueue_style

How to install a Notepad++ plugin offline?

Here are the steps that worked for me:

  1. Download the plugin and extract the plugin dll file.
  2. Place the plugin.dll file under plugin folder of notepad++ installation. For me it was : C:\Program Files\Notepad++\plugins
  3. Go to Notepad++ then : Settings -> Import -> Import plugin (import the plugin).
  4. Notepad++ will show the restart message / Sometimes it may not show it.
  5. Restart the notepad++.
  6. Should see new plugin under the Plugins menu. ALL DONE!!

How can I get query string values in JavaScript?

ES2015 (ES6)

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

Without jQuery

var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

With an URL like ?topic=123&name=query+string, the following will return:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)

Google method

Tearing Google's code I found the method they use: getUrlParameters

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}

It is obfuscated, but it is understandable. It does not work because some variables are undefined.

They start to look for parameters on the url from ? and also from the hash #. Then for each parameter they split in the equal sign b[f][p]("=") (which looks like indexOf, they use the position of the char to get the key/value). Having it split they check whether the parameter has a value or not, if it has then they store the value of d, otherwise they just continue.

In the end the object d is returned, handling escaping and the + sign. This object is just like mine, it has the same behavior.


My method as a jQuery plugin

(function($) {
    $.QueryString = (function(paramsArray) {
        let params = {};

        for (let i = 0; i < paramsArray.length; ++i)
        {
            let param = paramsArray[i]
                .split('=', 2);
            
            if (param.length !== 2)
                continue;
            
            params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
        }
            
        return params;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

Usage

//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"

//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }

//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object

//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue&param2=val"

//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));

Performance test (split method against regex method) (jsPerf)

Preparation code: methods declaration

Split test code

var qs = window.GetQueryString(query);

var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];

Regex test code

var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");

Testing in Firefox 4.0 x86 on Windows Server 2008 R2 / 7 x64

  • Split method: 144,780 ±2.17% fastest
  • Regex method: 13,891 ±0.85% | 90% slower

Recommended add-ons/plugins for Microsoft Visual Studio

If vi/vim editing is your thang:

ViEmu for Visual Studio

If you want color-coded control-flow syntax-highlighting and graphical outlines:

Codekana

I'm the developer of these commercial tools.

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

I'm on Windows 7 64 bit and couldn't understand if I can manually enable JRE8 64 bit for Chrome. Turned out that my problem was that Java plugin DLL is 64 bit which wouldn't work in 32 bit Chrome. Therefore you need to install x86 version of JRE. Below are Windows registry settings you need to create

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"Path"="C:\\Program Files (x86)\\Java\\jre8\\bin\\plugin2\\npjp2.dll"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="1.8.0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;jpi-version=1.8.0]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.1.3]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.2.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.3.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.1]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.4.2]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.5]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.6]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.7]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-applet;version=1.8]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm]
"Description"="Java™ Virtual Machine"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin,version=11.0.2\MimeTypes\application/x-java-vm-npruntime]
"Description"="Java™ Applet"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin]
"Description"="Oracle® Next Generation Java™ Plug-In"
"GeckoVersion"="1.9"
"ProductName"="Oracle® Java™ Plug-In"
"Vendor"="Oracle Corp."
"Version"="160_29"
"Path"="C:\\Program Files\\Java\\jre8\\bin\\plugin2\\npjp2.dll"

JavaScript editor within Eclipse

Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS.

Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.

Force Internet Explorer to use a specific Java Runtime Environment install?

For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,

<OBJECT 
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200">
  <PARAM name="code" value="Applet1.class">
</OBJECT>

The classid attribute identifies which version of Java Plug-in to use.

Following is an alternative form of the classid attribute:

classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"

In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the specific version of Java Plug-in to be used.

For example, to use Java Plug-in version 1.5.0, you specify:

classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"

How do I list loaded plugins in Vim?

If you use vim-plug (Plug), " A minimalist Vim plugin manager.":

:PlugStatus

That will not only list your plugins but check their status.

Eclipse plugin for generating a class diagram

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

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

How to try convert a string to a Guid

new Guid(string)

You could also look at using a TypeConverter.

Use Device Login on Smart TV / Console

Facebook login for smarttv/devices without facebook sdk is possible throught code , check the documentation here :

https://developers.facebook.com/docs/facebook-login/for-devices

How to copy sheets to another workbook using vba?

I was able to copy all the sheets in a workbook that had a vba app running, to a new workbook w/o the app macros, with:

ActiveWorkbook.Sheets.Copy

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

jQuery checkbox checked state changed event

Try this "html-approach" which is acceptable for small JS projects

_x000D_
_x000D_
function msg(animal,is) {
  console.log(animal, is.checked);   // Do stuff
}
_x000D_
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
_x000D_
_x000D_
_x000D_

Dependent DLL is not getting copied to the build output folder in Visual Studio

Add the DLL as an existing item to one of the projects and it should be sorted

Assign width to half available screen width declaratively

Using constraints layout

  1. Add a Guideline
  2. Set the percentage to 50%
  3. Constrain your view to the Guideline and the parent.

enter image description here

If you are having trouble changing it to a percentage, then see this answer.

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="81dp">

    <android.support.constraint.Guideline
        android:id="@+id/guideline8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/guideline8"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    
</android.support.constraint.ConstraintLayout>

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

Angular ui-grid dynamically calculate height of the grid

A simpler approach is set use css combined with setting the minRowsToShow and virtualizationThreshold value dynamically.

In stylesheet:

.ui-grid, .ui-grid-viewport {
    height: auto !important;
}

In code, call the below function every time you change your data in gridOptions. maxRowToShow is the value you pre-defined, for my use case, I set it to 25.

ES5:

setMinRowsToShow(){
    //if data length is smaller, we shrink. otherwise we can do pagination.
    $scope.gridOptions.minRowsToShow = Math.min($scope.gridOptions.data.length, $scope.maxRowToShow);
    $scope.gridOptions.virtualizationThreshold = $scope.gridOptions.minRowsToShow ;
}

Remove a child with a specific attribute, in SimpleXML for PHP

For future reference, deleting nodes with SimpleXML can be a pain sometimes, especially if you don't know the exact structure of the document. That's why I have written SimpleDOM, a class that extends SimpleXMLElement to add a few convenience methods.

For instance, deleteNodes() will delete all nodes matching a XPath expression. And if you want to delete all nodes with the attribute "id" equal to "A5", all you have to do is:

// don't forget to include SimpleDOM.php
include 'SimpleDOM.php';

// use simpledom_load_string() instead of simplexml_load_string()
$data = simpledom_load_string(
    '<data>
        <seg id="A1"/>
        <seg id="A5"/>
        <seg id="A12"/>
        <seg id="A29"/>
        <seg id="A30"/>
    </data>'
);

// and there the magic happens
$data->deleteNodes('//seg[@id="A5"]');

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

The other answers don't seem to address why close() is really necessary? * 2

Doubt on the answer "HttpClient resource deallocation".

It is mentioned in old 3.x httpcomponents doc, which is long back and has a lot difference from 4.x HC. Besides the explanation is so brief that doesn't say what this underlying resource is.

I did some research on 4.5.2 release source code, found the implementations of CloseableHttpClient:close() basically only closes its connection manager.

(FYI) That's why when you use a shared PoolingClientConnectionManager and call client close(), exception java.lang.IllegalStateException: Connection pool shut down will occur. To avoid, setConnectionManagerShared works.

I prefer not do CloseableHttpClient:close() after every single request

I used to create a new http client instance when doing request and finally close it. In this case, it'd better not to call close(). Since, if connection manager doesn't have "shared" flag, it'll be shutdown, which is too expensive for a single request.

In fact, I also found in library clj-http, a Clojure wrapper over Apache HC 4.5, doesn't call close() at all. See func request in file core.clj

Plot correlation matrix using pandas

For completeness, the simplest solution i know with seaborn as of late 2019, if one is using Jupyter:

import seaborn as sns
sns.heatmap(dataframe.corr())

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

I want to remove double quotes from a String

If you want to remove all double quotes in string, use

var str = '"some "quoted" string"';
console.log( str.replace(/"/g, '') );
// some quoted string

Otherwise you want to remove only quotes around the string, use:

var str = '"some "quoted" string"';
console.log( clean = str.replace(/^"|"$/g, '') );
// some "quoted" string

Regular expression for URL validation (in JavaScript)

In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:

var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true

or

var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false

or

var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false

References for syntax:

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

jQuery: How to get the HTTP status code from within the $.ajax.error method?

If you're using jQuery 1.5, then statusCode will work.

If you're using jQuery 1.4, try this:

error: function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.status);
    alert(textStatus);
    alert(errorThrown);
}

You should see the status code from the first alert.

Can't install gems on OS X "El Capitan"

That is because of the new security function of OS X "El Capitan". Try adding --user-install instead of using sudo:

$ gem install *** --user-install

For example, if you want to install fake3 just use:

$ gem install fake3 --user-install

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

what does this mean ? image/png;base64?

They serve the actual image inside CSS so there will be less HTTP requests per page.

How to pass arguments to a Button command in Tkinter?

The best thing to do is use lambda as follows:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

how to add css class to html generic control div?

Alternative approach if you want to add a class to an existing list of classes of an element:

element.Attributes["class"] += " myCssClass";

How can I check if a View exists in a Database?

For people checking the existence to drop View use this

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

syntax

DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]

Query :

DROP VIEW IF EXISTS view_name

More info here

Check that a input to UITextField is numeric only

@property (strong) NSNumberFormatter *numberFormatter;
@property (strong) NSString *oldStringValue;

- (void)awakeFromNib 
{
  [super awakeFromNib];
  self.numberFormatter = [[NSNumberFormatter alloc] init];
  self.oldStringValue = self.stringValue;
  [self setDelegate:self];
}

- (void)controlTextDidChange:(NSNotification *)obj
{
  NSNumber *number = [self.numberFormatter numberFromString:self.stringValue];
  if (number) {
    self.oldStringValue = self.stringValue;
  } else {
    self.stringValue = self.oldStringValue;
  }
}

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `songs` where `id` = 5 limit 1)

I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :

  1. I used bigIncrements('id') to define my primary key.
  2. I used unsignedBigInteger('user_id') to define the foreign referenced key.

        Schema::create('generals', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('general_name');
            $table->string('status');
            $table->timestamps();
        });
    
    
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('general_id');
            $table->foreign('general_id')->references('id')->on('generals');
            $table->string('category_name');
            $table->string('status');
            $table->timestamps();
        });
    

I hope this helps out.

Eclipse IDE: How to zoom in on text?

Here's a quicker way than multi-layer menus without resorting to plug-ins:

Use the Quick Access tool at the upper left corner.

Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".

One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.

If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.

It's not quite as nice as zooming with the scroll wheel, but it's a lot better than navigating through the menus every time!

Error renaming a column in MySQL

Lone Ranger is very close... in fact, you also need to specify the datatype of the renamed column. For example:

ALTER TABLE `xyz` CHANGE `manufacurerid` `manufacturerid` INT;

Remember :

  • Replace INT with whatever your column data type is (REQUIRED)
  • Tilde/ Backtick (`) is optional

How to use Comparator in Java to sort

public static Comparator<JobSet> JobEndTimeComparator = new Comparator<JobSet>() {
            public int compare(JobSet j1, JobSet j2) {
                int cost1 = j1.cost;
                int cost2 = j2.cost;
                return cost1-cost2;
            }
        };

How can I catch a ctrl-c event?

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.

Animate a custom Dialog

I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.

  1. Inside res/style.xml

    <style name="AppTheme" parent="android:Theme.Light" />
    <style name="PauseDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
    </style>
    
    <style name="PauseDialogAnimation">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>
    </style>
    

  2. Inside anim/fadein.xml

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
    
  3. Inside anim/fadeout.xml

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/anticipate_interpolator"
        android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
    
  4. MainActivity

    Dialog imageDiaglog= new Dialog(MainActivity.this,R.style.PauseDialog);
    

Detect when an HTML5 video finishes

JQUERY

$("#video1").bind("ended", function() {
   //TO DO: Your code goes here...
});

HTML

<video id="video1" width="420">
  <source src="path/filename.mp4" type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Event types HTML Audio and Video DOM Reference

Mercurial stuck "waiting for lock"

I had the same problem on Win 7. The solution was to remove following files:

  1. .hg/store/phaseroots
  2. .hg/wlock

As for .hg/store/lock - there was no such file.

How to update specific key's value in an associative array in PHP?

Change your foreach to something like this, You are not assigning data back to your return variable $data after performing operation on that.

foreach($data as $key => $value)
{
  $data[$key]['transaction_date'] = date('d/m/Y',$value['transaction_date']);
}

Codepad DEMO.

JVM heap parameters

The JVM will start with memory useage at the initial heap level. If the maxheap is higher, it will grow to the maxheap size as memory requirements exceed it's current memory.

So,

  • -Xms512m -Xmx512m

JVM starts with 512 M, never resizes.

  • -Xms64m -Xmx512m

JVM starts with 64M, grows (up to max ceiling of 512) if mem. requirements exceed 64.

How to retrieve the last autoincremented ID from a SQLite table?

According to Android Sqlite get last insert row id there is another query:

SELECT rowid from your_table_name order by ROWID DESC limit 1

How do I associate file types with an iPhone application?

To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:

    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>IPA</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>public.item</string>
                <string>public.content</string>
                <string>public.data</string>
                <string>public.database</string>
                <string>public.composite-content</string>
                <string>public.contact</string>
                <string>public.archive</string>
                <string>public.url-name</string>
                <string>public.text</string>
                <string>public.plain-text</string>
                <string>public.source-code</string>
                <string>public.executable</string>
                <string>public.script</string>
                <string>public.shell-script</string>
                <string>public.xml</string>
                <string>public.symlink</string>
                <string>org.gnu.gnu-zip-archve</string>
                <string>org.gnu.gnu-tar-archive</string>
                <string>public.image</string>
                <string>public.movie</string>
                <string>public.audiovisual-?content</string>
                <string>public.audio</string>
                <string>public.directory</string>
                <string>public.folder</string>
                <string>com.apple.bundle</string>
                <string>com.apple.package</string>
                <string>com.apple.plugin</string>
                <string>com.apple.application-?bundle</string>
                <string>com.pkware.zip-archive</string>
                <string>public.filename-extension</string>
                <string>public.mime-type</string>
                <string>com.apple.ostype</string>
                <string>com.apple.nspboard-typ</string>
                <string>com.adobe.pdf</string>
                <string>com.adobe.postscript</string>
                <string>com.adobe.encapsulated-?postscript</string>
                <string>com.adobe.photoshop-?image</string>
                <string>com.adobe.illustrator.ai-?image</string>
                <string>com.compuserve.gif</string>
                <string>com.microsoft.word.doc</string>
                <string>com.microsoft.excel.xls</string>
                <string>com.microsoft.powerpoint.?ppt</string>
                <string>com.microsoft.waveform-?audio</string>
                <string>com.microsoft.advanced-?systems-format</string>
                <string>com.microsoft.advanced-?stream-redirector</string>
                <string>com.microsoft.windows-?media-wmv</string>
                <string>com.microsoft.windows-?media-wmp</string>
                <string>com.microsoft.windows-?media-wma</string>
                <string>com.apple.keynote.key</string>
                <string>com.apple.keynote.kth</string>
                <string>com.truevision.tga-image</string>
            </array>
            <key>CFBundleTypeIconFiles</key>
            <array>
                <string>Icon-76@2x</string>
            </array>
        </dict>
    </array>

What's the best practice for putting multiple projects in a git repository?

While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.

Solution 1

A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.

git checkout --orphan BRANCHNAME

This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.

Now for whatever reason, git needs a bit of cleanup after an orphan checkout.

rm .git/index
rm -r *

Make sure everything is committed before deleting

Once the orphan branch is clean, you can use it normally.

Solution 2

Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.

# repo 1
git push origin master:master-1

# repo 2
git push origin master:master-2

Groovy - Convert object to JSON string

Do you mean like:

import groovy.json.*

class Me {
    String name
}

def o = new Me( name: 'tim' )

println new JsonBuilder( o ).toPrettyString()

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

How to format a float in javascript?

I use this code to format floats. It is based on toPrecision() but it strips unnecessary zeros. I would welcome suggestions for how to simplify the regex.

function round(x, n) {
    var exp = Math.pow(10, n);
    return Math.floor(x*exp + 0.5)/exp;
}

Usage example:

function test(x, n, d) {
    var rounded = rnd(x, d);
    var result = rounded.toPrecision(n);
    result = result.replace(/\.?0*$/, '');
    result = result.replace(/\.?0*e/, 'e');
    result = result.replace('e+', 'e');
    return result;  
}

document.write(test(1.2000e45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2000e+45, 3, 2) + '=' + '1.2e45' + '<br>');
document.write(test(1.2340e45, 3, 2) + '=' + '1.23e45' + '<br>');
document.write(test(1.2350e45, 3, 2) + '=' + '1.24e45' + '<br>');
document.write(test(1.0000, 3, 2) + '=' + '1' + '<br>');
document.write(test(1.0100, 3, 2) + '=' + '1.01' + '<br>');
document.write(test(1.2340, 4, 2) + '=' + '1.23' + '<br>');
document.write(test(1.2350, 4, 2) + '=' + '1.24' + '<br>');

Mercurial — revert back to old version and continue from there

I'd install Tortoise Hg (a free GUI for Mercurial) and use that. You can then just right-click on a revision you might want to return to - with all the commit messages there in front of your eyes - and 'Revert all files'. Makes it intuitive and easy to roll backwards and forwards between versions of a fileset, which can be really useful if you are looking to establish when a problem first appeared.

Programmatically set image to UIImageView with Xcode 6.1/Swift

With swift syntax this worked for me :

    let leftImageView = UIImageView()
    leftImageView.image = UIImage(named: "email")

    let leftView = UIView()
    leftView.addSubview(leftImageView)

    leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
    leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
    userNameTextField.leftViewMode = .always
    userNameTextField.leftView = leftView

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

Why doesn't C++ have a garbage collector?

One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:

  • deterministic lifetimes of objects (reference counting gives you this, but GC doesn't. Although it may not be that big of a deal).
  • what happens if a destructor throws when the object is being garbage collected? Most languages ignore this exception, since theres really no catch block to be able to transport it to, but this is probably not an acceptable solution for C++.
  • How to enable/disable it? Naturally it'd probably be a compile time decision but code that is written for GC vs code that is written for NOT GC is going to be very different and probably incompatible. How do you reconcile this?

These are just a few of the problems faced.

Cannot invoke an expression whose type lacks a call signature

Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

interface Fruit {
    isDecayed: boolean;
}

interface Apple extends Fruit {
    color: string;
}

interface Pear extends Fruit {
    weight: number;
}

interface FruitBasket {
    apples: Apple[];
    pears: Pear[];
}


const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
const fruits: Fruit[] = fruitBasket[key];

const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);

Use PHP composer to clone git repo

That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require (which is always needed) with a matching version constraint.

In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.


For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:

  • The "repositories" field is specified in the root composer.json (it's a root-only field, repository definitions from required packages are ignored)
  • The repositories definition points to a valid VCS repo
  • If the type is "git" instead of "vcs" (as in your question), make sure it is in fact a git repo
  • You have a require for the package in question
  • The constraint in the require matches the versions provided by the VCS repo. You can use composer show <packagename> to find the available versions. In this case ~2.3 would be a good option.
  • The name in the require matches the name in the remote composer.json. In this case, it is gedmo/doctrine-extensions.

Here is a sample composer.json that installs the same package via a VCS repo:

{
    "repositories": [
        {
            "url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
            "type": "git"
        }
    ],
    "require": {
        "gedmo/doctrine-extensions": "~2.3"
    }
}

The VCS repo docs explain all of this quite well.


If there is a git (or other VCS) repository with a composer.json available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.

Avoid package repos (see also the docs).

Identifying and removing null characters in UNIX

I discovered the following, which prints out which lines, if any, have null characters:

perl -ne '/\000/ and print;' file-with-nulls

Also, an octal dump can tell you if there are nulls:

od file-with-nulls | grep ' 000'

jQuery, simple polling example

This solution:

  1. has timeout
  2. polling works also after error response

Minimum version of jQuery is 1.12

$(document).ready(function () {
  function poll () {
    $.get({
      url: '/api/stream/',
      success: function (data) {
        console.log(data)
      },
      timeout: 10000                    // == 10 seconds timeout
    }).always(function () {
      setTimeout(poll, 30000)           // == 30 seconds polling period
    })
  }

  // start polling
  poll()
})

Android ListView with onClick items

listview.setOnItemClickListener(new OnItemClickListener(){

//setting onclick to items in the listview.

@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){

// case 0 is the first item in the listView.

  case 0:
    intent = new Intent(Activity.this,firstActivity.class);
    break;
//case 1 is the second item in the listView.

  case 1:
    intent = new Intent(Activity.this,secondActivity.class);
    break;
 case 2:
    intent = new Intent(Activity.this,thirdActivity.class);
    break;
//add more if you have more items in listView
startActivity(intent);
}

});

android image button

You just use an ImageButton and make the background whatever you want and set the icon as the src.

<ImageButton
    android:id="@+id/ImageButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/album_icon"
    android:background="@drawable/round_button" />

enter image description here

How to grant all privileges to root user in MySQL 8.0

1. grant privileges

mysql> GRANT ALL PRIVILEGES ON . TO 'root'@'%'WITH GRANT OPTION;

mysql> FLUSH PRIVILEGES

2. check user table:

mysql> use mysql

mysql> select host,user from user enter image description here

3.Modify the configuration file

mysql default bind ip:127.0.0.1, if we want to remote visit services,just delete config

#Modify the configuration file
vi /usr/local/etc/my.cnf

#Comment out the ip-address option
[mysqld]
# Only allow connections from localhost
#bind-address = 127.0.0.1

4.finally restart the services

brew services restart mysql

AngularJs - ng-model in a SELECT

However, ngOptions provides some benefits such as reducing memory and increasing speed by not creating a new scope for each repeated instance. angular docs

Alternative solution is use ng-init directive. You can specify function that will be initialize your default data.

$scope.init = function(){
            angular.forEach($scope.units, function(item){
                if(item.id === $scope.data.unit){
                    $scope.data.unit = item;
                }
            });
        } 

See jsfiddle

Determine a user's timezone

Getting a valid TZ Database timezone name in PHP is a two-step process:

  1. With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.

    var timezone_offset_minutes = new Date().getTimezoneOffset();
    timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
    

    Pass this offset to PHP.

  2. In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.

    // Just an example.
    $timezone_offset_minutes = -360;  // $_GET['timezone_offset_minutes']
    
    // Convert minutes to seconds
    $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
    
    // America/Chicago
    echo $timezone_name;</code></pre>
    

I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.

Meaning of $? (dollar question mark) in shell scripts

It has the last status code (exit value) of a command.

How to write a test which expects an Error to be thrown in Jasmine?

For anyone who still might be facing this issue, for me the posted solution didn't work and it kept on throwing this error: Error: Expected function to throw an exception. I later realised that the function which I was expecting to throw an error was an async function and was expecting promise to be rejected and then throw error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

and thats what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
         const promise = service.getRequestStatus('request-id');
                return expectToReject(promise).then((err) => {
                    expect(err.message).toEqual('REQUEST NOT FOUND');
                });
            }));

Python pandas: how to specify data types when reading an Excel file?

You just specify converters. I created an excel spreadsheet of the following structure:

names   ages
bob     05
tom     4
suzy    3

Where the "ages" column is formatted as strings. To load:

import pandas as pd

df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str})
>>> df
       names ages
   0   bob   05
   1   tom   4
   2   suzy  3

How do I iterate over a range of numbers defined by variables in Bash?

This works in Bash and Korn, also can go from higher to lower numbers. Probably not fastest or prettiest but works well enough. Handles negatives too.

function num_range {
   # Return a range of whole numbers from beginning value to ending value.
   # >>> num_range start end
   # start: Whole number to start with.
   # end: Whole number to end with.
   typeset s e v
   s=${1}
   e=${2}
   if (( ${e} >= ${s} )); then
      v=${s}
      while (( ${v} <= ${e} )); do
         echo ${v}
         ((v=v+1))
      done
   elif (( ${e} < ${s} )); then
      v=${s}
      while (( ${v} >= ${e} )); do
         echo ${v}
         ((v=v-1))
      done
   fi
}

function test_num_range {
   num_range 1 3 | egrep "1|2|3" | assert_lc 3
   num_range 1 3 | head -1 | assert_eq 1
   num_range -1 1 | head -1 | assert_eq "-1"
   num_range 3 1 | egrep "1|2|3" | assert_lc 3
   num_range 3 1 | head -1 | assert_eq 3
   num_range 1 -1 | tail -1 | assert_eq "-1"
}

Custom Cell Row Height setting in storyboard is not responding

If you're using swift , use like this. Don't Use storyboard to select row height. Programmatically set table row height like this,

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if indexPath.row == 0 || indexPath.row == 1{
        let cell = self.tableView.dequeueReusableCellWithIdentifier("section1", forIndexPath: indexPath) as! Section1TableViewCell
        self.tableView.rowHeight = 150
        cell.label1.text = "hiiiiii"
        cell.label2.text = "Huiiilllllll"
        return cell

    } else {

        let cell = self.tableView.dequeueReusableCellWithIdentifier("section2", forIndexPath: indexPath) as! Section2TableViewCell
        self.tableView.rowHeight = 60
        cell.label3.text = "llll"
        return cell
    }

}

How to make a TextBox accept only alphabetic characters?

You can try by handling the KeyPress event for the textbox

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}

Additionally say allow backspace in case you want to remove some text, this should work perfectly fine for you

EDIT

The above code won't work for paste in the field for which i believe you will have to use TextChanged event but then it would be a bit more complicated with you having to remove the incorrect char or highlight it and place the cursor for the user to make the correction Or maybe you could validate once the user has entered the complete text and tabs off the control.

CS0234: Mvc does not exist in the System.Web namespace

add Microsoft.AspNet.Mvc nuget package.

Initializing ArrayList with some predefined values

Personnaly I like to do all the initialisations in the constructor

public Test()
{
  symbolsPresent = new ArrayList<String>();
  symbolsPresent.add("ONE");
  symbolsPresent.add("TWO");
  symbolsPresent.add("THREE");
  symbolsPresent.add("FOUR");
}

Edit : It is a choice of course and others prefer to initialize in the declaration. Both are valid, I have choosen the constructor because all type of initialitions are possible there (if you need a loop or parameters, ...). However I initialize the constants in the declaration on the top on the source.
The most important is to follow a rule that you like and be consistent in our classes.

Calculate summary statistics of columns in dataframe

describe may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once

In [43]:

df.describe()

Out[43]:

       shopper_num is_martian  number_of_items  count_pineapples
count      14.0000         14        14.000000                14
mean        7.5000          0         3.357143                 0
std         4.1833          0         6.452276                 0
min         1.0000      False         0.000000                 0
25%         4.2500          0         0.000000                 0
50%         7.5000          0         0.000000                 0
75%        10.7500          0         3.500000                 0
max        14.0000      False        22.000000                 0

[8 rows x 4 columns]

Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data

As you prefer you can transpose the result if you prefer:

In [47]:

df.describe().transpose()

Out[47]:

                 count      mean       std    min   25%  50%    75%    max
shopper_num         14       7.5    4.1833      1  4.25  7.5  10.75     14
is_martian          14         0         0  False     0    0      0  False
number_of_items     14  3.357143  6.452276      0     0    0    3.5     22
count_pineapples    14         0         0      0     0    0      0      0

[4 rows x 8 columns]

Send POST data on redirect with JavaScript/jQuery?

This is quite handy to use:

var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:

myRedirect("/yourRedirectingUrl", "arg", "argValue");

Error CS2001: Source file '.cs' could not be found

They are likely still referenced by the project file. Make sure they are deleted using the Solution Explorer in Visual Studio - it should show them as being missing (with an exclamation mark).

How to place the ~/.composer/vendor/bin directory in your PATH?

The Composer bin directory is set and stored in bin-dir config variable and can be different depending on your setup. Running the command composer global config bin-dir --absolute will tell you the absolute path to your global composer bin directory. Using this command you can modify your .bash_profile to add it to your PATH exactly how it is configured.

# Add Composer bin-dir to PATH if it is installed.
command -v composer >/dev/null 2>&1 && {
        COMPOSER_BIN_DIR=$(composer global config bin-dir --absolute 2> /dev/null)
        PATH="$PATH:$COMPOSER_BIN_DIR";
}
export PATH

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

I like the WMILinq solution. While not exactly the solution to your problem, find below a taste of it :

using (WmiContext context = new WmiContext(@"\\.")) {

  context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;
  context.Log = Console.Out;

  var dnss = from nic in context.Source<Win32_NetworkAdapterConfiguration>()
          where nic.IPEnabled
          select nic;

  var ips = from s in dnss.SelectMany(dns => dns.DNSServerSearchOrder)
          select IPAddress.Parse(s);
}  

http://www.codeplex.com/linq2wmi

How to make links in a TextView clickable?

If you want to add HTML-like link, all you need to do is:

  • add a resource HTML-like string:

     <string name="link"><a href="https://www.google.pl/">Google</a></string>
    
  • add your view to the layout with NO link-specific configuration at all:

     <TextView
        android:id="@+id/link"
        android:text="@string/link" />`
    
  • add appropriate MovementMethod programmatically to your TextView:

     mLink = (TextView) findViewById(R.id.link);
     if (mLink != null) {
       mLink.setMovementMethod(LinkMovementMethod.getInstance());
     }
    

That's it! And yes, having options like "autoLink" and "linksClickable" working on explicit links only (not wrapped into html tags) is very misleading to me too...

Hive query output to file

Enter this line into Hive command line interface:

insert overwrite directory '/data/test' row format delimited fields terminated by '\t' stored as textfile select * from testViewQuery;

testViewQuery - some specific view

Difference between logger.info and logger.debug

  1. INFO is used to log the information your program is working as expected.
  2. DEBUG is used to find the reason in case your program is not working as expected or an exception has occurred. it's in the interest of the developer.

In Go's http package, how do I get the query string on a POST request?

Here's a simple, working example:

package main

import (
    "io"
    "net/http"
)
func queryParamDisplayHandler(res http.ResponseWriter, req *http.Request) {
    io.WriteString(res, "name: "+req.FormValue("name"))
    io.WriteString(res, "\nphone: "+req.FormValue("phone"))
}

func main() {
    http.HandleFunc("/example", func(res http.ResponseWriter, req *http.Request) {
        queryParamDisplayHandler(res, req)
    })
    println("Enter this in your browser:  http://localhost:8080/example?name=jenny&phone=867-5309")
    http.ListenAndServe(":8080", nil)
}

enter image description here

jQuery UI - Close Dialog When Clicked Outside

Check out the jQuery Outside Events plugin

Lets you do:

$field_hint.bind('clickoutside',function(){
    $field_hint.dialog('close');
});

How to sort an associative array by its values in Javascript?

There really isn't any such thing as an "associative array" in JavaScript. What you've got there is just a plain old object. They work kind-of like associative arrays, of course, and the keys are available but there's no semantics around the order of keys.

You could turn your object into an array of objects (key/value pairs) and sort that:

function sortObj(object, sortFunc) {
  var rv = [];
  for (var k in object) {
    if (object.hasOwnProperty(k)) rv.push({key: k, value:  object[k]});
  }
  rv.sort(function(o1, o2) {
    return sortFunc(o1.key, o2.key);
  });
  return rv;
}

Then you'd call that with a comparator function.

JavaScript: Object Rename Key

You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

I wish the syntax wasn't this complex but it is definitely nice having more control.

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

Maven: How to rename the war file for the project?

You can use the following in the web module that produces the war:

<build>
  <finalName>bird</finalName>
 . . .
</build>

This leads to a file called bird.war to be created when goal "war:war" is used.

Getting the Username from the HKEY_USERS values

It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.

wmic useraccount get name,sid

You can also export this information to CSV:

wmic useraccount get name,sid /format:csv > output.csv

I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

How I got this problem,

When I changed from Eclipse Juno to Luna, and checkout my maven projects from SVN repo, I got the same issues while building the applications.

What I tried? I tried clean Local repository and then updating all the versions again using -U option. But my problem continued.

Then I went to Window --> Preferences -> Maven --> User Settings --> and clicked on Reindex button under Local Repository and wait for the reindex to happen.

That's all, the issue is resolved.

What are unit tests, integration tests, smoke tests, and regression tests?

Regression test - Is a type of software testing where we try to cover or check around the bug fix. The functionality around the bug fix should not get changed or altered due to the fix provided. Issues found in such process are called as regression issues.

Smoke Testing: Is a kind of testing done to decide whether to accept the build/software for further QA testing.

Change multiple files

I'm surprised nobody has mentioned the -exec argument to find, which is intended for this type of use-case, although it will start a process for each matching file name:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} \;

Alternatively, one could use xargs, which will invoke fewer processes:

find . -type f -name 'xa*' | xargs sed -i 's/asd/dsg/g'

Or more simply use the + exec variant instead of ; in find to allow find to provide more than one file per subprocess call:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} +

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

How can I use pointers in Java?

There are pointers in Java, but you cannot manipulate them the way that you can in C++ or C. When you pass an object, you are passing a pointer to that object, but not in the same sense as in C++. That object cannot be dereferenced. If you set its values using its native accessors, it will change because Java knows its memory location through the pointer. But the pointer is immutable. When you attempt to set the pointer to a new location, you instead end up with a new local object with the same name as the other. The original object is unchanged. Here is a brief program to demonstrate the difference.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone {

    public static void main(String[] args) throws java.lang.Exception {
        System.out.println("Expected # = 0 1 2 2 1");
        Cat c = new Cat();
        c.setClaws(0);
        System.out.println("Initial value is " + c.getClaws());
        // prints 0 obviously
        clawsAreOne(c);
        System.out.println("Accessor changes value to " + c.getClaws());
        // prints 1 because the value 'referenced' by the 'pointer' is changed using an accessor.
        makeNewCat(c);
        System.out.println("Final value is " + c.getClaws());
        // prints 1 because the pointer is not changed to 'kitten'; that would be a reference pass.
    }

    public static void clawsAreOne(Cat kitty) {
        kitty.setClaws(1);
    }

    public static void makeNewCat(Cat kitty) {
        Cat kitten = new Cat();
        kitten.setClaws(2);
        kitty = kitten;
        System.out.println("Value in makeNewCat scope of kitten " + kitten.getClaws());
        //Prints 2. the value pointed to by 'kitten' is 2
        System.out.println("Value in makeNewcat scope of kitty " + kitty.getClaws());
        //Prints 2. The local copy is being used within the scope of this method.
    }
}

class Cat {

    private int claws;

    public void setClaws(int i) {
        claws = i;
    }

    public int getClaws() {
        return claws;
    }
}

This can be run at Ideone.com.

Function overloading in Python: Missing

You can pass a mutable container datatype into a function, and it can contain anything you want.

If you need a different functionality, name the functions differently, or if you need the same interface, just write an interface function (or method) that calls the functions appropriately based on the data received.

It took a while to me to get adjusted to this coming from Java, but it really isn't a "big handicap".

SHA1 vs md5 vs SHA256: which to use for a PHP login?

What people seem to be missing is that if the hacker has access to the database he probably also has access to the php file that hashes the password and can likely just modify that to send him all the successful user name password combos. If he doesn't have access to the web directory he could always just pick a password hash it, and write that into the database. In other words the hash algorithm doesn't really matter as much as system security, and limiting login attempts also if you don't use SSL then the attacker can just listen in on the connection to get the information. Unless you need the algorithm to take a long time to compute (for your own purposes) then SHA-256 or SHA-512 with a user specific salt should be enough.

As an added security measure set up a script (bash, batch, python, etc) or program and give it an obscure name and have it check and see if login.php has changed (check date/time stamp) and send you an email if it has. Also should probably log all attempts at login with admin rights and log all failed attempts to log into the database and have the logs emailed to you.

OpenCV with Network Cameras

I enclosed C++ code for grabbing frames. It requires OpenCV version 2.0 or higher. The code uses cv::mat structure which is preferred to old IplImage structure.

#include "cv.h"
#include "highgui.h"
#include <iostream>

int main(int, char**) {
    cv::VideoCapture vcap;
    cv::Mat image;

    const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp"; 
    /* it may be an address of an mjpeg stream, 
    e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */

    //open the video stream and make sure it's opened
    if(!vcap.open(videoStreamAddress)) {
        std::cout << "Error opening video stream or file" << std::endl;
        return -1;
    }

    //Create output window for displaying frames. 
    //It's important to create this window outside of the `for` loop
    //Otherwise this window will be created automatically each time you call
    //`imshow(...)`, which is very inefficient. 
    cv::namedWindow("Output Window");

    for(;;) {
        if(!vcap.read(image)) {
            std::cout << "No frame" << std::endl;
            cv::waitKey();
        }
        cv::imshow("Output Window", image);
        if(cv::waitKey(1) >= 0) break;
    }   
}

Update You can grab frames from H.264 RTSP streams. Look up your camera API for details to get the URL command. For example, for an Axis network camera the URL address might be:

// H.264 stream RTSP address, where 10.10.10.10 is an IP address 
// and 554 is the port number
rtsp://10.10.10.10:554/axis-media/media.amp

// if the camera is password protected
rtsp://username:[email protected]:554/axis-media/media.amp

difference between primary key and unique key

Difference between Primary Key and Unique Key

+-----------------------------------------+-----------------------------------------------+
|                Primary Key              |                    Unique Key                 |
+-----------------------------------------+-----------------------------------------------+
| Primary Key can't accept null values.   | Unique key can accept only one null value.    |
+-----------------------------------------+-----------------------------------------------+
| By default, Primary key is clustered    | By default, Unique key is a unique            |
| index and data in the database table is | non-clustered index.                          |
| physically organized in the sequence of |                                               |
| clustered index.                        |                                               |
+-----------------------------------------+-----------------------------------------------+
| We can have only one Primary key in a   | We can have more than one unique key in a     |
| table.                                  | table.                                        |
+-----------------------------------------+-----------------------------------------------+
| Primary key can be made foreign key     | In SQL Server, Unique key can be made foreign |
| into another table.                     | key into another table.                       |
+-----------------------------------------+-----------------------------------------------+

You can find detailed information from:
http://www.dotnet-tricks.com/Tutorial/sqlserver/V2bS260912-Difference-between-Primary-Key-and-Unique-Key.html

How do I scroll the UIScrollView when the keyboard appears?

The recommended way from Apple is to change the contentInset of the UIScrollView. It is a very elegant solution, because you do not have to mess with the contentSize. Following code is copied from the Keyboard Programming Guide, where the handling of this issue is explained. You should have a look into it.

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(keyboardWasShown:)
            name:UIKeyboardDidShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self
             selector:@selector(keyboardWillBeHidden:)
             name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent    
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

Swift version:

func registerForKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardAppear(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardDisappear(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

// Don't forget to unregister when done
deinit {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

@objc func onKeyboardAppear(_ notification: NSNotification) {
    let info = notification.userInfo!
    let rect: CGRect = info[UIKeyboardFrameBeginUserInfoKey] as! CGRect
    let kbSize = rect.size

    let insets = UIEdgeInsetsMake(0, 0, kbSize.height, 0)
    scrollView.contentInset = insets
    scrollView.scrollIndicatorInsets = insets

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    var aRect = self.view.frame;
    aRect.size.height -= kbSize.height;

    let activeField: UITextField? = [addressTextView, servicePathTextView, usernameTextView, passwordTextView].first { $0.isFirstResponder }
    if let activeField = activeField {
        if !aRect.contains(activeField.frame.origin) {
            let scrollPoint = CGPoint(x: 0, y: activeField.frame.origin.y-kbSize.height)
            scrollView.setContentOffset(scrollPoint, animated: true)
        }
    }
}

@objc func onKeyboardDisappear(_ notification: NSNotification) {
    scrollView.contentInset = UIEdgeInsets.zero
    scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}

How to change color of Toolbar back button in Android?

I did it this way using the Material Components library:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>
</style>

<style name="AppTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>

How to calculate the sentence similarity using word2vec model of gensim with python

I would like to update the existing solution to help the people who are going to calculate the semantic similarity of sentences.

Step 1:

Load the suitable model using gensim and calculate the word vectors for words in the sentence and store them as a word list

Step 2 : Computing the sentence vector

The calculation of semantic similarity between sentences was difficult before but recently a paper named "A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SENTENCE EMBEDDINGS" was proposed which suggests a simple approach by computing the weighted average of word vectors in the sentence and then remove the projections of the average vectors on their first principal component.Here the weight of a word w is a/(a + p(w)) with a being a parameter and p(w) the (estimated) word frequency called smooth inverse frequency.this method performing significantly better.

A simple code to calculate the sentence vector using SIF(smooth inverse frequency) the method proposed in the paper has been given here

Step 3: using sklearn cosine_similarity load two vectors for the sentences and compute the similarity.

This is the most simple and efficient method to compute the sentence similarity.

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Static methods in Python?

Perhaps the simplest option is just to put those functions outside of the class:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def bark(self):
        if self.name == "Doggy":
            return barking_sound()
        else:
            return "yip yip"

def barking_sound():
    return "woof woof"

Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.

Let's say this file is called dogs.py. To use these, you'd call dogs.barking_sound() instead of dogs.Dog.barking_sound.

If you really need a static method to be part of the class, you can use the staticmethod decorator.

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

For iOS 8 above it's really simple:

override func viewDidLoad() {  
    super.viewDidLoad()

    self.tableView.estimatedRowHeight = 80
    self.tableView.rowHeight = UITableView.automaticDimension
}

or

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

But for iOS 7, the key is calculate the height after autolayout:

func calculateHeightForConfiguredSizingCell(cell: GSTableViewCell) -> CGFloat {
    cell.setNeedsLayout()
    cell.layoutIfNeeded()
    let height = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height + 1.0
    return height
}

Important

  • If multiple lines labels, don't forget set the numberOfLines to 0.

  • Don't forget label.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)

The full example code is here.

Find the similarity metric between two strings

Textdistance:

TextDistance – python library for comparing distance between two or more sequences by many algorithms. It has Textdistance

  • 30+ algorithms
  • Pure python implementation
  • Simple usage
  • More than two sequences comparing
  • Some algorithms have more than one implementation in one class.
  • Optional numpy usage for maximum speed.

Example1:

import textdistance
textdistance.hamming('test', 'text')

Output:

1

Example2:

import textdistance

textdistance.hamming.normalized_similarity('test', 'text')

Output:

0.75

Thanks and Cheers!!!

How to empty a Heroku database

Today the command

heroku pg:reset --db SHARED_DATABASE_URL

not working for shared plans, I'm resolve using

heroku pg:reset SHARED_DATABASE

How to recover stashed uncommitted changes

On mac this worked for me:

git stash list(see all your stashs)

git stash list

git stash apply (just the number that you want from your stash list)

like this:

git stash apply 1

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

If you are running MYSQL through XAMPP:

  1. Open XAMPP mysql configuration file (on OSX):

    /Applications/XAMPP/etc/my.cnf

  2. Copy the socket path:

    socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

  3. Open rails project's database configuration file: myproject/config/database.yml

  4. Add the socket config to the development database config:

-->

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: difiuri_falcioni
  pool: 5
  username: root
  password:
  host: localhost
  socket: /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
  1. Restart rails server

Enjoy :)

Testing Spring's @RequestBody using Spring MockMVC

I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...) but it would not work in my case.

I actually had a String in a JSON format, but I feel like it is literally transforming the toString() method of every field into JSON. In my case, a date LocalDate field would end up as:

"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}

which is not the best date format to send in a request ...

In the end, the simplest solution in my case is to use the Spring ObjectMapper. Its behaviour is better since it uses Jackson to build your JSON with complex types.

@Autowired
private ObjectMapper objectMapper;

and I simply used it in mytest:

mockMvc.perform(post("/api/")
                .content(objectMapper.writeValueAsString(...))
                .contentType(MediaType.APPLICATION_JSON)
);

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

Why does Firebug say toFixed() is not a function?

Low is a string.

.toFixed() only works with a number.

A simple way to overcome such problem is to use type coercion:

Low = (Low*1).toFixed(..);

The multiplication by 1 forces to code to convert the string to number and doesn't change the value.

What is a stack trace, and how can I use it to debug my application errors?

I am posting this answer so the topmost answer (when sorted by activity) is not one that is just plain wrong.

What is a Stacktrace?

A stacktrace is a very helpful debugging tool. It shows the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:

What is an Exception?

An Exception is what the runtime environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object:

Object a = null;
a.toString();                 //this line throws a NullPointerException

Object[] b = new Object[5];
System.out.println(b[10]);    //this line throws an IndexOutOfBoundsException,
                              //because b is only 5 elements long
int ia = 5;
int ib = 0;
ia = ia/ib;                   //this line throws an  ArithmeticException with the 
                              //message "/ by 0", because you are trying to
                              //divide by 0, which is not possible.

How should I deal with Stacktraces/Exceptions?

At first, find out what is causing the Exception. Try googleing the name of the exception to find out, what is the cause of that exception. Most of the time it will be caused by incorrect code. In the given examples above, all of the exceptions are caused by incorrect code. So for the NullPointerException example you could make sure that a is never null at that time. You could, for example, initialise a or include a check like this one:

if (a!=null) {
    a.toString();
}

This way, the offending line is not executed if a==null. Same goes for the other examples.

Sometimes you can't make sure that you don't get an exception. For example, if you are using a network connection in your program, you cannot stop the computer from loosing it's internet connection (e.g. you can't stop the user from disconnecting the computer's network connection). In this case the network library will probably throw an exception. Now you should catch the exception and handle it. This means, in the example with the network connection, you should try to reopen the connection or notify the user or something like that. Also, whenever you use catch, always catch only the exception you want to catch, do not use broad catch statements like catch (Exception e) that would catch all exceptions. This is very important, because otherwise you might accidentally catch the wrong exception and react in the wrong way.

try {
    Socket x = new Socket("1.1.1.1", 6789);
    x.getInputStream().read()
} catch (IOException e) {
    System.err.println("Connection could not be established, please try again later!")
}

Why should I not use catch (Exception e)?

Let's use a small example to show why you should not just catch all exceptions:

int mult(Integer a,Integer b) {
    try {
        int result = a/b
        return result;
    } catch (Exception e) {
        System.err.println("Error: Division by zero!");
        return 0;
    }
}

What this code is trying to do is to catch the ArithmeticException caused by a possible division by 0. But it also catches a possible NullPointerException that is thrown if a or b are null. This means, you might get a NullPointerException but you'll treat it as an ArithmeticException and probably do the wrong thing. In the best case you still miss that there was a NullPointerException. Stuff like that makes debugging much harder, so don't do that.

TLDR

  1. Figure out what is the cause of the exception and fix it, so that it doesn't throw the exception at all.
  2. If 1. is not possible, catch the specific exception and handle it.

    • Never just add a try/catch and then just ignore the exception! Don't do that!
    • Never use catch (Exception e), always catch specific Exceptions. That will save you a lot of headaches.

select rows in sql with latest date for each ID repeated multiple times

One way is:

select table.* 
from table
join 
(
    select ID, max(Date) as max_dt 
    from table
    group by ID
) t
on table.ID= t.ID and table.Date = t.max_dt 

Note that if you have multiple equally higher dates for same ID, then you will get all those rows in result

json_encode(): Invalid UTF-8 sequence in argument

Seems like the symbol was Å, but since data consists of surnames that shouldn't be public, only first letter was shown and it was done by just $lastname[0], which is wrong for multibyte strings and caused the whole hassle. Changed it to mb_substr($lastname, 0, 1) - works like a charm.

jQuery AJAX submit form

Try

fetch(form.action,{method:'post', body: new FormData(form)});

_x000D_
_x000D_
function send(e,form) {_x000D_
  fetch(form.action,{method:'post', body: new FormData(form)});_x000D_
_x000D_
  console.log('We submit form asynchronously (AJAX)');_x000D_
  e.preventDefault();_x000D_
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">_x000D_
    <input hidden name="csrfToken" value="$0meh@$h">_x000D_
    <input name="email" value="[email protected]">_x000D_
    <input name="phone" value="123-456-666">_x000D_
    <input type="submit">    _x000D_
</form>_x000D_
_x000D_
Look on Chrome Console > Network after/before 'submit'
_x000D_
_x000D_
_x000D_

how to open a page in new tab on button click in asp.net?

add target='_blank' after check validation :

_x000D_
_x000D_
    <asp:button id="_ButPrint"  ValidationGroup="print" OnClientClick="if (Page_ClientValidate()){$('form').attr('target','_blank');}"  runat="server" onclick="ButPrint_Click" Text="print" />
                                                                 
_x000D_
_x000D_
_x000D_

What is the best way to find the users home directory in Java?

The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the System.getProperty("user.home") approach is probably still the best. The user.home approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means.

If user.home isn't good enough for you I would suggest choosing a definition of home directory for windows and using it, getting the appropriate environment variable with System.getenv(String).

How do I escape a percentage sign in T-SQL?

In MySQL,

WHERE column_name LIKE '%|%%' ESCAPE '|'

Subset data to contain only columns whose names match a condition

This worked for me:

df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

In Python, how to display current time in readable format

import time
time.strftime('%H:%M%p %Z on %b %d, %Y')

This may come in handy

Rock, Paper, Scissors Game Java

Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:

if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}
else 
     System.out.println("Invalid user input.");

Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:

if( /* insert your check for bad characters here */ ) { 
     System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}

How to convert an integer to a string in any base?

I made a pip package for this.

I recommend you use my bases.py https://github.com/kamijoutouma/bases.py which was inspired by bases.js

from bases import Bases
bases = Bases()

bases.toBase16(200)                // => 'c8'
bases.toBase(200, 16)              // => 'c8'
bases.toBase62(99999)              // => 'q0T'
bases.toBase(200, 62)              // => 'q0T'
bases.toAlphabet(300, 'aAbBcC')    // => 'Abba'

bases.fromBase16('c8')               // => 200
bases.fromBase('c8', 16)             // => 200
bases.fromBase62('q0T')              // => 99999
bases.fromBase('q0T', 62)            // => 99999
bases.fromAlphabet('Abba', 'aAbBcC') // => 300

refer to https://github.com/kamijoutouma/bases.py#known-basesalphabets for what bases are usable

EDIT: pip link https://pypi.python.org/pypi/bases.py/0.2.2

How do I store the select column in a variable?

Assuming such a query would return a single row, you could use either

select @EmpId = Id from dbo.Employee

Or

set @EmpId = (select Id from dbo.Employee)

'Missing contentDescription attribute on image' in XML

If you don't care at all do this:

    android:contentDescription="@null"

Although I would advise the accepted solutions, this is a hack :D

/usr/bin/ld: cannot find

You need to add -L/opt/lib to tell ld to look there for shared objects.

In Firebase, is there a way to get the number of children of a node without loading all the node data?

The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.

Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.

For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:

var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

For more info, see https://www.firebase.com/docs/transactions.html

UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.

If you want to count upvotes for example, you should create a structure similar to this one:

{
  "posts" : {
    "-JRHTHaIs-jNPLXOQivY" : {
      "upvotes_count":5,
      "upvotes" : {
      "userX" : true,
      "userY" : true,
      "userZ" : true,
      ...
    }
    }
  }
}

And then write a javascript function to increase the upvotes_count when there is a new write to the upvotes node.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
  return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});

You can read the Documentation to know how to Get Started with Cloud Functions.

Also, another example of counting posts is here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js

Update January 2018

The firebase docs have changed so instead of event we now have change and context.

The given example throws an error complaining that event.data is undefined. This pattern seems to work better:

exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
    const data = change.after.val();
    const count = Object.keys(data).length;
    return change.after.ref.child('_count').set(count);
});

```

How to draw vertical lines on a given plot in matplotlib

The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline

import matplotlib.pyplot as plt

plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)

OR

xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
    plt.axvline(x=xc)

You can use many of the keywords available for other plot commands (e.g. color, linestyle, linewidth ...). You can pass in keyword arguments ymin and ymax if you like in axes corrdinates (e.g. ymin=0.25, ymax=0.75 will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline) and rectangles (axvspan).

Slack clean all messages (~8K) in a channel

I quickly found out there's someone already made a helper: slack-cleaner for this.

And for me it's just:

slack-cleaner --token=<TOKEN> --message --channel jenkins --user "*" --perform

How to empty the content of a div

In jQuery it would be as simple as $('#yourDivID').empty()

See the documentation.

How to get domain root url in Laravel 4?

This is for Laravel 5.1 and I am not sure does it work for earlier versions but if somebody search on Google and lands here it might be handy in middleware handle function gets $request parameter:

$request->server->get('SERVER_NAME')

outside of middleware handle method you can access it by helper function request()

request()->server->get('SERVER_NAME')

Revert to a commit by a SHA hash in Git?

Should be as simple as:

git reset --hard 56e05f

That'll get you back to that specific point in time.

Difference between Destroy and Delete

A lot of answers already; wanted to jump on with a bit more.

docs:

For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).

The delete verbage works differently for ActiveRecord::Association.has_many and ActiveRecord::Base. For the latter, delete will execute SQL DELETE and bypass all validations/callbacks. The former will be executed based on the :dependent option passed into the association. However, during testing, I found the following side effect where callbacks were only ran for delete and not delete_all

dependent: :destroy Example:

class Parent < ApplicationRecord
   has_many :children,
     before_remove: -> (_) { puts "before_remove callback" },
     dependent: :destroy
end

class Child < ApplicationRecord
   belongs_to :parent

   before_destroy -> { puts "before_destroy callback" }
end

> child.delete                            # Ran without callbacks
Child Destroy (99.6ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 21]]

> parent.children.delete(other_child)     # Ran with callbacks
before_remove callback
before_destroy callback
Child Destroy (0.4ms)  DELETE FROM "children" WHERE "children"."id" = $1  [["id", 22]]

> parent.children.delete_all              # Ran without callbacks
Child Destroy (1.0ms)  DELETE FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 1]]

Printing image with PrintDocument. how to adjust the image to fit paper size

all these answers has the problem, that's always stretching the image to pagesize and cuts off some content at trying this.
Found a little bit easier way.

My own solution only stretch(is this the right word?) if the image is to large, can use multiply copies and pageorientations.

                PrintDialog dlg = new PrintDialog();

            if (dlg.ShowDialog() == true)
            {
                BitmapImage bmi = new BitmapImage(new Uri(strPath));

                Image img = new Image();
                img.Source = bmi;

                if (bmi.PixelWidth < dlg.PrintableAreaWidth ||
                           bmi.PixelHeight < dlg.PrintableAreaHeight)
                {
                    img.Stretch = Stretch.None;
                    img.Width = bmi.PixelWidth;
                    img.Height = bmi.PixelHeight;
                }


                if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)
                {
                    img.Margin = new Thickness(0);
                }
                else
                {
                    img.Margin = new Thickness(48);
                }
                img.VerticalAlignment = VerticalAlignment.Top;
                img.HorizontalAlignment = HorizontalAlignment.Left;

                for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)
                {
                    dlg.PrintVisual(img, "Print a Image");
                }
            }

raw_input function in Python

The "input" function converts the input you enter as if it were python code. "raw_input" doesn't convert the input and takes the input as it is given. Its advisable to use raw_input for everything. Usage:

>>a = raw_input()
>>5
>>a
>>'5'

How to grep a text file which contains some binary data?

grep -a will force grep to search and output from a file that grep thinks is binary. grep -a re test.log

How can I style a PHP echo text?

echo '<span style="Your CSS Styles">' . $ip['cityName'] . '</span>';

C# - Winforms - Global Variables

They have already answered how to use a global variable.

I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.

Explicit translation of the text in Spanish:

Impact of the change

The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.

So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.

But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.

In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.

A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .

Order of destruction

Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int,enums, etc., which are never destroyed if they are global / static until they end the program).

The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.

If all your global / static variables are in a single compilation unit (that is, you only have a .cpp), then the order of construction is the same as the writing one (that is, variables defined before, are built before).

But if you have more than one .cpp each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp) in particular, is respected: if the global variableA is defined before B,A will be built before B, but It is possible that between A andB variables of other .cpp are initialized. For example, if you have three units with the following global / static variables:

Image1

In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp):

Image2

Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).

Hidden dependencies and * test cases *

I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.

Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?

After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.

In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).

Solution

This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.

If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.

If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.

But is it always bad?

Not necessarily, there may be good uses for global variables. For example, constant values ??(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ??tend to be primitive and are unlikely to change their definition.

It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.

Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout,std :: cin or std :: cerr, which are also global objects.

Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.

Answer by: Peregring-lk

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

How to compare two dates in php

Not answering the OPs actual problem, but answering just the title. Since this is the top result for "comparing dates in php".

Pretty simple to use Datetime Objects (php >= 5.3.0) and Compare them directly

$date1 = new DateTime("2009-10-11");
$date2 = new DateTime("tomorrow"); // Can use date/string just like strtotime.
var_dump($date1 < $date2);

Parsing huge logfiles in Node.js - read in line-by-line

You can use the inbuilt readline package, see docs here. I use stream to create a new output stream.

var fs = require('fs'),
    readline = require('readline'),
    stream = require('stream');

var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;

var rl = readline.createInterface({
    input: instream,
    output: outstream,
    terminal: false
});

rl.on('line', function(line) {
    console.log(line);
    //Do your stuff ...
    //Then write to outstream
    rl.write(cubestuff);
});

Large files will take some time to process. Do tell if it works.

A better way to check if a path exists or not in PowerShell

This is my powershell newbie way of doing this

if ((Test-Path ".\Desktop\checkfile.txt") -ne "True") {
    Write-Host "Damn it"
} else {
    Write-Host "Yay"
}

Exiting out of a FOR loop in a batch file?

You could simply use echo on and you will see that goto :eof or even exit /b doesn't work as expected.

The code inside of the loop isn't executed anymore, but the loop is expanded for all numbers to the end.
That's why it's so slow.

The only way to exit a FOR /L loop seems to be the variant of exit like the exsample of Wimmel, but this isn't very fast nor useful to access any results from the loop.

This shows 10 expansions, but none of them will be executed

echo on
for /l %%n in (1,1,10) do (
  goto :eof
  echo %%n
)

Force "portrait" orientation mode

According to Android's documentation, you should also often include screenSize as a possible configuration change.

android:configChanges="orientation|screenSize"

If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.

Also, if you all include value keyboardHidden in your examples, shouldn't you then also consider locale, mcc, fontScale, keyboard and others?..

Copy array by value

You can also use ES6 spread operator to copy Array

var arr=[2,3,4,5];
var copyArr=[...arr];

What's the difference between a 302 and a 307 redirect?

Originally there was just 302

Response What browsers should do
302 Found Redo request with new url

The idea is that:

  • if you were doing a GET at some location, you would redo your GET to the new URL
  • if you were doing a POST at some location, you would redo your POST to the new URL
  • if you were doing a PUT at some location, you would redo your PUT to the new URL
  • if you were doing a DELETE at some location, you would redo your DELETE to the new URL
  • etc

Unfortunately every browser did it wrong. When getting a 302, they would always switch to GET at the new URL, rather than retrying the request with the same verb (e.g., POST):

  • Mosaic did it wrong
  • Netscape copied the bugs in Mosaic; so they got it wrong
  • Internet Explorer copied the bugs in Netscape; so they got it wrong

It became de-facto wrong.

All browsers got 302 wrong. So 303 and 307 were created.

Response What browsers should do What browsers actually do
302 Found Redo request with new url GET with new url
303 See Other GET with new url GET with new url
307 Temporary Redirect Redo request with new url Redo request with new url

In chart form

The 5 different kinds of redirects:

+------------------------------------------------------------+
¦           ¦                Switch to GET?                  ¦
¦           ¦------------------------------------------------¦
¦ Temporary ¦          No            ¦         Yes           ¦
¦-----------+------------------------+-----------------------¦
¦ No        ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes       ¦ 307 Temporary Redirect ¦ 303 See Other         ¦
¦           ¦ 302 Found (intended)   ¦ 302 Found (actual)    ¦
+------------------------------------------------------------+

Alternatively:

Response Switch to get? Temporary?
301 Moved Permanently No No
302 Found (intended) No Yes
302 Found (actual) Yes Yes
303 See Other Yes Yes
307 Temporary Redirect No Yes
308 Permanent Redirect No No

How do I make a composite key with SQL Server Management Studio?

Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')

Holding down the Ctrl key highlight two or more columns in the left hand table margin

Hit the little 'Key' on the standard menu bar at the top

You're done..

:-)

How to detect pressing Enter on keyboard using jQuery?

this my how I solved you shoud give return false;

_x000D_
_x000D_
 
 $(document).on('keypress',function(e) {
            if(e.which == 13) {
                $('#sub_btn').trigger('click');
                alert('You pressed a "enter" key in somewhere'); 
                return false;     
            }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
                    <div class="modal-header">
                        <button type="button" class="close" id="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Subscribe to our Technical Analysis</h4>
                    </div>
                    <div class="modal-body">
                        <p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
                        <div class="input-group">
                            <input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
                        </div>
                        <span id="save-error"></span>
                    </div>
                    <div class="modal-footer">
                        <div class="input-group-append">
                            <input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
                        </div>
                    </div>
                </form>
_x000D_
_x000D_
_x000D_

`

convert string array to string

Aggregate can also be used for same.

string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);

SHA-256 or MD5 for file integrity

The underlying MD5 algorithm is no longer deemed secure, thus while md5sum is well-suited for identifying known files in situations that are not security related, it should not be relied on if there is a chance that files have been purposefully and maliciously tampered. In the latter case, the use of a newer hashing tool such as sha256sum is highly recommended.

So, if you are simply looking to check for file corruption or file differences, when the source of the file is trusted, MD5 should be sufficient. If you are looking to verify the integrity of a file coming from an untrusted source, or over from a trusted source over an unencrypted connection, MD5 is not sufficient.

Another commenter noted that Ubuntu and others use MD5 checksums. Ubuntu has moved to PGP and SHA256, in addition to MD5, but the documentation of the stronger verification strategies are more difficult to find. See the HowToSHA256SUM page for more details.

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

How to use a DataAdapter with stored procedure and parameter

 SqlConnection con = new SqlConnection(@"Some Connection String");
 SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;

How to remove elements from a generic list while iterating over it?

Using .ToList() will make a copy of your list, as explained in this question: ToList()-- Does it Create a New List?

By using ToList(), you can remove from your original list, because you're actually iterating over a copy.

foreach (var item in listTracked.ToList()) {    

        if (DetermineIfRequiresRemoval(item)) {
            listTracked.Remove(item)
        }

     }

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How can I set a custom baud rate on Linux?

There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.

Usually, an application did the following steps on the serial port

  1. Set baud rate, parity, encoding, flow control, and starting / ending sequence length during program start. This setup can be done via ioctl to the serial device or 'stty' command. In fact, the stty command uses ioctl to that serial device.
  2. Write characters of data to the serial device and the driver will be writing data charaters to the UART chip through its 8-bit data bus.

In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

git-diff to ignore ^M

I struggled with this problem for a long time. By far the easiest solution is to not worry about the ^M characters and just use a visual diff tool that can handle them.

Instead of typing:

git diff <commitHash> <filename>

try:

git difftool <commitHash> <filename>

How do I serialize an object and save it to a file in Android?

You must add an ObjectSerialization class to your program the following may work

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;

    public class ObjectSerializer {

public static String serialize(Serializable obj) throws IOException {
    if (obj == null) return "";
    try {
        ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
        ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
        objStream.writeObject(obj);
        objStream.close();
        return encodeBytes(serialObj.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static Object deserialize(String str) throws IOException {
    if (str == null || str.length() == 0) return null;
    try {
        ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
        ObjectInputStream objStream = new ObjectInputStream(serialObj);
        return objStream.readObject();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public static String encodeBytes(byte[] bytes) {
    StringBuffer strBuf = new StringBuffer();

    for (int i = 0; i < bytes.length; i++) {
        strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
        strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
    }

    return strBuf.toString();
}

public static byte[] decodeBytes(String str) {
    byte[] bytes = new byte[str.length() / 2];
    for (int i = 0; i < str.length(); i+=2) {
        char c = str.charAt(i);
        bytes[i/2] = (byte) ((c - 'a') << 4);
        c = str.charAt(i+1);
        bytes[i/2] += (c - 'a');
    }
    return bytes;
}

}

if you are using to store an array with SharedPreferences than use following:-

SharedPreferences sharedPreferences = this.getSharedPreferences(getPackageName(),MODE_PRIVATE);

To Serialize:-

sharedPreferences.putString("name",ObjectSerializer.serialize(array));

To Deserialize:-

newarray = (CAST_IT_TO_PROPER_TYPE) ObjectSerializer.deSerialize(sharedPreferences.getString(name),null);

NPM: npm-cli.js not found when running npm

I encountered the exact same problem today in a Linux server. And the reason is really simple as I didn't do make install after make and tried to directly call the generated npm. Thus the PATH and everything was a mess.

So for me, the solution is just to do make install after make and run the npm under .node/bin/npm.

What is the difference between a string and a byte string?

Unicode is an agreed-upon format for the binary representation of characters and various kinds of formatting (e.g. lower case/upper case, new line, carriage return), and other "things" (e.g. emojis). A computer is no less capable of storing a unicode representation (a series of bits), whether in memory or in a file, than it is of storing an ascii representation (a different series of bits), or any other representation (series of bits).

For communication to take place, the parties to the communication must agree on what representation will be used.

Because unicode seeks to represent all the possible characters (and other "things") used in inter-human and inter-computer communication, it requires a greater number of bits for the representation of many characters (or things) than other systems of representation that seek to represent a more limited set of characters/things. To "simplify," and perhaps to accommodate historical usage, unicode representation is almost exclusively converted to some other system of representation (e.g. ascii) for the purpose of storing characters in files.

It is not the case that unicode cannot be used for storing characters in files, or transmitting them through any communications channel, simply that it is not.

The term "string," is not precisely defined. "String," in its common usage, refers to a set of characters/things. In a computer, those characters may be stored in any one of many different bit-by-bit representations. A "byte string" is a set of characters stored using a representation that uses eight bits (eight bits being referred to as a byte). Since, these days, computers use the unicode system (characters represented by a variable number of bytes) to store characters in memory, and byte strings (characters represented by single bytes) to store characters to files, a conversion must be used before characters represented in memory will be moved into storage in files.

HTML button to NOT submit form

I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.

<button type="button">My Button</button>

Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):

The missing value default and invalid value default are the Submit Button state.

Onchange open URL via select - jQuery

Try this code its working perfect

<script>
$(function() {

    $("#submit").hide();

    $("#page-changer select").change(function() {
        window.location = $("#page-changer select option:selected").val();
    })

});
</script>

<?php
    if (isset($_POST['nav'])) {
         header("Location: $_POST[nav]");
    }
?>
<form id="page-changer" action="" method="post">
    <select name="nav">
        <option value="">Go to page...</option>
        <option value="http://css-tricks.com/">CSS-Tricks</option>
        <option value="http://digwp.com/">Digging Into WordPress</option>
        <option value="http://quotesondesign.com/">Quotes on Design</option>
    </select>
    <input type="submit" value="Go" id="submit" />
</form>

Function to convert timestamp to human date in javascript

To calculate date in timestamp from the given date

//To get the timestamp date from normal date: In format - 1560105000000

//input date can be in format : "2019-06-09T18:30:00.000Z"

this.calculateDateInTimestamp = function (inputDate) {
    var date = new Date(inputDate);
    return date.getTime();
}

output : 1560018600000

Cassandra port usage - how are the ports used?

I resolved issue using below steps :

  1. Stop cassandara services

    sudo su -
    systemctl stop datastax-agent
    systemctl stop opscenterd
    systemctl stop app-dse
    
  2. Take backup and Change port from 9042 to 9035

    cp /opt/dse/resources/cassandra/conf/cassandra.yaml /opt/dse/resources/cassandra/conf/bkp_cassandra.yaml
    Vi /opt/dse/resources/cassandra/conf/cassandra.yaml
    native_transport_port: 9035
    
  3. Start Cassandra services

    systemctl start datastax-agent
    systemctl start opscenterd
    systemctl start app-dse
    
  4. create cqlshrc file.

    vi  /root/.cassandra/cqlshrc
    
    [connection]
    hostname = 198.168.1.100
    port = 9035
    

Thanks, Mahesh

Escape @ character in razor view engine

use <text></text> or the easier way @:

Python Linked List

When using immutable linked lists, consider using Python's tuple directly.

ls = (1, 2, 3, 4, 5)

def first(ls): return ls[0]
def rest(ls): return ls[1:]

Its really that ease, and you get to keep the additional funcitons like len(ls), x in ls, etc.

undefined reference to boost::system::system_category() when compiling

When I had this, problem, the cause was the ordering of the libraries. To fix it, I put libboost_system last:

g++ mingw/timer1.o -o mingw/timer1.exe  -L/usr/local/boost_1_61_0/stage/lib \
    -lboost_timer-mgw53-mt-1_61 \
    -lboost_chrono-mgw53-mt-1_61 \
    -lboost_system-mgw53-mt-1_61

This was on mingw with gcc 5.3 and boost 1.61.0 with a simple timer example.

What is the best collation to use for MySQL with PHP?

Actually, you probably want to use utf8_unicode_ci or utf8_general_ci.

  • utf8_general_ci sorts by stripping away all accents and sorting as if it were ASCII
  • utf8_unicode_ci uses the Unicode sort order, so it sorts correctly in more languages

However, if you are only using this to store English text, these shouldn't differ.

How to dynamically add a style for text-align using jQuery

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $( document ).ready(function() {
      $this = $('h1');
         $this.css('color','#3498db');
         $this.css('text-align','center');
         $this.css('border','1px solid #ededed');
      });
    </script>

  </head>
  <body>
      <h1>Title</h1>
 </body>
</html>

How do you run a Python script as a service in Windows?

pysc: Service Control Manager on Python

Example script to run as a service taken from pythonhosted.org:

from xmlrpc.server import SimpleXMLRPCServer

from pysc import event_stop


class TestServer:

    def echo(self, msg):
        return msg


if __name__ == '__main__':
    server = SimpleXMLRPCServer(('127.0.0.1', 9001))

    @event_stop
    def stop():
        server.server_close()

    server.register_instance(TestServer())
    server.serve_forever()

Create and start service

import os
import sys
from xmlrpc.client import ServerProxy

import pysc


if __name__ == '__main__':
    service_name = 'test_xmlrpc_server'
    script_path = os.path.join(
        os.path.dirname(__file__), 'xmlrpc_server.py'
    )
    pysc.create(
        service_name=service_name,
        cmd=[sys.executable, script_path]
    )
    pysc.start(service_name)

    client = ServerProxy('http://127.0.0.1:9001')
    print(client.echo('test scm'))

Stop and delete service

import pysc

service_name = 'test_xmlrpc_server'

pysc.stop(service_name)
pysc.delete(service_name)
pip install pysc

MySQLDump one INSERT statement for each data row

Use:

mysqldump --extended-insert=FALSE 

Be aware that multiple inserts will be slower than one big insert.

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

Basics

The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

The common interfaces

The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

  • CrudRepository - CRUD methods
  • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

Store-specific interfaces

The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

Custom repository base interfaces

The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

  1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
  2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }

interface ReadOnlyRepository<T> extends Repository<T, Long> {

  // Al finder methods go here
}

The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

Summary - tl;dr

The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

Can I invoke an instance method on a Ruby module without including it?

To invoke a module instance method without including the module (and without creating intermediary objects):

class UsefulWorker
  def do_work
    UsefulThings.instance_method(:format_text).bind(self).call("abc")
    ...
  end
end

Sort an Array by keys based on another Array?

IF you have array in your array, you'll have to adapt the function by Eran a little bit...

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key => $value) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

How to get the difference between two dictionaries in Python?

This function gives you all the diffs (and what stayed the same) based on the dictionary keys only. It also highlights some nice Dict comprehension, Set operations and python 3.6 type annotations :)

from typing import Dict, Any, Tuple
def get_dict_diffs(a: Dict[str, Any], b: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:

    added_to_b_dict: Dict[str, Any] = {k: b[k] for k in set(b) - set(a)}
    removed_from_a_dict: Dict[str, Any] = {k: a[k] for k in set(a) - set(b)}
    common_dict_a: Dict[str, Any] = {k: a[k] for k in set(a) & set(b)}
    common_dict_b: Dict[str, Any] = {k: b[k] for k in set(a) & set(b)}
    return added_to_b_dict, removed_from_a_dict, common_dict_a, common_dict_b

If you want to compare the dictionary values:

values_in_b_not_a_dict = {k : b[k] for k, _ in set(b.items()) - set(a.items())}

Sum all values in every column of a data.frame in R

You can use function colSums() to calculate sum of all values. [,-1] ensures that first column with names of people is excluded.

 colSums(people[,-1])
Height Weight 
   199    425

Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:

colSums(Filter(is.numeric, people))

C# Ignore certificate errors?

Old, but still helps...

Another great way of achieving the same behavior is through configuration file (web.config)

 <system.net>
    <settings>
      <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false" />
    </settings>
  </system.net>

NOTE: tested on .net full.

PHP Fatal error: Cannot access empty property

I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...

You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:

        foreach ($object->someArray as $key->$val) {
            // do something
        }

Of course, I should have had:

        foreach ($object->someArray as $key=>$val) {
            // do something
        }

I confused myself at first, thinking the reported error was referring to the someArray property!

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Remove servlet.jar from source web-inf/lib folder as it is available in tomcat lib folder then it works fine

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

How to adjust layout when soft keyboard appears

I use this Extended class frame And when I need to recalculate the height size onLayout I override onmeasure and subtract keyboardHeight using getKeyboardHeight()

My create frame who needs resize with softkeyboard

SizeNotifierFrameLayout frameLayout = new SizeNotifierFrameLayout(context) {
            private boolean first = true;

            @Override
            protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
                super.onLayout(changed, left, top, right, bottom);

                if (changed) {
                    fixLayoutInternal(first);
                    first = false;
                }
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - getKeyboardHeight(), MeasureSpec.EXACTLY));
            }

            @Override
            protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
                boolean result = super.drawChild(canvas, child, drawingTime);
                if (child == actionBar) {
                    parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
                }
                return result;
            }


        };

SizeNotifierFrameLayout

public class SizeNotifierFrameLayout extends FrameLayout {

    public interface SizeNotifierFrameLayoutDelegate {
        void onSizeChanged(int keyboardHeight, boolean isWidthGreater);
    }

    private Rect                            rect            = new Rect();
    private Drawable                        backgroundDrawable;
    private int                             keyboardHeight;
    private int                             bottomClip;
    private SizeNotifierFrameLayoutDelegate delegate;
    private boolean                         occupyStatusBar = true;

    public SizeNotifierFrameLayout(Context context) {
        super(context);
        setWillNotDraw(false);
    }

    public Drawable getBackgroundImage() {
        return backgroundDrawable;
    }

    public void setBackgroundImage(Drawable bitmap) {
        backgroundDrawable = bitmap;
        invalidate();
    }

    public int getKeyboardHeight() {
        View rootView = getRootView();
        getWindowVisibleDisplayFrame(rect);
        int usableViewHeight = rootView.getHeight() - (rect.top != 0 ? AndroidUtilities.statusBarHeight : 0) - AndroidUtilities.getViewInset(rootView);
        return usableViewHeight - (rect.bottom - rect.top);
    }

    public void notifyHeightChanged() {
        if (delegate != null) {
            keyboardHeight = getKeyboardHeight();
            final boolean isWidthGreater = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y;
            post(new Runnable() {
                @Override
                public void run() {
                    if (delegate != null) {
                        delegate.onSizeChanged(keyboardHeight, isWidthGreater);
                    }
                }
            });
        }
    }

    public void setBottomClip(int value) {
        bottomClip = value;
    }

    public void setDelegate(SizeNotifierFrameLayoutDelegate delegate) {
        this.delegate = delegate;
    }

    public void setOccupyStatusBar(boolean value) {
        occupyStatusBar = value;
    }

    protected boolean isActionBarVisible() {
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (backgroundDrawable != null) {
            if (backgroundDrawable instanceof ColorDrawable) {
                if (bottomClip != 0) {
                    canvas.save();
                    canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - bottomClip);
                }
                backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
                backgroundDrawable.draw(canvas);
                if (bottomClip != 0) {
                    canvas.restore();
                }
            } else if (backgroundDrawable instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
                if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
                    canvas.save();
                    float scale = 2.0f / AndroidUtilities.density;
                    canvas.scale(scale, scale);
                    backgroundDrawable.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
                    backgroundDrawable.draw(canvas);
                    canvas.restore();
                } else {
                    int actionBarHeight =
                            (isActionBarVisible() ? ActionBar.getCurrentActionBarHeight() : 0) + (Build.VERSION.SDK_INT >= 21 && occupyStatusBar ? AndroidUtilities.statusBarHeight : 0);
                    int   viewHeight = getMeasuredHeight() - actionBarHeight;
                    float scaleX     = (float) getMeasuredWidth() / (float) backgroundDrawable.getIntrinsicWidth();
                    float scaleY     = (float) (viewHeight + keyboardHeight) / (float) backgroundDrawable.getIntrinsicHeight();
                    float scale      = scaleX < scaleY ? scaleY : scaleX;
                    int   width      = (int) Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
                    int   height     = (int) Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
                    int   x          = (getMeasuredWidth() - width) / 2;
                    int   y          = (viewHeight - height + keyboardHeight) / 2 + actionBarHeight;
                    canvas.save();
                    canvas.clipRect(0, actionBarHeight, width, getMeasuredHeight() - bottomClip);
                    backgroundDrawable.setBounds(x, y, x + width, y + height);
                    backgroundDrawable.draw(canvas);
                    canvas.restore();
                }
            }
        } else {
            super.onDraw(canvas);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        notifyHeightChanged();
    }
}

Bootstrap 3 hidden-xs makes row narrower

.row {
    margin-right: 15px;
}

throw this in your CSS

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

If You try to insert other than the number in the Table column you get Constraint[numbering] error.

Try to insert the only number (or) make your Table column to char Type

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

Regarding the Hibernate validator documentation page, you have to define a dependency to a JSR-341 implementation:

<dependency>
   <groupId>org.glassfish</groupId>
   <artifactId>javax.el</artifactId>
   <version>3.0.1-b11</version>
</dependency>

C++ String array sorting

My solution is slightly different to any of those above and works as I just ran it.So for interest:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
  char *name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
  vector<string> v(name, name + 14);

  sort(v.begin(),v.end());
  for(vector<string>::const_iterator i = v.begin(); i != v.end(); ++i) cout << *i << ' ';
  return 0;
}

TypeError: cannot perform reduce with flexible type

When your are trying to apply prod on string type of value like:

['-214' '-153' '-58' ..., '36' '191' '-37']

you will get the error.

Solution: Append only integer value like [1,2,3], and you will get your expected output.

If the value is in string format before appending then, in the array you can convert the type into int type and store it in a list.

Test for array of string type in TypeScript

I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

If you have a type like: Object[] | string[] and what to do something conditionally based on what type it is - you can use this type guarding:

function isStringArray(value: any): value is string[] {
  if (value instanceof Array) {
    value.forEach(function(item) { // maybe only check first value?
      if (typeof item !== 'string') {
        return false
      }
    })
    return true
  }
  return false
}

function join<T>(value: string[] | T[]) {
  if (isStringArray(value)) {
    return value.join(',') // value is string[] here
  } else {
    return value.map((x) => x.toString()).join(',') // value is T[] here
  }
}

There is an issue with an empty array being typed as string[], but that might be okay

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

Checking host availability by using ping in bash scripts

up=`fping -r 1 $1 `
if [ -z "${up}" ]; then
    printf "Host $1 not responding to ping   \n"
    else
    printf "Host $1 responding to ping  \n"
fi

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

Can be triggered by a stray comma (,) in an RxJS pipe(...)

The compile won't catch this extra comma at the end:

pipe(first(), map(result => ({ event: 'completed', result: result}),);

It becomes an 'invisible' undefined operator which screws the whole pipe up, and leads to a very confusing error message - which in this case has nothing to do with my actual logic.

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

When do you use POST and when do you use GET?

Because GETs are purely URLs, they can be cached by the web browser and may be better used for things like consistently generated images. (Set an Expiry time)

One example from the gravatar page: http://www.gravatar.com/avatar/4c3be63a4c2f539b013787725dfce802?d=monsterid

GET may yeild marginally better performance, some webservers write POST contents to a temporary file before invoking the handler.

Another thing to consider is the size limit. GETs are capped by the size of the URL, 1024 bytes by the standard, though browsers may support more.

Transferring more data than that should use a POST to get better browser compatibility.

Even less than that limit is a problem, as another poster wrote, anything in the URL could end up in other parts of the brower's UI, like history.

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

Stopping a windows service when the stop option is grayed out

If you run the command:

sc queryex <service name>

where is the the name of the service, not the display name (spooler, not Print Spooler), at the cmd prompt it will return the PID of the process the service is running as. Take that PID and run

taskkill /F /PID <Service PID>

to force the PID to stop. Sometimes if the process hangs while stopping the GUI won't let you do anything with the service.

Get a specific bit from byte

Try the code below. The difference with other posts is that you can set/get multiple bits using a mask (field). The mask for the 4th bit can be 1<<3, or 0x10, for example.

    public int SetBits(this int target, int field, bool value)
    {
        if (value) //set value
        {
            return target | field;
        }
        else //clear value
        {
            return target & (~field);
        }
    }

    public bool GetBits(this int target, int field)
    {
        return (target & field) > 0;
    }

** Example **

        bool is_ok = 0x01AF.GetBits(0x10); //false
        int res = 0x01AF.SetBits(0x10, true);
        is_ok = res.GetBits(0x10);  // true

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

This IP, site or mobile application is not authorized to use this API key

I had the same issue and I found this.

On the url, it requires the server key in the end and not the api key for the app.

So Basically, you just add the server key in the end of the URL like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&sensor=true&key=SERVERKEY

Now, to obtain the server key, just follow these steps:

1) Go to Developer Console https://code.google.com/apis/console/

2) In the Credentials, under Public API Access, Create New key

3) Select the server key from the option.

4) Enter your IP Address on the field and if you have more ip addresses, you can just add on every single line.NOTE: Enter the IP Address only when you want to use it for your testing purpose. Else leave the IP Address section blank.

5) Once you are done, click create and your new Server Key will be generated and you can then add that server key to your URL.

Last thing is that, instead of putting the sensor=true in the middle of the URL, you can add it in the end like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&key=SERVERKEY&sensor=true

This will definitely solve the issue and just remember to use the server key for Places API.

EDIT

I believe the web URL has changed in the past years. You can access developers console from here now - https://console.developers.google.com/apis/dashboard

  • Navigate to developers console - https://console.developers.google.com/ or use the link from details to navigate directly to API dashboard.
  • Under developer console, find Label from the left navigation panel
  • Select project
  • Choose Credentials from the left Navigation panel
  • You could create credentials type from the Top nav bar as required.

Hope this answer will help you and other viewers. Good Luck .. :)

How to get filename without extension from file path in Ruby

Jonathan Lonowski answered perfectly, but there is something that none of the answers mentioned here. Instead of File::extname, you can directly use a '.*' to get the file name.

File.basename("C:\\projects\\blah.dll", ".*") # => "C:\\projects\\blah"

But, if you want to get the base file name of any specific extension files, then you need to use File::extname, otherwise not.