Programs & Examples On #Pluggable

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Starting with MySQL 8.0.4, they have changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.

You can run the below command to resolve the issue.

sample username / password => student / pass123

ALTER USER 'student'@'localhost' IDENTIFIED WITH mysql_native_password BY 'pass123';

Refer the official page for details: MySQL Reference Manual

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

My application.properties looked something like this

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=root

The only thing worked for me is to maven clean and then maven install.

JBoss vs Tomcat again

Take a look at TOMEE

It has all the features that you need to build a complete Java EE app.

Get started with Latex on Linux

To get started with LaTeX on Linux, you're going to need to install a couple of packages:

  1. You're going to need a LaTeX distribution. This is the collection of programs that comprise the (La)TeX computer typesetting system. The standard LaTeX distribution on Unix systems used to be teTeX, but it has been superceded by TeX Live. Most Linux distributions have installation packages for TeX Live--see, for example, the package database entries for Ubuntu and Fedora.

  2. You will probably want to install a LaTeX editor. Standard Linux text editors will work fine; in particular, Emacs has a nice package of (La)TeX editing macros called AUCTeX. Specialized LaTeX editors also exist; of those, Kile (KDE Integrated LaTeX Environment) is particularly nice.

  3. You will probably want a LaTeX tutorial. The classic tutorial is "A (Not So) Short Introduction to LaTeX2e," but nowadays the LaTeX wikibook might be a better choice.

Vertically align text within input field of fixed-height without display: table or padding?

In Opera 9.62, Mozilla 3.0.4, Safari 3.2 (for Windows) it helps, if you put some text or at least a whitespace within the same line as the input field.

<div style="line-height: 60px; height: 60px; border: 1px solid black;">
    <input type="text" value="foo" />&nbsp;
</div>

(imagine an &nbsp after the input-statement)

IE 7 ignores every CSS hack I tried. I would recommend using padding for IE only. Should make it easier for you to position it correctly if it only has to work within one specific browser.

Get a worksheet name using Excel VBA

Extend Code for Show Selected Sheet(s) [ one or more sheets].

Sub Show_SelectSheet()
  For Each xSheet In ThisWorkbook.Worksheets
     For Each xSelectSheet In ActiveWindow.SelectedSheets
         If xSheet.Name = xSelectSheet.Name Then
            '=== Show Selected Sheet ===
            GoTo xNext_SelectSheet
         End If
     Next xSelectSheet
  xSheet.Visible = False  
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub

How to change navbar/container width? Bootstrap 3

The .navbar-static-top you are using forces your navbar to become full-width. Remove that class and you will get a resizable navbar. Then, you can wrap it in a span# of the size you want.

<div class="container">
<div class="row">
    <div class="span6 offset3">
        <div class="navbar">
            ...
        </div>
    </div>
</div>

Update OpenSSL on OS X with Homebrew

  1. install port: https://guide.macports.org/
  2. install or upgrade openssl package: sudo port install openssl or sudo port upgrade openssl
  3. that's it, run openssl version to see the result.

jQuery: Currency Format Number

You can use this way to format your currency needing.

var xx = new Intl.NumberFormat(‘en-US’, {
  style: ‘currency’,
  currency: ‘USD’,
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
xx.format(123456.789); // ‘$123,456.79’

For more info you can access this link.

https://www.justinmccandless.com/post/formatting-currency-in-javascript/

How do I write a backslash (\) in a string?

even though this post is quite old I tried something that worked for my case .

I wanted to create a string variable with the value below:

21541_12_1_13\":null

so my approach was like that:

  • build the string using verbatim

    string substring = @"21541_12_1_13\"":null";

  • and then remove the unwanted backslashes using Remove function

    string newsubstring = substring.Remove(13, 1);

Hope that helps. Cheers

How to configure PostgreSQL to accept all incoming connections

Just use 0.0.0.0/0.

host    all             all             0.0.0.0/0            md5

Make sure the listen_addresses in postgresql.conf (or ALTER SYSTEM SET) allows incoming connections on all available IP interfaces.

listen_addresses = '*'

After the changes you have to reload the configuration. One way to do this is execute this SELECT as a superuser.

SELECT pg_reload_conf();

Note: to change listen_addresses, a reload is not enough, and you have to restart the server.

php pdo: get the columns name of a table

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

must be

$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

AngularJS: Basic example to use authentication in Single Page Application

I answered a similar question here: AngularJS Authentication + RESTful API


I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.

You could either:

  1. Modify the module and attach it to your own API, or
  2. Use the module together with UserApp (a cloud-based user management API)

https://github.com/userapp-io/userapp-angular

If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.

Here's some examples of how it works:

  • How to specify which routes that should be public, and which route that is the login form:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
    

    The .otherwise() route should be set to where you want your users to be redirected after login. Example:

    $routeProvider.otherwise({redirectTo: '/home'});

  • Login form with error handling:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • Signup form with error handling:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    
  • Log out link:

    <a href="#" ua-logout>Log Out</a>

    (Ends the session and redirects to the login route)

  • Access user properties:

    User properties are accessed using the user service, e.g: user.current.email

    Or in the template: <span>{{ user.email }}</span>

  • Hide elements that should only be visible when logged in:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • Show an element based on permissions:

    <div ua-has-permission="admin">You are an admin</div>

And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.

If you need any help, just let me know!

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

In Kotlin:

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
    // Handle the back button event
}

For more information you can check this.

There is also specific question about overriding back button in Kotlin.

How can I break from a try/catch block without throwing an exception in Java

There are several ways to do it:

  1. Move the code into a new method and return from it

  2. Wrap the try/catch in a do{}while(false); loop.

Python Iterate Dictionary by Index

When I need to keep the order, I use a list and a companion dict:

color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
    color[i]

The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:

fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)): 
    fruitcolor[i][1]
for f, c in fruitcolor:
    c

Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

The error message means that any method that calls showfile() must either declare that it, in turn, throws IOException, or the call must be inside a try block that catches IOException. When you call showfile(), you do neither of these; for example, your filecontent constructor neither declares IOException nor contains a try block.

The intent is that some method, somewhere, should contain a try block, and catch and handle this exception. The compiler is trying to force you to handle the exception somewhere.

By the way, this code is (sorry to be so blunt) horrible. You don't close any of the files you open, the BufferedReader always points to the first file, even though you seem to be trying to make it point to another, the loops contain off-by-one errors that will cause various exceptions, etc. When you do get this to compile, it will not work as you expect. I think you need to slow down a little.

How to check if a database exists in SQL Server?

I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
    declare @result bit = 0 
    SELECT @result = CAST(
        CASE WHEN db_id(@dbname) is not null THEN 1 
        ELSE 0 
        END 
    AS BIT)
    return @result
END
GO

Now you can use it like this:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

Git Pull vs Git Rebase

In a nutshell :

-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record

-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

Simulate limited bandwidth from within Chrome?

As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.

How to set bootstrap navbar active class with Angular JS?

Just to add my two cents in the debate I have made a pure angular module (no jquery), and it will also work with hash urls containing data. (i.g. #/this/is/path?this=is&some=data)

You just add the module as a dependency and auto-active to one of the ancestors of the menu. Like this:

<ul auto-active>
    <li><a href="#/">main</a></li>
    <li><a href="#/first">first</a></li>
    <li><a href="#/second">second</a></li>
    <li><a href="#/third">third</a></li>
</ul>

And the module look like this:

(function () {
    angular.module('autoActive', [])
        .directive('autoActive', ['$location', function ($location) {
        return {
            restrict: 'A',
            scope: false,
            link: function (scope, element) {
                function setActive() {
                    var path = $location.path();
                    if (path) {
                        angular.forEach(element.find('li'), function (li) {
                            var anchor = li.querySelector('a');
                            if (anchor.href.match('#' + path + '(?=\\?|$)')) {
                                angular.element(li).addClass('active');
                            } else {
                                angular.element(li).removeClass('active');
                            }
                        });
                    }
                }

                setActive();

                scope.$on('$locationChangeSuccess', setActive);
            }
        }
    }]);
}());

* (You can of course just use the directive part)

** It's also worth noticing that this doesn't work for empty hashes (i.g. example.com/# or just example.com) it needs to have at least example.com/#/ or just example.com#/. But this happens automatically with ngResource and the like.

iOS 7's blurred overlay effect using CSS?

I've been using svg filters to achieve similar effects for sprites

<svg id="gray_calendar" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 48 48 48">
  <filter id="greyscale">
    <feColorMatrix type="saturate" values="0"/>
  </filter>
  <image width="48" height="10224" xlink:href="tango48i.png" filter="url(#greyscale)"/>
</svg>
  • The viewBox attribute will select just the portion of your included image that you want.
  • Just change the filter to any that you want, such as Keith's <feGaussianBlur stdDeviation="10"/> example.
  • Use the <image ...> tag to apply it to any image or even use multiple images.
  • You can build this up with js and use it as an image or use the id in your css.

Laravel: PDOException: could not find driver

First check php -m
.If you don't see mysql driver install mysql sudo apt-cache search php-mysql
Your results will be similar to:

php-mysql - MySQL module for PHP [default]


install php- mysql Driver

sudo apt-get install php7.1-mysql

how can I debug a jar at runtime?

http://www.eclipsezone.com/eclipse/forums/t53459.html

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044

The application, at launch, will wait until you connect from another source.

presentViewController and displaying navigation bar

I use this code. It's working fine in iOS 8.

MyProfileEditViewController *myprofileEdit=[self.storyboard instantiateViewControllerWithIdentifier:@"myprofileeditSid"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:myprofileEdit];
[self presentViewController:navigationController animated:YES completion:^{}];

What is the difference between active and passive FTP?

Redacted version of my article FTP Connection Modes (Active vs. Passive):

FTP connection mode (active or passive), determines how a data connection is established. In both cases, a client creates a TCP control connection to an FTP server command port 21. This is a standard outgoing connection, as with any other file transfer protocol (SFTP, SCP, WebDAV) or any other TCP client application (e.g. web browser). So, usually there are no problems when opening the control connection.

Where FTP protocol is more complicated comparing to the other file transfer protocols are file transfers. While the other protocols use the same connection for both session control and file (data) transfers, the FTP protocol uses a separate connection for the file transfers and directory listings.

In the active mode, the client starts listening on a random port for incoming data connections from the server (the client sends the FTP command PORT to inform the server on which port it is listening). Nowadays, it is typical that the client is behind a firewall (e.g. built-in Windows firewall) or NAT router (e.g. ADSL modem), unable to accept incoming TCP connections.

For this reason the passive mode was introduced and is mostly used nowadays. Using the passive mode is preferable because most of the complex configuration is done only once on the server side, by experienced administrator, rather than individually on a client side, by (possibly) inexperienced users.

In the passive mode, the client uses the control connection to send a PASV command to the server and then receives a server IP address and server port number from the server, which the client then uses to open a data connection to the server IP address and server port number received.

Network Configuration for Passive Mode

With the passive mode, most of the configuration burden is on the server side. The server administrator should setup the server as described below.

The firewall and NAT on the FTP server side have to be configured not only to allow/route the incoming connections on FTP port 21 but also a range of ports for the incoming data connections. Typically, the FTP server software has a configuration option to setup a range of the ports, the server will use. And the same range has to be opened/routed on the firewall/NAT.

When the FTP server is behind a NAT, it needs to know it's external IP address, so it can provide it to the client in a response to PASV command.

Network Configuration for Active Mode

With the active mode, most of the configuration burden is on the client side.

The firewall (e.g. Windows firewall) and NAT (e.g. ADSL modem routing rules) on the client side have to be configured to allow/route a range of ports for the incoming data connections. To open the ports in Windows, go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules > New Rule. For routing the ports on the NAT (if any), refer to its documentation.

When there's NAT in your network, the FTP client needs to know its external IP address that the WinSCP needs to provide to the FTP server using PORT command. So that the server can correctly connect back to the client to open the data connection. Some FTP clients are capable of autodetecting the external IP address, some have to be manually configured.

Smart Firewalls/NATs

Some firewalls/NATs try to automatically open/close data ports by inspecting FTP control connection and/or translate the data connection IP addresses in control connection traffic.

With such a firewall/NAT, the above configuration is not necessary for a plain unencrypted FTP. But this cannot work with FTPS, as the control connection traffic is encrypted and the firewall/NAT cannot inspect nor modify it.

Exporting result of select statement to CSV format in DB2

I tried this and got a ';'-delimited csv file:

--#SET TERMINATOR % 
EXPORT TO result.csv OF DEL MODIFIED BY CHARDEL;
SELECT * FROM A

Add inline style using Javascript

You can try with this

nFilter.style.cssText = 'width:330px;float:left;';

That should do it for you.

private final static attribute vs private final attribute

While the other answers seem to make it pretty clear that there is generally no reason to use non-static constants, I couldn't find anyone pointing out that it is possible to have various instances with different values on their constant variables.

Consider the following example:

public class TestClass {
    private final static double NUMBER = Math.random();

    public TestClass () {
        System.out.println(NUMBER);
    }
}

Creating three instances of TestClass would print the same random value three times, since only one value is generated and stored into the static constant.

However, when trying the following example instead:

public class TestClass {
    private final double NUMBER = Math.random();

    public TestClass () {
        System.out.println(NUMBER);
    }
}

Creating three instances of TestClass would now print three different random values, because each instance has its own randomly generated constant value.

I can't think of any situation where it would be really useful to have different constant values on different instances, but I hope this helps pointing out that there is a clear difference between static and non-static finals.

How to force composer to reinstall a library?

Reinstall the dependencies. Remove the vendor folder (manually) or via rm command (if you are in the project folder, sure) on Linux before:

rm -rf vendor/

composer update -v

https://www.dev-metal.com/composer-problems-try-full-reset/

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

Programmatically stop execution of python script?

sys.exit() will do exactly what you want.

import sys
sys.exit("Error message")

URL encode sees “&” (ampersand) as “&amp;” HTML entity

If you did literally this:

encodeURIComponent('&')

Then the result is %26, you can test it here. Make sure the string you are encoding is just & and not &amp; to begin with...otherwise it is encoding correctly, which is likely the case. If you need a different result for some reason, you can do a .replace(/&amp;/g,'&') before the encoding.

How to Set focus to first text input in a bootstrap modal after shown

I found the best way to do this, without jQuery.

<input value="" autofocus>

works perfectly.

This is a html5 attribute. Supported by all major browsers.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

Manually put files to Android emulator SD card

In Visual Studio 2019 (Xamarin):

  1. Click on the Device Monitor (DDMS) button.

enter image description here

  1. Go to the File Explorer tab and click the button with a phone and a right-pointing arrow on top of it.

enter image description here

Oracle Not Equals Operator

As everybody else has said, there is no difference. (As a sanity check I did some tests, but it was a waste of time, of course they work the same.)

But there are actually FOUR types of inequality operators: !=, ^=, <>, and ¬=. See this page in the Oracle SQL reference. On the website the fourth operator shows up as ÿ= but in the PDF it shows as ¬=. According to the documentation some of them are unavailable on some platforms. Which really means that ¬= almost never works.

Just out of curiosity, I'd really like to know what environment ¬= works on.

Android OnClickListener - identify a button

In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.

How to remove all white space from the beginning or end of a string?

take a look at Trim() which returns a new string with whitespace removed from the beginning and end of the string it is called on.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I'm the creator of Restangular.

You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).

Check out this plunkr example:

http://plnkr.co/edit/d6yDka?p=preview

You could also see the README and check the documentation here https://github.com/mgonto/restangular

If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)

Hope it helps!

How to prevent scrollbar from repositioning web page?

The solutions posted using calc(100vw - 100%) are on the right track, but there is a problem with this: You'll forever have a margin to the left the size of the scrollbar, even if you resize the window so that the content fills up the entire viewport.

If you try to get around this with a media query you'll have an awkward snapping moment because the margin won't progressively get smaller as you resize the window.

Here's a solution that gets around that and AFAIK has no drawbacks:

Instead of using margin: auto to center your content, use this:

body {
margin-left: calc(50vw - 500px);
}

Replace 500px with half the max-width of your content (so in this example the content max-width is 1000px). The content will now stay centered and the margin will progressively decrease all the way until the content fills the viewport.

In order to stop the margin from going negative when the viewport is smaller than the max-width just add a media query like so:

@media screen and (max-width:1000px) {
    body {
        margin-left: 0;
    }
}

Et voilà!

What's the best UI for entering date of birth?

I would prefer a datepicker (and a input box with documented format as a fall-back) for an international site.

Date formats vary and are sometimes hard to read if you are now used to them. Too bad many people aren't comfortable with ISO 8601. :-(

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

if The given id is not exist in the DB ,then you may get this exception.

Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

How to make a <div> or <a href="#"> to align center

In your html file:

<a href="contact.html" class="button large hpbottom">Get Started</a>

In your css file:

.hpbottom{
    text-align: center;
}

How do I convert a string to a number in PHP?

I've been reading through answers and didn't see anybody mention the biggest caveat in PHP's number conversion.

The most upvoted answer suggests doing the following:

$str = "3.14"
$intstr = (int)$str // now it's a number equal to 3

That's brilliant. PHP does direct casting. But what if we did the following?

$str = "3.14is_trash"
$intstr = (int)$str

Does PHP consider such conversions valid?

Apparently yes.

PHP reads the string until it finds first non-numerical character for the required type. Meaning that for integers, numerical characters are [0-9]. As a result, it reads 3, since it's in [0-9] character range, it continues reading. Reads . and stops there since it's not in [0-9] range.

Same would happen if you were to cast to float or double. PHP would read 3, then ., then 1, then 4, and would stop at i since it's not valid float numeric character.

As a result, "million" >= 1000000 evaluates to false, but "1000000million" >= 1000000 evaluates to true.

See also:

https://www.php.net/manual/en/language.operators.comparison.php how conversions are done while comparing

https://www.php.net/manual/en/language.types.string.php#language.types.string.conversion how strings are converted to respective numbers

I want to get the type of a variable at runtime

So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:

val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x

But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:

val x: Any = 5
def f[T](v: T) = v match {
  case _: Int    => "Int"
  case _: String => "String"
  case _         => "Unknown"
}
f(x)

Here it doesn't matter what is the type of the variable, Any. What matters, what is checked is the type of 5, the value. In fact, T is useless -- you might as well have written it def f(v: Any) instead. Also, this uses either ClassTag or a value's Class, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_] (List of something), but not whether it is, for example, a List[Int] or List[String].

Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag or a TypeTag. For example:

val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"

A ClassTag will also let you use type parameters you received on match. This won't work:

def f[A, B](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}

But this will:

val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)

Here I'm using the context bounds syntax, B : ClassTag, which works just like the implicit parameter in the previous ClassTag example, but uses an anonymous variable.

One can also get a ClassTag from a value's Class, like this:

val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
  val B = ClassTag(b.getClass)
  ClassTag(a.getClass) match {
    case B => "a is the same class as b"
    case _ => "a is not the same class as b"
  }
}
f(x, y) == f(y, x) // true, a is the same class as b

A ClassTag is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag for List[Int] and List[String] is the same, List. If you need type parameters, then you must use a TypeTag instead. A TypeTag however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.

Examples with TypeTag can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:

import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int

Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag, so I'll stop here.

Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:

val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it

It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.

How to split data into trainset and testset randomly?

A quick note for the answer from @subin sahayam

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int(len(data)*.80+1):] #Splits 20% data to test set

If your list size is a even number, you should not add the 1 in the code below. Instead, you need to check the size of the list first and then determine if you need to add the 1.

test_data = data[int(len(data)*.80+1):]

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

How to print / echo environment variables?

The syntax

variable=value command

is often used to set an environment variables for a specific process. However, you must understand which process gets what variable and who interprets it. As an example, using two shells:

a=5
# variable expansion by the current shell:
a=3 bash -c "echo $a"
# variable expansion by the second shell:
a=3 bash -c 'echo $a'

The result will be 5 for the first echo and 3 for the second.

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

Yes there is one and it is inside the SQLServer management studio. Unlike the previous versions I think. Follow these simple steps.

1)Right click on a database in the Object explorer 2)Selected New Query from the popup menu 3)Query Analyzer will be opened.

Enjoy work.

How to get browser width using JavaScript code?

From W3schools and its cross browser back to the dark ages of IE!

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";

alert("Browser inner window width: " + w + ", height: " + h + ".");

</script>

</body>
</html>

Can't connect to MySQL server on 'localhost' (10061)

You'll probably have to grant 'localhost' privileges to on the table to the user. See the 'GRANT' syntax documentation. Here's an example (from some C source).

"GRANT ALL PRIVILEGES ON %s.* TO '%s'@'localhost' IDENTIFIED BY '%s'";

That's the most common access problem with MySQL.

Other than that, you might check that the user you have defined to create your instance has full privileges, else the user cannot grant privileges.

Also, make sure the mysql service is started.

Make sure you don't have a third party firewall or Internet security service turned on.

Beyond that, there's several pages of the MySQL forum devoted to this: http://forums.mysql.com/read.php?11,9293,9609#msg-9609

Try reading that.

VBA: Convert Text to Number

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

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

How do you add an action to a button programmatically in xcode

For Swift 3

Create a function for button action first and then add the function to your button target

func buttonAction(sender: UIButton!) {
    print("Button tapped")
}

button.addTarget(self, action: #selector(buttonAction),for: .touchUpInside)

Copy file or directories recursively in Python

Unix cp doesn't 'support both directories and files':

betelgeuse:tmp james$ cp source/ dest/
cp: source/ is a directory (not copied).

To make cp copy a directory, you have to manually tell cp that it's a directory, by using the '-r' flag.

There is some disconnect here though - cp -r when passed a filename as the source will happily copy just the single file; copytree won't.

Change SQLite database mode to read-write

If using Android.

Make sure you have added the permission to write to your EXTERNAL_STORAGE to your AndroidManifest.xml.

Add this line to your AndroidManifest.xml file above and outside your <application> tag.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

This will allow your application to write to the sdcard. This will help if your EXTERNAL_STORAGE is where you have stored your database on the device.

Detecting endianness programmatically in a C++ program

Unless you're using a framework that has been ported to PPC and Intel processors, you will have to do conditional compiles, since PPC and Intel platforms have completely different hardware architectures, pipelines, busses, etc. This renders the assembly code completely different between the two.

As for finding endianness, do the following:

short temp = 0x1234;
char* tempChar = (char*)&temp;

You will either get tempChar to be 0x12 or 0x34, from which you will know the endianness.

Export table data from one SQL Server to another

It can be done through "Import/Export Data..." in SQL Server Management Studio

Get last record of a table in Postgres

Easy way: ORDER BY in conjunction with LIMIT

SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1;

However, LIMIT is not standard and as stated by Wikipedia, The SQL standard's core functionality does not explicitly define a default sort order for Nulls.. Finally, only one row is returned when several records share the maximum timestamp.

Relational way:

The typical way of doing this is to check that no row has a higher timestamp than any row we retrieve.

SELECT timestamp, value, card
FROM my_table t1
WHERE NOT EXISTS (
  SELECT *
  FROM my_table t2
  WHERE t2.timestamp > t1.timestamp
);

It is my favorite solution, and the one I tend to use. The drawback is that our intent is not immediately clear when having a glimpse on this query.

Instructive way: MAX

To circumvent this, one can use MAX in the subquery instead of the correlation.

SELECT timestamp, value, card
FROM my_table
WHERE timestamp = (
  SELECT MAX(timestamp)
  FROM my_table
);

But without an index, two passes on the data will be necessary whereas the previous query can find the solution with only one scan. That said, we should not take performances into consideration when designing queries unless necessary, as we can expect optimizers to improve over time. However this particular kind of query is quite used.

Show off way: Windowing functions

I don't recommend doing this, but maybe you can make a good impression on your boss or something ;-)

SELECT DISTINCT
  first_value(timestamp) OVER w,
  first_value(value) OVER w,
  first_value(card) OVER w
FROM my_table
WINDOW w AS (ORDER BY timestamp DESC);

Actually this has the virtue of showing that a simple query can be expressed in a wide variety of ways (there are several others I can think of), and that picking one or the other form should be done according to several criteria such as:

  • portability (Relational/Instructive ways)
  • efficiency (Relational way)
  • expressiveness (Easy/Instructive way)

Execute command without keeping it in history

If you are using zsh you can run:

setopt histignorespace

After this is set, each command starting with a space will be excluded from history.

You can use aliases in .zshrc to turn this on/off:

# Toggle ignore-space. Useful when entering passwords.
alias history-ignore-space-on='\
setopt hist_ignore_space;\
echo "Commands starting with space are now EXCLUDED from history."'

alias history-ignore-space-off='\
unsetopt hist_ignore_space;\
echo "Commands starting with space are now ADDED to history."'

What's the difference between a web site and a web application?

Web applications are dynamic websites.

According to wikipedia, website is the abstract term of this paradigm.

A website, also written as web site, or simply site, is a set of related web pages typically served from a single web domain. A website is hosted on at least one web server, accessible via a network such as the Internet or a private local area network through an Internet address known as a uniform resource locator (URL). All publicly accessible websites collectively constitute the World Wide Web. (Source: http://en.wikipedia.org/wiki/Website)

Therefore, the Web Application is a type of website regardless of its purpose, in fact, a dynamic website, but the website is not indeed a web application.

In my point of view, all modern websites are web applications, including CMS's. Does anyone in the world still writes manual static html files, I don't think so. Even though, some websites have few static pages, but if they were created dynamically via a CMS, then it is definitely a CMS web application.

Read more:

  1. http://en.wikipedia.org/wiki/Web_application
  2. http://en.wikipedia.org/wiki/Website

jQuery - Detect value change on hidden input field

Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.

(Sometimes hidden input value changes are done by some other scripts you can't modify)

This does not work in IE10 and below

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var trackChange = function(element) {
  var observer = new MutationObserver(function(mutations, observer) {
    if(mutations[0].attributeName == "value") {
        $(element).trigger("change");
    }
  });
  observer.observe(element, {
    attributes: true
  });
}

// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

To be consistent with what is probably the most likely source of generating a time span (computing the difference of 2 times or date-times), you may want to store a .NET TimeSpan as a SQL Server DateTime Type.

This is because in SQL Server, the difference of 2 DateTime's (Cast to Float's and then Cast back to a DateTime) is simply a DateTime relative to Jan. 1, 1900. Ex. A difference of +0.1 second would be January 1, 1900 00:00:00.100 and -0.1 second would be Dec. 31, 1899 23:59:59.900.

To convert a .NET TimeSpan to a SQL Server DateTime Type, you would first convert it to a .NET DateTime Type by adding it to a DateTime of Jan. 1, 1900. Of course, when you read it into .NET from SQL Server, you would first read it into a .NET DateTime and then subtract Jan. 1, 1900 from it to convert it to a .NET TimeSpan.

For use cases where the time spans are being generated from SQL Server DateTime's and within SQL Server (i.e. via T-SQL) and SQL Server is prior to 2016, depending on your range and precision needs, it may not be practical to store them as milliseconds (not to mention Ticks) because the Int Type returned by DateDiff (vs. the BigInt from SS 2016+'s DateDiff_Big) overflows after ~24 days worth of milliseconds and ~67 yrs. of seconds. Whereas, this solution will handle time spans with precision down to 0.1 seconds and from -147 to +8,099 yrs..

WARNINGS:

  1. This would only work if the difference relative to Jan. 1, 1900 would result in a value within the range of a SQL Server DateTime Type (Jan. 1, 1753 to Dec. 31, 9999 aka -147 to +8,099 yrs.). We don't have to worry near as much on the .NET TimeSpan side, since it can hold ~29 k to +29 k yrs. I didn't mention the SQL Server DateTime2 Type (whose range, on the negative side, is much greater than SQL Server DateTime's), because: a) it cannot be converted to a numeric via a simple Cast and b) DateTime's range should suffice for the vast majority of use cases.

  2. SQL Server DateTime differences computed via the Cast - to - Float - and - back method does not appear to be accurate beyond 0.1 seconds.

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

I have some vague recollections of Oracle databases needing a bit of fiddling when you reboot for the first time after installing the database. However, you haven't given us enough information to work on. To start with:

  • What code are you using to connect to the database?
  • It's not clear whether the database instance has been started. Can you connect to the database using sqlplus / as sysdba from within the VM?
  • What has been written to the listener.log file (in %ORACLE_HOME%\network\log) since the last reboot?

EDIT: I've now been able to come up with a scenario which generates the same error message you got. It looks to me like the database you're attempting to connect to has not been started up. The example I present below uses Oracle XE on Linux, but I don't think this makes a significant difference.

First, let us confirm that the database is shut down:

$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:16:43 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

It's the text Connected to an idle instance that tells us that the database is shut down.

Using sqlplus / as sysdba connects us to the database as SYS without needing a password, but it only works on the same machine as the database itself. In your case, you'd need to run this inside the virtual machine. SYS has permission to start up and shut down the database, and to connect to it when it is shut down, but normal users don't have these permissions.

Now let us disconnect and try reconnecting as a normal user, one that does not have permission to startup/shutdown the database nor connect to it when it is down:

SQL> exit
Disconnected

$ sqlplus -L "user/pw@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE)))"

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:16:47 2010                                                                                                               

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

ERROR:
ORA-12505: TNS:listener does not currently know of SID given in connect
descriptor                                                             


SP2-0751: Unable to connect to Oracle.  Exiting SQL*Plus

That's the error message you've been getting.

Now, let's start the database up:

$ sqlplus / as sysdba

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:17:00 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Connected to an idle instance.

SQL> startup
ORACLE instance started.

Total System Global Area  805306368 bytes
Fixed Size                  1261444 bytes
Variable Size             209715324 bytes
Database Buffers          591396864 bytes
Redo Buffers                2932736 bytes
Database mounted.
Database opened.
SQL> exit
Disconnected from Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

Now that the database is up, let's attempt to log in as a normal user:

$ sqlplus -L "user/pw@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE)))"

SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 17 18:17:11 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.


Connected to:
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production

SQL> 

We're in.

I hadn't seen an ORA-12505 error before because I don't normally connect to an Oracle database by entering the entire connection string on the command line. This is likely to be similar to how you are attempting to connect to the database. Usually, I either connect to a local database, or connect to a remote database by using a TNS name (these are listed in the tnsnames.ora file, in %ORACLE_HOME%\network\admin). In both of these cases you get a different error message if you attempt to connect to a database that has been shut down.

If the above doesn't help you (in particular, if the database has already been started, or you get errors starting up the database), please let us know.

EDIT 2: it seems the problems you were having were indeed because the database hadn't been started. It also appears that your database isn't configured to start up when the service starts. It is possible to get the database to start up when the service is started, and to shut down when the service is stopped. To do this, use the Oracle Administration Assistant for Windows, see here.

How to apply !important using .css()?

The easiest and best solution for this problem from me was to simply use addClass() instead of .css() or .attr().

For example:

$('#elem').addClass('importantClass');

And in your CSS file:

.importantClass {
    width: 100px !important;
}

How can I remove the first line of a text file using bash/sed script?

Since it sounds like I can't speed up the deletion, I think a good approach might be to process the file in batches like this:

While file1 not empty
  file2 = head -n1000 file1
  process file2
  sed -i -e "1000d" file1
end

The drawback of this is that if the program gets killed in the middle (or if there's some bad sql in there - causing the "process" part to die or lock-up), there will be lines that are either skipped, or processed twice.

(file1 contains lines of sql code)

can not find module "@angular/material"

Change to,

import {MaterialModule} from '@angular/material';

DEMO

How to deal with floating point number precision in JavaScript?

Problem

Floating point can't store all decimal values exactly. So when using floating point formats there will always be rounding errors on the input values. The errors on the inputs of course results on errors on the output. In case of a discrete function or operator there can be big differences on the output around the point where the function or operator is discrete.

Input and output for floating point values

So, when using floating point variables, you should always be aware of this. And whatever output you want from a calculation with floating points should always be formatted/conditioned before displaying with this in mind.
When only continuous functions and operators are used, rounding to the desired precision often will do (don't truncate). Standard formatting features used to convert floats to string will usually do this for you.
Because the rounding adds an error which can cause the total error to be more then half of the desired precision, the output should be corrected based on expected precision of inputs and desired precision of output. You should

  • Round inputs to the expected precision or make sure no values can be entered with higher precision.
  • Add a small value to the outputs before rounding/formatting them which is smaller than or equal to 1/4 of the desired precision and bigger than the maximum expected error caused by rounding errors on input and during calculation. If that is not possible the combination of the precision of the used data type isn't enough to deliver the desired output precision for your calculation.

These 2 things are usually not done and in most cases the differences caused by not doing them are too small to be important for most users, but I already had a project where output wasn't accepted by the users without those corrections.

Discrete functions or operators (like modula)

When discrete operators or functions are involved, extra corrections might be required to make sure the output is as expected. Rounding and adding small corrections before rounding can't solve the problem.
A special check/correction on intermediate calculation results, immediately after applying the discrete function or operator might be required. For a specific case (modula operator), see my answer on question: Why does modulus operator return fractional number in javascript?

Better avoid having the problem

It is often more efficient to avoid these problems by using data types (integer or fixed point formats) for calculations like this which can store the expected input without rounding errors. An example of that is that you should never use floating point values for financial calculations.

Parsing JSON array with PHP foreach

$user->data is an array of objects. Each element in the array has a name and value property (as well as others).

Try putting the 2nd foreach inside the 1st.

foreach($user->data as $mydata)
{
    echo $mydata->name . "\n";
    foreach($mydata->values as $values)
    {
        echo $values->value . "\n";
    }
}

How to create roles in ASP.NET Core and assign them to users?

My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.

You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.

private async Task CreateRoles(IServiceProvider serviceProvider)
    {
        //initializing custom roles 
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        string[] roleNames = { "Admin", "Manager", "Member" };
        IdentityResult roleResult;

        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        //Here you could create a super user who will maintain the web app
        var poweruser = new ApplicationUser
        {

            UserName = Configuration["AppSettings:UserName"],
            Email = Configuration["AppSettings:UserEmail"],
        };
    //Ensure you have these values in your appsettings.json file
        string userPWD = Configuration["AppSettings:UserPassword"];
        var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);

       if(_user == null)
       {
            var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
            if (createPowerUser.Succeeded)
            {
                //here we tie the new user to the role
                await UserManager.AddToRoleAsync(poweruser, "Admin");

            }
       }
    }

and then you could call the CreateRoles(serviceProvider).Wait(); method from the Configure method in the Startup class. ensure you have IServiceProvider as a parameter in the Configure class.

Using role-based authorization in a controller to filter user access: Question 2

You can do this easily, like so.

[Authorize(Roles="Manager")]
public class ManageController : Controller
{
   //....
}

You can also use role-based authorization in the action method like so. Assign multiple roles, if you will

[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
 .....
 */ 
}

While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here

How to jquery alert confirm box "yes" & "no"

This plugin can help you,

craftpip/jquery-confirm

Its easy to setup and has great set of features.

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            $.alert('Confirmed!');
        },
        cancel: function () {
            $.alert('Canceled!');
        },
        somethingElse: {
            text: 'Something else',
            btnClass: 'btn-blue',
            keys: ['enter', 'shift'], // trigger when enter or shift is pressed
            action: function(){
                $.alert('Something else?');
            }
        }
    }
});

Other than this you can also load your content from a remote url.

$.confirm({
    content: 'url:hugedata.html' // location of your hugedata.html.
});

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

Why do Sublime Text 3 Themes not affect the sidebar?

You are looking for a Sublime UI Theme, which modifies Sublime's User Interface (e.g.: side bar). It's different from a Color Theme/Scheme, which modifies only the code part of Sublime's window. I tested a lot of UI Themes and the one I liked the most was Theme - Soda. You can install it using Sublime's Package Control. To enable it, go to Preferences >> Settings - User and add this line:

"theme": "Soda Dark 3.sublime-theme",

Here is a printscreen of my Sublime Text 3 with Soda Dark UI Theme and Twilight default Color Scheme:

enter image description here

Removing array item by value

The most powerful solution would be using array_filter, which allows you to define your own filtering function.

But some might say it's a bit overkill, in your situation...
A simple foreach loop to go trough the array and remove the item you don't want should be enough.

Something like this, in your case, should probably do the trick :

foreach ($items as $key => $value) {
    if ($value == $id) {
        unset($items[$key]);
        // If you know you only have one line to remove, you can decomment the next line, to stop looping
        //break;
    }
}

This project references NuGet package(s) that are missing on this computer

Is it possible that the packages have been restored to the wrong folder? Check that the paths in the csproj files are correct.

If they are different it could be caused by the packages now being restored to a different location. This could be caused by a NuGet.Config file being checked in specifying a node like this:

<add key="repositoryPath" value="..\..\Packages" />

The packages are being restored, by the projects are still looking at the old location.

How can I force a long string without any blank to be wrapped?

If you're using PHP then the wordwrap function works well for this: http://php.net/manual/en/function.wordwrap.php

The CSS solution word-wrap: break-word; does not seem to be consistent across all browsers.

Other server-side languages have similar functions - or can be hand built.

Here's how the the PHP wordwrap function works:

$string = "ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTCGATGTAGCTAGTAGCATGTAGTGA";

$wrappedstring = wordwrap($string,50,"&lt;br&gt;",true);

This wraps the string at 50 characters with a <br> tag. The 'true' parameter forces the string to be cut.

Search a string in a file and delete it from this file by Shell Script

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

How to get a variable type in Typescript?

I have checked a variable if it is a boolean or not as below

console.log(isBoolean(this.myVariable));

Similarly we have

isNumber(this.myVariable);
isString(this.myvariable);

and so on.

What is the difference between localStorage, sessionStorage, session and cookies?

OK, LocalStorage as it's called it's local storage for your browsers, it can save up to 10MB, SessionStorage does the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookies are very tiny data storing in your browser, that can save up 4KB and can be accessed through server or browser both...

I also created the image below to show the differences at a glance:

LocalStorage, SessionStorage and Cookies

How to load html string in a webview?

To load your data in WebView. Call loadData() method of WebView

wv.loadData(yourData, "text/html", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

[Edit 1]

You should add -- \ -- before -- " -- for example --> name=\"spanish press\"

below string worked for me

String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
 "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";

How do I prevent the padding property from changing width or height in CSS?

just change your div width to 160px if you have a padding of 20px it adds 40px extra to the width of your div so you need to subtract 40px from the width in order to keep your div looking normal and not distorted with extra width on it and your text all messed up.

Python - How to cut a string in Python?

You need to split the string:

>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s.split('&')
['http://www.domain.com/?s=some', 'two=20']

That will return a list as you can see so you can do:

>>> s2 = s.split('&')[0]
>>> print s2
http://www.domain.com/?s=some

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

how to convert image to byte array in java?

Here is a complete version of code for doing this. I have tested it. The BufferedImage and Base64 class do the trick mainly. Also some parameter needs to be set correctly.

public class SimpleConvertImage {
    public static void main(String[] args) throws IOException{
        String dirName="C:\\";
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
        BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
        ImageIO.write(img, "jpg", baos);
        baos.flush();

        String base64String=Base64.encode(baos.toByteArray());
        baos.close();

        byte[] bytearray = Base64.decode(base64String);

        BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
        ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
    }
}

Reference link

How to get cell value from DataGridView in VB.Net?

This helped me get close to what I needed and I will throw this out there for anyone else who needs it.

If you are looking for the value in the first cell in the selected column, you can try this. (I chose the first column, since you are asking for it to return "3", but you can change the number after Cells to get whichever column you need. Remember it is zero-based.)

This will copy the result to the clipboard: Clipboard.SetDataObject(Me.DataGridView1.CurrentRow.Cells(0).Value)

Node.js: How to read a stream into a buffer?

Overall I don't see anything that would break in your code.

Two suggestions:

The way you are combining Buffer objects is a suboptimal because it has to copy all the pre-existing data on every 'data' event. It would be better to put the chunks in an array and concat them all at the end.

var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
  var buf = Buffer.concat(bufs);
}

For performance, I would look into if the S3 library you are using supports streams. Ideally you wouldn't need to create one large buffer at all, and instead just pass the stdout stream directly to the S3 library.

As for the second part of your question, that isn't possible. When a function is called, it is allocated its own private context, and everything defined inside of that will only be accessible from other items defined inside that function.

Update

Dumping the file to the filesystem would probably mean less memory usage per request, but file IO can be pretty slow so it might not be worth it. I'd say that you shouldn't optimize too much until you can profile and stress-test this function. If the garbage collector is doing its job you may be overoptimizing.

With all that said, there are better ways anyway, so don't use files. Since all you want is the length, you can calculate that without needing to append all of the buffers together, so then you don't need to allocate a new Buffer at all.

var pause_stream = require('pause-stream');

// Your other code.

var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
  var contentLength = bufs.reduce(function(sum, buf){
    return sum + buf.length;
  }, 0);

  // Create a stream that will emit your chunks when resumed.
  var stream = pause_stream();
  stream.pause();
  while (bufs.length) stream.write(bufs.shift());
  stream.end();

  var headers = {
      'Content-Length': contentLength,
      // ...
  };

  s3.putStream(stream, ....);

Restricting JTextField input to Integers

You can also use JFormattedTextField, which is much simpler to use. Example:

public static void main(String[] args) {
    NumberFormat format = NumberFormat.getInstance();
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMinimum(0);
    formatter.setMaximum(Integer.MAX_VALUE);
    formatter.setAllowsInvalid(false);
    // If you want the value to be committed on each keystroke instead of focus lost
    formatter.setCommitsOnValidEdit(true);
    JFormattedTextField field = new JFormattedTextField(formatter);

    JOptionPane.showMessageDialog(null, field);

    // getValue() always returns something valid
    System.out.println(field.getValue());
}

Python and pip, list all versions of a package that's available?

My take is a combination of a couple of posted answers, with some modifications to make them easier to use from within a running python environment.

The idea is to provide a entirely new command (modeled after the install command) that gives you an instance of the package finder to use. The upside is that it works with, and uses, any indexes that pip supports and reads your local pip configuration files, so you get the correct results as you would with a normal pip install.

I've made an attempt at making it compatible with both pip v 9.x and 10.x.. but only tried it on 9.x

https://gist.github.com/kaos/68511bd013fcdebe766c981f50b473d4

#!/usr/bin/env python
# When you want a easy way to get at all (or the latest) version of a certain python package from a PyPi index.

import sys
import logging

try:
    from pip._internal import cmdoptions, main
    from pip._internal.commands import commands_dict
    from pip._internal.basecommand import RequirementCommand
except ImportError:
    from pip import cmdoptions, main
    from pip.commands import commands_dict
    from pip.basecommand import RequirementCommand

from pip._vendor.packaging.version import parse as parse_version

logger = logging.getLogger('pip')

class ListPkgVersionsCommand(RequirementCommand):
    """
    List all available versions for a given package from:

    - PyPI (and other indexes) using requirement specifiers.
    - VCS project urls.
    - Local project directories.
    - Local or remote source archives.

    """
    name = "list-pkg-versions"
    usage = """
      %prog [options] <requirement specifier> [package-index-options] ...
      %prog [options] [-e] <vcs project url> ...
      %prog [options] [-e] <local project path> ...
      %prog [options] <archive url/path> ..."""

    summary = 'List package versions.'

    def __init__(self, *args, **kw):
        super(ListPkgVersionsCommand, self).__init__(*args, **kw)

        cmd_opts = self.cmd_opts

        cmd_opts.add_option(cmdoptions.install_options())
        cmd_opts.add_option(cmdoptions.global_options())
        cmd_opts.add_option(cmdoptions.use_wheel())
        cmd_opts.add_option(cmdoptions.no_use_wheel())
        cmd_opts.add_option(cmdoptions.no_binary())
        cmd_opts.add_option(cmdoptions.only_binary())
        cmd_opts.add_option(cmdoptions.pre())
        cmd_opts.add_option(cmdoptions.require_hashes())

        index_opts = cmdoptions.make_option_group(
            cmdoptions.index_group,
            self.parser,
        )

        self.parser.insert_option_group(0, index_opts)
        self.parser.insert_option_group(0, cmd_opts)

    def run(self, options, args):
        cmdoptions.resolve_wheel_no_use_binary(options)
        cmdoptions.check_install_build_global(options)

        with self._build_session(options) as session:
            finder = self._build_package_finder(options, session)

            # do what you please with the finder object here... ;)
            for pkg in args:
                logger.info(
                    '%s: %s', pkg,
                    ', '.join(
                        sorted(
                            set(str(c.version) for c in finder.find_all_candidates(pkg)),
                            key=parse_version,
                        )
                    )
                )


commands_dict[ListPkgVersionsCommand.name] = ListPkgVersionsCommand

if __name__ == '__main__':
    sys.exit(main())

Example output

./list-pkg-versions.py list-pkg-versions pika django
pika: 0.5, 0.5.1, 0.5.2, 0.9.1a0, 0.9.2a0, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 0.9.10, 0.9.11, 0.9.12, 0.9.13, 0.9.14, 0.10.0b1, 0.10.0b2, 0.10.0, 0.11.0b1, 0.11.0, 0.11.1, 0.11.2, 0.12.0b2
django: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4

Vim clear last search highlighting

If you have incsearch.vim plugin installed, then there is a setting to automatically clear highlight after searching:

let g:incsearch#auto_nohlsearch = 1

enter image description here

Why am I getting error for apple-touch-icon-precomposed.png

If a user from Safari Web browser (Apple devices) visit your site. The browser tries to fetch the site icon if it is not defined in <head> in the following order:

  1. apple-touch-icon-57x57-precomposed.png
  2. apple-touch-icon-57x57.png
  3. apple-touch-icon-precomposed.png
  4. apple-touch-icon.png

To resolve this issue either define an icon for safari web browsers or apple devices. Add something like this to head section of your site:

<link rel="apple-touch-icon" href="/custom_icon.png"/>

If you want to keep <head> clean then upload the icon to root dir of your site with proper name.

The default icon size is 57px.

You can find more details on iOS developer library.

mongoError: Topology was destroyed

I solved this issue by:

  1. ensuring mongo is running
  2. restarting my server

Android: adb: Permission Denied

Do adb remount. And then try adb shell

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Dynamic constant assignment

Constants in ruby cannot be defined inside methods. See the notes at the bottom of this page, for example

Using strtok with a std::string

Assuming that by "string" you're talking about std::string in C++, you might have a look at the Tokenizer package in Boost.

How to place a file on classpath in Eclipse?

Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.

How to use OAuth2RestTemplate?

I have different approach if you want access token and make call to other resource system with access token in header

Spring Security comes with automatic security: oauth2 properties access from application.yml file for every request and every request has SESSIONID which it reads and pull user info via Principal, so you need to make sure inject Principal in OAuthUser and get accessToken and make call to resource server

This is your application.yml, change according to your auth server:

security:
  oauth2:
    client:
      clientId: 233668646673605
      clientSecret: 33b17e044ee6a4fa383f46ec6e28ea1d
      accessTokenUri: https://graph.facebook.com/oauth/access_token
      userAuthorizationUri: https://www.facebook.com/dialog/oauth
      tokenName: oauth_token
      authenticationScheme: query
      clientAuthenticationScheme: form
    resource:
      userInfoUri: https://graph.facebook.com/me

@Component
public class OAuthUser implements Serializable {

private static final long serialVersionUID = 1L;

private String authority;

@JsonIgnore
private String clientId;

@JsonIgnore
private String grantType;
private boolean isAuthenticated;
private Map<String, Object> userDetail = new LinkedHashMap<String, Object>();

@JsonIgnore
private String sessionId;

@JsonIgnore
private String tokenType;

@JsonIgnore
private String accessToken;

@JsonIgnore
private Principal principal;

public void setOAuthUser(Principal principal) {
    this.principal = principal;
    init();
}

public Principal getPrincipal() {
    return principal;
}

private void init() {
    if (principal != null) {
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
        if (oAuth2Authentication != null) {
            for (GrantedAuthority ga : oAuth2Authentication.getAuthorities()) {
                setAuthority(ga.getAuthority());
            }
            setClientId(oAuth2Authentication.getOAuth2Request().getClientId());
            setGrantType(oAuth2Authentication.getOAuth2Request().getGrantType());
            setAuthenticated(oAuth2Authentication.getUserAuthentication().isAuthenticated());

            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) oAuth2Authentication
                    .getDetails();
            if (oAuth2AuthenticationDetails != null) {
                setSessionId(oAuth2AuthenticationDetails.getSessionId());
                setTokenType(oAuth2AuthenticationDetails.getTokenType());

            // This is what you will be looking for 
                setAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            }

    // This detail is more related to Logged-in User
            UsernamePasswordAuthenticationToken userAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
            if (userAuthenticationToken != null) {
                LinkedHashMap<String, Object> detailMap = (LinkedHashMap<String, Object>) userAuthenticationToken.getDetails();
                if (detailMap != null) {
                    for (Map.Entry<String, Object> mapEntry : detailMap.entrySet()) {
                        //System.out.println("#### detail Key = " + mapEntry.getKey());
                        //System.out.println("#### detail Value = " + mapEntry.getValue());
                        getUserDetail().put(mapEntry.getKey(), mapEntry.getValue());
                    }

                }

            }

        }

    }
}


public String getAuthority() {
    return authority;
}

public void setAuthority(String authority) {
    this.authority = authority;
}

public String getClientId() {
    return clientId;
}

public void setClientId(String clientId) {
    this.clientId = clientId;
}

public String getGrantType() {
    return grantType;
}

public void setGrantType(String grantType) {
    this.grantType = grantType;
}

public boolean isAuthenticated() {
    return isAuthenticated;
}

public void setAuthenticated(boolean isAuthenticated) {
    this.isAuthenticated = isAuthenticated;
}

public Map<String, Object> getUserDetail() {
    return userDetail;
}

public void setUserDetail(Map<String, Object> userDetail) {
    this.userDetail = userDetail;
}

public String getSessionId() {
    return sessionId;
}

public void setSessionId(String sessionId) {
    this.sessionId = sessionId;
}

public String getTokenType() {
    return tokenType;
}

public void setTokenType(String tokenType) {
    this.tokenType = tokenType;
}

public String getAccessToken() {
    return accessToken;
}

public void setAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

@Override
public String toString() {
    return "OAuthUser [clientId=" + clientId + ", grantType=" + grantType + ", isAuthenticated=" + isAuthenticated
            + ", userDetail=" + userDetail + ", sessionId=" + sessionId + ", tokenType="
            + tokenType + ", accessToken= " + accessToken + " ]";
}

@RestController
public class YourController {

@Autowired
OAuthUser oAuthUser;

// In case if you want to see Profile of user then you this 
@RequestMapping(value = "/profile", produces = MediaType.APPLICATION_JSON_VALUE)
public OAuthUser user(Principal principal) {
    oAuthUser.setOAuthUser(principal);

    // System.out.println("#### Inside user() - oAuthUser.toString() = " + oAuthUser.toString());

    return oAuthUser;
}


@RequestMapping(value = "/createOrder",
        method = RequestMethod.POST,
        headers = {"Content-type=application/json"},
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public FinalOrderDetail createOrder(@RequestBody CreateOrder createOrder) {

    return postCreateOrder_restTemplate(createOrder, oAuthUser).getBody();
}


private ResponseEntity<String> postCreateOrder_restTemplate(CreateOrder createOrder, OAuthUser oAuthUser) {

String url_POST = "your post url goes here";

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", String.format("%s %s", oAuthUser.getTokenType(), oAuthUser.getAccessToken()));
    headers.add("Content-Type", "application/json");

    RestTemplate restTemplate = new RestTemplate();
    //restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpEntity<String> request = new HttpEntity<String>(createOrder, headers);

    ResponseEntity<String> result = restTemplate.exchange(url_POST, HttpMethod.POST, request, String.class);
    System.out.println("#### post response = " + result);

    return result;
}


}

Setting the Textbox read only property to true using JavaScript

document.getElementById('textbox-id').readOnly=true should work

'any' vs 'Object'

Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.

Spring MVC + JSON = 406 Not Acceptable

You have to register the annotation binding for Jackson in your spring-mvc-config.xml, for example :

<!-- activates annotation driven binding -->
<mvc:annotation-driven ignoreDefaultModelOnRedirect="true" validator="validator">
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

Then in your controller you can use :

@RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")
@ResponseBody

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

How to call base.base.method()?

There seems to be a lot of these questions surrounding inheriting a member method from a Grandparent Class, overriding it in a second Class, then calling its method again from a Grandchild Class. Why not just inherit the grandparent's members down to the grandchildren?

class A
{
    private string mystring = "A";    
    public string Method1()
    {
        return mystring;
    }
}

class B : A
{
    // this inherits Method1() naturally
}

class C : B
{
    // this inherits Method1() naturally
}


string newstring = "";
A a = new A();
B b = new B();
C c = new C();
newstring = a.Method1();// returns "A"
newstring = b.Method1();// returns "A"
newstring = c.Method1();// returns "A"

Seems simple....the grandchild inherits the grandparents method here. Think about it.....that's how "Object" and its members like ToString() are inherited down to all classes in C#. I'm thinking Microsoft has not done a good job of explaining basic inheritance. There is too much focus on polymorphism and implementation. When I dig through their documentation there are no examples of this very basic idea. :(

Generate a random double in a range

import java.util.Random;

public class MyClass {
     public static void main(String args[]) {
          Double min = 0.0;  // Set To Your Desired Min Value
          Double max = 10.0; // Set To Your Desired Max Value
          double x = (Math.random() * ((max - min) + 1)) + min;   // This Will Create A Random Number Inbetween Your Min And Max.
          double xrounded = Math.round(x * 100.0) / 100.0;   // Creates Answer To The Nearest 100 th, You Can Modify This To Change How It Rounds.
          System.out.println(xrounded);    // This Will Now Print Out The Rounded, Random Number.
     }
}

Android: No Activity found to handle Intent error? How it will resolve

if (intent.resolveActivity(getPackageManager()) == null) {
    Utils.showToast(activity, no_app_available_to_complete_this_task);
} else {
    startActivityForResult(intent, 1);
}

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

Exception : AAPT2 error: check logs for details

I faced similar problem. Akilesh awasthi's answer helped me fix it. My problem was a little different. I was using places_ic_search icon from com.google.android.gms:play-services-location The latest version com.google.android.gms:play-services-location:15.0.0 does not provide the icon places_ic_search. Because of this there was a problem in the layout.xml files.That led to build failure AAPT2 error: check logs for details as the message. Android studio should be showing cannot find drawable places_ic_search as the message instead.

I ended up using a lower version of com.google.android.gms:play-services-location temporarily. Hope this helps someone in future.

Add a scrollbar to a <textarea>

like this

css

textarea {

overflow:scroll;
height:100px;
}

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = new Guid.NewGuid()
});

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

Javascript String to int conversion

Convert by Number Class:-

Eg:

var n = Number("103");
console.log(n+1)

Output: 104

Note:- Number is class. When we pass string, then constructor of Number class will convert it.

How to sort mongodb with pymongo

This also works:

db.Account.find().sort('UserName', -1)
db.Account.find().sort('UserName', 1)

I'm using this in my code, please comment if i'm doing something wrong here, thanks.

AngularJS: ng-model not binding to ng-checked for checkboxes

The ng-model and ng-checked directives should not be used together

From the Docs:

ngChecked

Sets the checked attribute on the element, if the expression inside ngChecked is truthy.

Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.

AngularJS ng-checked Directive API Reference


Instead set the desired initial value from the controller:

<input type="checkbox" name="test" ng-model="testModel['item1']" ?n?g?-?c?h?e?c?k?e?d?=?"?t?r?u?e?"? />
    Testing<br />
<input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2<br />
<input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3<br />
<input type="button" ng-click="submit()" value="Submit" />
$scope.testModel = { item1: true };

Vertical Align text in a Label

Use css on your label.

For example:

label {line-height:1em; margin:2px 5px 3px 5px; padding:2px 5px 3px 5px;}

Notice that the line-height will adjust the height of the line itself, whereas margin will dictate how far out other elements will be outside the lable and padding will dictate any inner space from the outside edge of the label. The margin and padding work like this (clockwise: Top Right Bottom Left), so 2px 5px 3px 5px is:

2px Top 5px Right 3px Bottom 5px Left

How to add new line in Markdown presentation?

See the original markdown specification (bold mine):

The implication of the “one or more consecutive lines of text” rule is that Markdown supports “hard-wrapped” text paragraphs. This differs significantly from most other text-to-HTML formatters (including Movable Type’s “Convert Line Breaks” option) which translate every line break character in a paragraph into a <br /> tag.

When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return.

IIS7 folder permissions for web application

In IIS 7 (not IIS 7.5), sites access files and folders based on the account set on the application pool for the site. By default, in IIS7, this account is NETWORK SERVICE.

Specify an Identity for an Application Pool (IIS 7)

In IIS 7.5 (Windows 2008 R2 and Windows 7), the application pools run under the ApplicationPoolIdentity which is created when the application pool starts. If you want to set ACLS for this account, you need to choose IIS AppPool\ApplicationPoolName instead of NT Authority\Network Service.

How to count the number of occurrences of an element in a List

A slightly more efficient approach might be

Map<String, AtomicInteger> instances = new HashMap<String, AtomicInteger>();

void add(String name) {
     AtomicInteger value = instances.get(name);
     if (value == null) 
        instances.put(name, new AtomicInteger(1));
     else
        value.incrementAndGet();
}

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How to get jQuery dropdown value onchange event

If you have simple dropdown like:

<select name="status" id="status">
    <option value="1">Active</option>
    <option value="0">Inactive</option>
</select>

Then you can use this code for getting value:

$(function(){

 $("#status").change(function(){
     var status = this.value;
     alert(status);
   if(status=="1")
     $("#icon_class, #background_class").hide();// hide multiple sections
  });

});

How to sort by column in descending order in Spark SQL?

In the case of Java:

If we use DataFrames, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:

Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");

where e_id is the column on which join is applied while sorted by salary in ASC.

Also, we can use Spark SQL as:

SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();

where

  • spark  -> SparkSession
  • salary -> GlobalTemp View.

How can I set a custom date time format in Oracle SQL Developer?

SQL Developer Version 4.1.0.19

Step 1: Go to Tools -> Preferences

Step 2: Select Database -> NLS

Step 3: Go to Date Format and Enter DD-MON-RR HH24: MI: SS

Step 4: Click OK.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How to do a scatter plot with empty circles in Python?

Here's another way: this adds a circle to the current axes, plot or image or whatever :

from matplotlib.patches import Circle  # $matplotlib/patches.py

def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
    """ add a circle to ax= or current axes
    """
        # from .../pylab_examples/ellipse_demo.py
    e = Circle( xy=xy, radius=radius )
    if ax is None:
        ax = pl.gca()  # ax = subplot( 1,1,1 )
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_edgecolor( color )
    e.set_facecolor( facecolor )  # "none" not None
    e.set_alpha( alpha )

alt text

(The circles in the picture get squashed to ellipses because imshow aspect="auto" ).

How can I pass POST parameters in a URL?

Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

Shuffle an array with python, randomize array item order with python

Just in case you want a new array you can use sample:

import random
new_array = random.sample( array, len(array) )

How to delete Tkinter widgets from a window?

Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.

from tkinter import *

cnt = 0


def MsgClick(event):
    children = root.winfo_children()
    for child in children:
        # print("type of widget is : " + str(type(child)))
        if str(type(child)) == "<class 'tkinter.Message'>":
            # print("Here Message widget will destroy")
            child.destroy()
            return

def MsgMotion(event):
  print("Mouse position: (%s %s)" % (event.x, event.y))
  return


def ButtonClick(event):
    global cnt, msg
    cnt += 1
    msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
    msg.config(bg='lightgreen', font=('times', 24, 'italic'))
    msg.bind("<Button-1>", MsgClick)
    msg.bind("<Motion>", MsgMotion)
    msg.pack()
    #print(type(msg)) tkinter.Message


def ButtonDoubleClick(event):
    import sys; sys.exit()


root = Tk()

root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
    root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)

root.mainloop()

Hope it will help someone...

How to set JVM parameters for Junit Unit Tests?

According to this support question https://intellij-support.jetbrains.com/hc/en-us/community/posts/206165789-JUnit-default-heap-size-overridden-

the -Xmx argument for an IntelliJ junit test run will come from the maven-surefire-plugin, if it's set.

This pom.xml snippet

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <argLine>-Xmx1024m</argLine>
            </configuration>
        </plugin>

seems to pass the -Xmx1024 argument to the junit test run, with IntelliJ 2016.2.4.

How to embed an autoplaying YouTube video in an iframe?

2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip

rel=0&amp;autoplay 

Example Below: .

<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

Rules for C++ string literals escape character

I left something like this as a comment, but I feel it probably needs more visibility as none of the answers mention this method:

The method I now prefer for initializing a std::string with non-printing characters in general (and embedded null characters in particular) is to use the C++11 feature of initializer lists.

std::string const str({'\0', '6', '\a', 'H', '\t'});

I am not required to perform error-prone manual counting of the number of characters that I am using, so that if later on I want to insert a '\013' in the middle somewhere, I can and all of my code will still work. It also completely sidesteps any issues of using the wrong escape sequence by accident.

The only downside is all of those extra ' and , characters.

What’s the best way to check if a file exists in C++? (cross platform)

Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.

It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.

Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html

Loop in Jade (currently known as "Pug") template engine

Pug (renamed from 'Jade') is a templating engine for full stack web app development. It provides a neat and clean syntax for writing HTML and maintains strict whitespace indentation (like Python). It has been implemented with JavaScript APIs. The language mainly supports two iteration constructs: each and while. 'for' can be used instead 'each'. Kindly consult the language reference here:

https://pugjs.org/language/iteration.html

Here is one of my snippets: each/for iteration in pug_screenshot

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Check the level of collation that is mismatched (server, database,table,column,character).

If it is the server, these steps helped me once:

  1. Stop the server
  2. Find your sqlservr.exe tool
  3. Run this command:

    sqlservr -m -T4022 -T3659 -s"name_of_insance" -q "name_of_collation"

  4. Start your sql server:

    net start name_of_instance

  5. Check the collation of your server again.

Here is more info:

https://www.mssqltips.com/sqlservertip/3519/changing-sql-server-collation-after-installation/

How to fix Error: listen EADDRINUSE while using nodejs?

The error EADDRINUSE (Address already in use) reports that there is already another process on the local system occupying that address / port.

There is a npm package called find-process which helps finding (and closing) the occupying process.

Here is a little demo code:

const find = require('find-process')

const PORT = 80

find('port', PORT)
.then((list) => {
  console.log(`Port "${PORT}" is blocked. Killing blocking applications...`)
  const processIds = list.map((item) => item.pid)
  processIds.forEach((pid) => process.kill(pid, 10))
})

I prepared a small sample which can reproduce the EADDRINUSE error. If you launch the following program in two separate terminals, you will see that the first terminal will start a server (on port "3000") and the second terminal will close the already running server (because it blocks the execution of the second terminal, EADDRINUSE):

Minimal Working Example:

const find = require('find-process')
const http = require('http')

const PORT = 3000

// Handling exceptions
process.on('uncaughtException', (error) => {
  if (error.code === 'EADDRINUSE') {
    find('port', PORT)
      .then((list) => {
        const blockingApplication = list[0]
        if (blockingApplication) {
          console.log(`Port "${PORT}" is blocked by "${blockingApplication.name}".`)
          console.log('Shutting down blocking application...')
          process.kill(blockingApplication.pid)
          // TODO: Restart server
        }
      })
  }
})

// Starting server
const server = http.createServer((request, response) => {
  response.writeHead(200, {'Content-Type': 'text/plain'})
  response.write('Hello World!')
  response.end()
})

server.listen(PORT, () => console.log(`Server running on port "${PORT}"...`))

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

It is very late but preferably symbols should be used as key:

my_hash = {}
my_hash[:my_key] = 'value'

my_hash.has_key?("my_key")
 => false 
my_hash.has_key?("my_key".to_sym)
 => true 

my_hash2 = {}
my_hash2['my_key'] = 'value'

my_hash2.has_key?("my_key")
 => true 
my_hash2.has_key?("my_key".to_sym)
 => false 

But when creating hash if you pass string as key then it will search for the string in keys.

But when creating hash you pass symbol as key then has_key? will search the keys by using symbol.


If you are using Rails, you can use Hash#with_indifferent_access to avoid this; both hash[:my_key] and hash["my_key"] will point to the same record

How to get images in Bootstrap's card to be the same height/width?

Each of the images need to be the exact dimensions before you put them up otherwise bootstrap 4 will try to place them in a funky shape. Bootstrap also has something like Masonry on their documents that you can use if need be, you can see that here, http://v4-alpha.getbootstrap.com/components/card/#columns.

How to check if an element is in an array

An array that contains a property that equals to

yourArray.contains(where: {$0.propertyToCheck == value })

Returns boolean.

MySQL - Select the last inserted row easiest way

SELECT MAX(ID) from bugs WHERE user=Me

CURL Command Line URL Parameters

The application/x-www-form-urlencoded Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:

curl -X DELETE "http://localhost:5000/locations?id=3"

or

curl -X GET "http://localhost:5000/locations?id=3"

How to calculate mean, median, mode and range from a set of numbers

If you only care about unimodal distributions, consider sth. like this.

public static Optional<Integer> mode(Stream<Integer> stream) {
    Map<Integer, Long> frequencies = stream
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return frequencies.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
}

__FILE__ macro shows full path

Try

#pragma push_macro("__FILE__")
#define __FILE__ "foobar.c"

after the include statements in your source file and add

#pragma pop_macro("__FILE__")

at the end of your source file.

contenteditable change events

non jQuery quick and dirty answer:

function setChangeListener (div, listener) {

    div.addEventListener("blur", listener);
    div.addEventListener("keyup", listener);
    div.addEventListener("paste", listener);
    div.addEventListener("copy", listener);
    div.addEventListener("cut", listener);
    div.addEventListener("delete", listener);
    div.addEventListener("mouseup", listener);

}

var div = document.querySelector("someDiv");

setChangeListener(div, function(event){
    console.log(event);
});

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

Step1: Delete all instances of java from you machine

Step2: Delete all the environment variables related to java/jdk/jre

Step3: Check in programm files and program files(X86) folder, there should not be java folder.

Step4: Install java again.

Step5: Go to cmd and type "java -version" Result: it will display the java version which is installed in your machine.

Step6: now delete all the files which are in C:/User/AdminOrUserNameofYourMachine/.m2 folder

Step6: go to cmd and run "mvn -v" Result: It will display the Apache maven version installed on your machine

Step7: Now Rebuild your project.

This worked for me.

@Value annotation type casting to Integer from String

Since using the @Value("new Long("myconfig")") with cast could throw error on startup if the config is not found or if not in the same expected number format

We used the following approach and is working as expected with fail safe check.

@Configuration()
public class MyConfiguration {

   Long DEFAULT_MAX_IDLE_TIMEOUT = 5l;

   @Value("db.timeoutInString")
   private String timeout;

   public Long getTimout() {
        final Long timoutVal = StringUtil.parseLong(timeout);
        if (null == timoutVal) {
            return DEFAULT_MAX_IDLE_TIMEOUT;
        }
        return timoutVal;
    }
}
   

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

When should I use GC.SuppressFinalize()?

SupressFinalize tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:

Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleaned up in the finalizer.

SupressFinalize is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().

Extending the User model with custom fields in Django

It's too late, but my answer is for those who search for a solution with a recent version of Django.

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    extra_Field_1 = models.CharField(max_length=25, blank=True)
    extra_Field_2 = models.CharField(max_length=25, blank=True)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

you can use it in templates like this:

<h2>{{ user.get_full_name }}</h2>
<ul>
  <li>Username: {{ user.username }}</li>
  <li>Location: {{ user.profile.extra_Field_1 }}</li>
  <li>Birth Date: {{ user.profile.extra_Field_2 }}</li>
</ul>

and in views.py like this:

def update_profile(request, user_id):
    user = User.objects.get(pk=user_id)
    user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'
    user.save()

What is "android:allowBackup"?

Here is what backup in this sense really means:

Android's backup service allows you to copy your persistent application data to remote "cloud" storage, in order to provide a restore point for the application data and settings. If a user performs a factory reset or converts to a new Android-powered device, the system automatically restores your backup data when the application is re-installed. This way, your users don't need to reproduce their previous data or application settings.

~Taken from http://developer.android.com/guide/topics/data/backup.html

You can register for this backup service as a developer here: https://developer.android.com/google/backup/signup.html

The type of data that can be backed up are files, databases, sharedPreferences, cache, and lib. These are generally stored in your device's /data/data/[com.myapp] directory, which is read-protected and cannot be accessed unless you have root privileges.

UPDATE: You can see this flag listed on BackupManager's api doc: BackupManager

What is memoization and how can I use it in Python?

Solution that works with both positional and keyword arguments independently of order in which keyword args were passed (using inspect.getargspec):

import inspect
import functools

def memoize(fn):
    cache = fn.cache = {}
    @functools.wraps(fn)
    def memoizer(*args, **kwargs):
        kwargs.update(dict(zip(inspect.getargspec(fn).args, args)))
        key = tuple(kwargs.get(k, None) for k in inspect.getargspec(fn).args)
        if key not in cache:
            cache[key] = fn(**kwargs)
        return cache[key]
    return memoizer

Similar question: Identifying equivalent varargs function calls for memoization in Python

Skip rows during csv import pandas

I don't have reputation to comment yet, but I want to add to alko answer for further reference.

From the docs:

skiprows: A collection of numbers for rows in the file to skip. Can also be an integer to skip the first n rows

A hex viewer / editor plugin for Notepad++?

The hex editor plugin mentioned by ellak still works, but it seems that you need the TextFX Characters plugin as well.

I initially installed only the hex plugin and Notepad++ would no longer pop up; instead it started eating memory (killed it at 1.2 GB). I removed it again and for other reasons installed the TextFX plugin (based on Find multiple lines in Notepad++)

Out of curiosity I installed the hex plugin again and now it works.

Note that this is on a fresh install of Windows 7 64 bit.

C++/CLI Converting from System::String^ to std::string

// I used VS2012 to write below code-- convert_system_string to Standard_Sting

        #include "stdafx.h"
        #include <iostream>
        #include <string> 

        using namespace System;
        using namespace Runtime::InteropServices; 


        void MarshalString ( String^ s, std::string& outputstring )
        {  
           const char* kPtoC =  (const char*) (Marshal::StringToHGlobalAnsi(s)).ToPointer();                                                        
           outputstring = kPtoC;  
           Marshal::FreeHGlobal(IntPtr((void*)kPtoC));  
        }   

        int _tmain(int argc, _TCHAR* argv[])
        {
             std::string strNativeString;  
             String ^ strManagedString = "Temp";

             MarshalString(strManagedString, strNativeString);  
             std::cout << strNativeString << std::endl; 

             return 0;
        }

Is it a good practice to place C++ definitions in header files?

The day C++ coders agree on The Way, lambs will lie down with lions, Palestinians will embrace Israelis, and cats and dogs will be allowed to marry.

The separation between .h and .cpp files is mostly arbitrary at this point, a vestige of compiler optimizations long past. To my eye, declarations belong in the header and definitions belong in the implementation file. But, that's just habit, not religion.

How to filter by string in JSONPath?

Drop the quotes:

List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");

See also this Json Path Example page

Perform an action in every sub-directory using Bash

A version that avoids creating a sub-process:

for D in *; do
    if [ -d "${D}" ]; then
        echo "${D}"   # your processing here
    fi
done

Or, if your action is a single command, this is more concise:

for D in *; do [ -d "${D}" ] && my_command; done

Or an even more concise version (thanks @enzotib). Note that in this version each value of D will have a trailing slash:

for D in */; do my_command; done

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

In numpy, index and dimension numbering starts with 0. So axis 0 means the 1st dimension. Also in numpy a dimension can have length (size) 0. The simplest case is:

In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0

I also get it if x = np.zeros((0,5), int), a 2d array with 0 rows, and 5 columns.

So someplace in your code you are creating an array with a size 0 first axis.

When asking about errors, it is expected that you tell us where the error occurs.

Also when debugging problems like this, the first thing you should do is print the shape (and maybe the dtype) of the suspected variables.

Applied to pandas

Resolving the error:

  1. Use a try-except block
  2. Verify the size of the array is not 0
    • if x.size != 0:

StringBuilder vs String concatenation in toString() in Java

Using latest version of Java(1.8) the disassembly(javap -c) shows the optimization introduced by compiler. + as well sb.append() will generate very similar code. However, it will be worthwhile inspecting the behaviour if we are using + in a for loop.

Adding strings using + in a for loop

Java:

public String myCatPlus(String[] vals) {
    String result = "";
    for (String val : vals) {
        result = result + val;
    }
    return result;
}

ByteCode:(for loop excerpt)

12: iload         5
14: iload         4
16: if_icmpge     51
19: aload_3
20: iload         5
22: aaload
23: astore        6
25: new           #3                  // class java/lang/StringBuilder
28: dup
29: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
32: aload_2
33: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
36: aload         6
38: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
41: invokevirtual #6                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
44: astore_2
45: iinc          5, 1
48: goto          12

Adding strings using stringbuilder.append

Java:

public String myCatSb(String[] vals) {
    StringBuilder sb = new StringBuilder();
    for(String val : vals) {
        sb.append(val);
    }
    return sb.toString();
}

ByteCdoe:(for loop excerpt)

17: iload         5
19: iload         4
21: if_icmpge     43
24: aload_3
25: iload         5
27: aaload
28: astore        6
30: aload_2
31: aload         6
33: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
36: pop
37: iinc          5, 1
40: goto          17
43: aload_2

There is a bit of glaring difference though. In first case, where + was used, new StringBuilder is created for each for loop iteration and generated result is stored by doing a toString() call(29 through 41). So you are generating intermediate Strings that your really do not need while using + operator in for loop.

Twitter Bootstrap 3: How to center a block

You can use class .center-block in combination with style="width:400px;max-width:100%;" to preserve responsiveness.

Using .col-md-* class with .center-block will not work because of the float on .col-md-*.

Listing only directories in UNIX

You can use the tree command with its d switch to accomplish this.

% tree -d tstdir
tstdir
|-- d1
|   `-- d11
|       `-- d111
`-- d2
    `-- d21
        `-- d211

6 directories

see man tree for more info.

What is an alternative to execfile in Python 3?

If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

If you're using Python 3.1 or later, you should also take a look at importlib.

How to make child process die after parent exits?

I don't believe it's possible to guarantee that using only standard POSIX calls. Like real life, once a child is spawned, it has a life of its own.

It is possible for the parent process to catch most possible termination events, and attempt to kill the child process at that point, but there's always some that can't be caught.

For example, no process can catch a SIGKILL. When the kernel handles this signal it will kill the specified process with no notification to that process whatsoever.

To extend the analogy - the only other standard way of doing it is for the child to commit suicide when it finds that it no longer has a parent.

There is a Linux-only way of doing it with prctl(2) - see other answers.

How can I export tables to Excel from a webpage

And now there is a better way.

OpenXML SDK for JavaScript.

https://openxmlsdkjs.codeplex.com/

Check if number is decimal

$lat = '-25.3654';

if(preg_match('/./',$lat)) {
    echo "\nYes its a decimal value\n";
}
else{
    echo 'No its not a decimal value';
}

Remove spacing between table cells and rows

If you see table class it has border-spacing: 2px; You could override table class in your css and set its border-spacing: 0px!important in table; I did it like

table {
      border-collapse: separate;
      white-space: normal;
      line-height: normal;
      font-weight: normal;
      font-size: medium;
      font-style: normal;
      color: -internal-quirk-inherit;
      text-align: start;
      border-spacing: 0px!important;
      font-variant: normal;   }

It saved my day.Hope it would be of help. Thanks.

Check if a process is running or not on Windows with Python

You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.

import psutil    
"someProgram" in (p.name() for p in psutil.process_iter())

Facebook user url by id

Accepted answer didn't work for me, this does:

https://www.facebook.com/app_scoped_user_id/10152384781676191

Align DIV to bottom of the page

Right I think I know what you mean so lets see....

HTML:

<div id="con">
   <div id="content">Results will go here</div>
   <div id="footer">Footer will always be at the bottom</div>
</div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
div {
    outline: 1px solid;
}
#con {
   min-height:100%;
   position:relative;
}
#content {
   height: 1000px; /* Changed this height */
   padding-bottom:60px;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
}

This demo have the height of contentheight: 1000px; so you can see what it would look like scrolling down the bottom.

DEMO HERE

This demo has the height of content height: 100px; so you can see what it would look like with no scrolling.

DEMO HERE

So this will move the footer below the div content but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.

Updated fiddles so its easier to see with backgrounds.

Refresh Fragment at reload

You cannot reload the fragment while it is attached to an Activity, where you get "Fragment Already Added" exception.

So the fragment has to be first detached from its activity and then attached. All can be done using the fluent api in one line:

getFragmentManager().beginTransaction().detach(this).attach(this).commit();

Update: This is to incorporate the changes made to API 26 and above:

FragmentTransaction transaction = mActivity.getFragmentManager()
                        .beginTransaction();
                if (Build.VERSION.SDK_INT >= 26) {
                    transaction.setReorderingAllowed(false);
                }
                transaction.detach(this).attach
                        (this).commit();

For more description of the update please see https://stackoverflow.com/a/51327440/4514796

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

The error is triggered because the file you're linking to in your HTML file is the unbundled version of the file. To get the full bundled version you'll have to install it with npm:

npm install --save milsymbol

This downloads the full package to your node_modules folder.

You can then access the standalone minified JavaScript file at node_modules/milsymbol/dist/milsymbol.js

You can do this in any directory, and then just copy the below file to your /src directory.

Remove a string from the beginning of a string

function remove_prefix($text, $prefix) {
    if(0 === strpos($text, $prefix))
        $text = substr($text, strlen($prefix)).'';
    return $text;
}

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

There is a conflict between your build settings and the default build settings that Cocoapods wants. To see the Cocoapods build settings, view the .xcconfig file(s) in Pods/Target Support Files/Pods-${PROJECTNAME}/ in your project. For me this file contains:

GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/Commando"
OTHER_LDFLAGS = -ObjC -framework Foundation -framework QuartzCore -framework UIKit
PODS_ROOT = ${SRCROOT}/Pods

If you are happy with the Cocoapods settings, then go to Build Settings for your project, find the appropriate setting and hit the Delete key. This will use the setting from Cocoapods.

On the other hand, if you have a custom setting that you need to use, then add $(inherited) to that setting.

Rendering HTML elements to <canvas>

Take a look on MDN

It will render html element using creating SVG images.

For Example: There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.

Here is Javascript Code to add HTML element to canvas.

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
  '<foreignObject width="100%" height="100%">' +_x000D_
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
  '<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
  '</div>' +_x000D_
  '</foreignObject>' +_x000D_
  '</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
  type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
  ctx.drawImage(img, 0, 0);_x000D_
  DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
_x000D_
_x000D_

Can't ping a local VM from the host

try to drop the firewall on your laptop and see if there is difference. Maybe Your laptop is firewall blocking some broadcasts that prevents local network name resolution.

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

How does one target IE7 and IE8 with valid CSS?

Well you don't really have to worry about IE7 code not working in IE8 because IE8 has compatibility mode (it can render pages the same as IE7). But if you still want to target different versions of IE, a way that's been done for a while now is to either use conditional comments or begin your css rule with a * to target IE7 and below. Or you could pay attention to user agent on the servers and dish up a different CSS file based on that information.

Generating HTML email body in C#

You might want to have a look at some of the template frameworks that are available at the moment. Some of them are spin offs as a result of MVC but that isn't required. Spark is a good one.

How to _really_ programmatically change primary and accent color in Android Lollipop?

This is what you CAN do:

write a file in drawable folder, lets name it background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="?attr/colorPrimary"/>
</shape>

then set your Layout's (or what so ever the case is) android:background="@drawable/background"

on setting your theme this color would represent the same.

Encoding conversion in java

UTF-8 and UCS-2/UTF-16 can be distinguished reasonably easily via a byte order mark at the start of the file. If this exists then it's a pretty good bet that the file is in that encoding - but it's not a dead certainty. You may well also find that the file is in one of those encodings, but doesn't have a byte order mark.

I don't know much about ISO-8859-2, but I wouldn't be surprised if almost every file is a valid text file in that encoding. The best you'll be able to do is check it heuristically. Indeed, the Wikipedia page talking about it would suggest that only byte 0x7f is invalid.

There's no idea of reading a file "as it is" and yet getting text out - a file is a sequence of bytes, so you have to apply a character encoding in order to decode those bytes into characters.

Source by stackoverflow

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to Check whether Session is Expired or not in asp.net

Edit

You can use the IsNewSession property to check if the session was created on the request of the page

protected void Page_Load() 
{ 
   if (Context.Session != null) 
   { 
      if (Session.IsNewSession) 
      { 
         string cookieHeader = Request.Headers["Cookie"]; 
         if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) 
         { 
            Response.Redirect("sessionTimeout.htm"); 
         } 
      } 
   } 
}

pre

Store Userid in session variable when user logs into website and check on your master page or created base page form which other page gets inherits. Then in page load check that Userid is present and not if not then redirect to login page.

if(Session["Userid"]==null)
{
  //session expire redirect to login page 
}

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Change the position attribute to fixed instead of absolute.

Converting an int into a 4 byte char array (C)

Do you want to address the individual bytes of a 32-bit int? One possible method is a union:

union
{
    unsigned int integer;
    unsigned char byte[4];
} foo;

int main()
{
    foo.integer = 123456789;
    printf("%u %u %u %u\n", foo.byte[3], foo.byte[2], foo.byte[1], foo.byte[0]);
}

Note: corrected the printf to reflect unsigned values.

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

CentOS 64 bit bad ELF interpreter

Try

$ yum provides ld-linux.so.2
$ yum update
$ yum install glibc.i686 libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6

Hope this clears out.

Xcode 4: create IPA file instead of .xcarchive

I had the same problem... Had to recreate the project from scratch.

Note: my project was created in XCode 3.1 and was linking against a static library that was being built as a subproject (to a common destination). I changed this to build the source instead when I recreated the XCode project in XCode 4.

Now doing a Product/Archive/Share... gets the option of "iOS App Store Package (.ipa)" directly above "Application" (which is now greyed out) and "Archive" (which exports the .xcarchive).

Pretty-print a Map in Java

Have a look at the Guava library:

Joiner.MapJoiner mapJoiner = Joiner.on(",").withKeyValueSeparator("=");
System.out.println(mapJoiner.join(map));

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

By using Chrome or Opera

without any plugins, without writing any single XPath syntax character

  1. right click the required element, then "inspect"
  2. right click on highlighted element tag, choose Copy ? Copy XPath.

;)

Enter image description here

How should I do integer division in Perl?

You can cast ints in Perl:

int(5/1.5) = 3;

Confused about stdin, stdout and stderr?

Here is a lengthy article on stdin, stdout and stderr:

To summarize:

Streams Are Handled Like Files

Streams in Linux—like almost everything else—are treated as though they were files. You can read text from a file, and you can write text into a file. Both of these actions involve a stream of data. So the concept of handling a stream of data as a file isn’t that much of a stretch.

Each file associated with a process is allocated a unique number to identify it. This is known as the file descriptor. Whenever an action is required to be performed on a file, the file descriptor is used to identify the file.

These values are always used for stdin, stdout, and stderr:

0: stdin
1: stdout
2: stderr

Ironically I found this question on stack overflow and the article above because I was searching for information on abnormal / non-standard streams. So my search continues.

How to pass multiple parameters to a get method in ASP.NET Core

To parse the search parameters from the URL, you need to annotate the controller method parameters with [FromQuery], for example:

[Route("api/person")]
public class PersonController : Controller
{
    [HttpGet]
    public string GetById([FromQuery]int id)
    {

    }

    [HttpGet]
    public string GetByName([FromQuery]string firstName, [FromQuery]string lastName)
    {

    }

    [HttpGet]
    public string GetByNameAndAddress([FromQuery]string firstName, [FromQuery]string lastName, [FromQuery]string address)
    {

    }
}

C++ floating point to integer type conversions

Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

Android set height and width of Custom view programmatically

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

NameError: name 'reduce' is not defined in Python

Or if you use the six library

from six.moves import reduce

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

XSS will always be there even if you use $_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME'] OR $_SERVER['PHP_SELF']

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

javascript multiple OR conditions in IF statement

When it checks id!=2 it returns true and stops further checking

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Using Mockito to test abstract classes

Assuming your test classes are in the same package (under a different source root) as your classes under test you can simply create the mock:

YourClass yourObject = mock(YourClass.class);

and call the methods you want to test just as you would any other method.

You need to provide expectations for each method that is called with the expectation on any concrete methods calling the super method - not sure how you'd do that with Mockito, but I believe it's possible with EasyMock.

All this is doing is creating a concrete instance of YouClass and saving you the effort of providing empty implementations of each abstract method.

As an aside, I often find it useful to implement the abstract class in my test, where it serves as an example implementation that I test via its public interface, although this does depend on the functionality provided by the abstract class.

Is there 'byte' data type in C++?

No, but since C++11 there is [u]int8_t.