Programs & Examples On #Paradigms

A tag for questions relating to the world view underlying a particular software methodology or theory.

OOP vs Functional Programming vs Procedural

For GUI I'd say that the Object-Oriented Paradigma is very well suited. The Window is an Object, the Textboxes are Objects, and the Okay-Button is one too. On the other Hand stuff like String Processing can be done with much less overhead and therefore more straightforward with simple procedural paradigma.

I don't think it is a question of the language neither. You can write functional, procedural or object-oriented in almost any popular language, although it might be some additional effort in some.

What is the difference between procedural programming and functional programming?

Funtional Programming

num = 1 
def function_to_add_one(num):
    num += 1
    return num


function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)

#Final Output: 2

Procedural Programming

num = 1 
def procedure_to_add_one():
    global num
    num += 1
    return num


procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()

#Final Output: 6

function_to_add_one is a function

procedure_to_add_one is a procedure

Even if you run the function five times, every time it will return 2

If you run the procedure five times, at the end of fifth run it will give you 6.

DISCLAIMER: Obviously this is a hyper-simplified view of reality. This answer just gives a taste of "functions" as opposed to "procedures". Nothing more. Once you have tasted this superficial yet deeply penetrative intuition, start exploring the two paradigms, and you will start to see the difference quite clearly.

Helps my students, hope it helps you too.

What is the difference between declarative and imperative paradigm in programming?

From my understanding, both terms have roots in philosophy, there are declarative and imperative kinds of knowledge. Declarative knowledge are assertions of truth, statements of fact like math axioms. It tells you something. Imperative, or procedural knowledge, tells you step by step how to arrive at something. That's what the definition of an algorithm essentially is. If you would, compare a computer programming language with the English language. Declarative sentences state something. A boring example, but here's a declarative way of displaying whether two numbers are equal to each other, in Java:

public static void main(String[] args)
{
    System.out.print("4 = 4.");
}

Imperative sentences in English, on the other hand, give a command or make some sort of request. Imperative programming, then, is just a list of commands (do this, do that). Here's an imperative way of displaying whether two numbers are equal to each other or not while accepting user input, in Java:

private static Scanner input;    

public static void main(String[] args) 
{
    input = new Scanner(System.in);
    System.out.println();
    System.out.print("Enter an integer value for x: ");
    int x = input.nextInt();
    System.out.print("Enter an integer value for y: ");        
    int y = input.nextInt();

    System.out.println();
    System.out.printf("%d == %d? %s\n", x, y, x == y);
}

Essentially, declarative knowledge skips over certain elements to form a layer of abstraction over those elements. Declarative programming does the same.

Functional, Declarative, and Imperative Programming

imperative - expressions describe sequence of actions to perform (associative)

declarative - expressions are declarations that contribute to behavior of program (associative, commutative, idempotent, monotonic)

functional - expressions have value as only effect; semantics support equational reasoning

Functional programming vs Object Oriented programming

You don't necessarily have to choose between the two paradigms. You can write software with an OO architecture using many functional concepts. FP and OOP are orthogonal in nature.

Take for example C#. You could say it's mostly OOP, but there are many FP concepts and constructs. If you consider Linq, the most important constructs that permit Linq to exist are functional in nature: lambda expressions.

Another example, F#. You could say it's mostly FP, but there are many OOP concepts and constructs available. You can define classes, abstract classes, interfaces, deal with inheritance. You can even use mutability when it makes your code clearer or when it dramatically increases performance.

Many modern languages are multi-paradigm.

Recommended readings

As I'm in the same boat (OOP background, learning FP), I'd suggest you some readings I've really appreciated:

Which one is the best PDF-API for PHP?

I personally generate XSL:FO from PHP and use Apache FOP to convert it to PDF. Not a PHP-native solution, not very efficient either, but it works well even if you need to generate PDF with very complex layouts.

ASP.NET Core Identity - get current user

In .NET Core 2.0 the user already exists as part of the underlying inherited controller. Just use the User as you would normally or pass across to any repository code.

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "TENANT")]
[HttpGet("issue-type-selection"), Produces("application/json")]
public async Task<IActionResult> IssueTypeSelection()
{
    try
    {
        return new ObjectResult(await _item.IssueTypeSelection(User));
    }
    catch (ExceptionNotFound)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new
        {
            error = "invalid_grant",
            error_description = "Item Not Found"
        });
    }
}

This is where it inherits it from

#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\BhailDa\.nuget\packages\microsoft.aspnetcore.mvc.core\2.0.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll
#endregion

using System;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Net.Http.Headers;

namespace Microsoft.AspNetCore.Mvc
{
    //
    // Summary:
    //     A base class for an MVC controller without view support.
    [Controller]
    public abstract class ControllerBase
    {
        protected ControllerBase();

        //
        // Summary:
        //     Gets the System.Security.Claims.ClaimsPrincipal for user associated with the
        //     executing action.
        public ClaimsPrincipal User { get; }

How to serialize an object into a string

Take a look at the java.sql.PreparedStatement class, specifically the function

http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html#setBinaryStream(int,%20java.io.InputStream)

Then take a look at the java.sql.ResultSet class, specifically the function

http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html#getBinaryStream(int)

Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object's signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn't read any of the previously serialized information.

You might be better off writing clunky per property columns in a table and composing and decomposing the object in this manner instead, to avoid this issue with object versions and deserialization. Or writing the properties into a hashmap of some sort, like a java.util.Properties object, and then serializing the properties object which is extremely unlikely to change.

npm install gives error "can't find a package.json file"

I'm not sure what you're trying to do here:

npm install alone in your home directory shouldn't do much -- it's not the root of a node app, so there's nothing to install, since there's no package.json.

There are two possible solutions:

1) cd to a node app and run npm install there. OR

2) if you're trying to install something as a command to use in the shell (You don't have a node application), npm install -g packagename. -g flag tells it to install in global namespace.

rake assets:precompile RAILS_ENV=production not working as required

I had this problem today. I fixed it being being explict about my require

gem 'uglifier', '>= 1.0.3', require: 'uglifier'

I had mine still in the assets group.

Find a private field with Reflection?

I came across this while searching for this on google so I realise I'm bumping an old post. However the GetCustomAttributes requires two params.

typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.GetCustomAttributes(typeof(SomeAttribute), false).Length > 0);

The second parameter specifies whether or not you wish to search the inheritance hierarchy

Javascript : get <img> src and set as variable?

var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);

Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/

How to set the thumbnail image on HTML5 video?

1) add the below jquery:

$thumbnail.on('click', function(e){
 e.preventDefault();
 src = src+'&autoplay=1'; // src: the original URL for embedding 
 $videoContainer.empty().append( $iframe.clone().attr({'src': src}) ); // $iframe: the original iframe for embedding
 }
);

note: in the first src (shown) add the original youtube link.

2) edit the iframe tag as:

<iframe width="1280" height="720" src="https://www.youtube.com/embed/nfQHF87vY0s?autoplay=1" frameborder="0" allowfullscreen></iframe>

note: copy paste the youtube video id after the embed/ in the iframe src.

Wamp Server not goes to green color

Click wamp icon :

1- apache -> httpd.conf (A notepad file will be opened)

2- Find 80

3 -Replace with 81

Listen 12.34.56.78:81 Listen 0.0.0.0:81 Listen [::0]:81

4- Restart wamp services

!!Done

Gradle: How to Display Test Results in the Console in Real Time?

For those using Kotlin DSL, you can do:

tasks {
  named<Test>("test") {
    testLogging.showStandardStreams = true
  }
}

Passing 'this' to an onclick event

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

VBA Excel 2-Dimensional Arrays

You need ReDim:

m = 5
n = 8
Dim my_array()
ReDim my_array(1 To m, 1 To n)
For i = 1 To m
  For j = 1 To n
    my_array(i, j) = i * j
  Next
Next

For i = 1 To m
  For j = 1 To n
    Cells(i, j) = my_array(i, j)
  Next
Next

As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:

Dim r1 As Range
Dim r2 As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
totalRow = ws1.Range("A1").End(xlDown).Row
totalCol = ws1.Range("A1").End(xlToRight).Column

Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
r2.Value = r1.Value

How to get progress from XMLHttpRequest

If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).

Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).

There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).

Flutter - Wrap text on overflow, like insert ellipsis or fade

Using Ellipsis

Text(
  "This is a long text",
  overflow: TextOverflow.ellipsis,
),

enter image description here


Using Fade

Text(
  "This is a long text",
  overflow: TextOverflow.fade,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Using Clip

Text(
  "This is a long text",
  overflow: TextOverflow.clip,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Note:

If you are using Text inside a Row, you can put above Text inside Expanded like:

Expanded(
  child: AboveText(),
)

Network tools that simulate slow network connection

For Linux or OSX, you can use ipfw.

From Quora (http://www.quora.com/What-is-the-best-tool-to-simulate-a-slow-internet-connection-on-a-Mac)

Essentially using a firewall to throttle all network data:

Define a rule that uses a pipe to reroute all traffic from any source address to any destination address, execute the following command (as root, or using sudo):

$ ipfw add pipe 1 all from any to any

To configure this rule to limit bandwidth to 300Kbit/s and impose 200ms of latency each way:

$ ipfw pipe 1 config bw 300Kbit/s delay 200ms

To remove all rules and recover your original network connection:

$ ipfw flush

How to run a command as a specific user in an init script?

On RHEL systems, the /etc/rc.d/init.d/functions script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.

The specific function provided to help with this is daemon. If you are intending to use it to start a daemon-like program, a simple usage would be:

daemon --user=username command

If that is too heavy-handed for what you need, there is runuser (see man runuser for full info; some versions may need -u prior to the username):

/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"

How to find out what group a given user has?

This one shows the user's uid as well as all the groups (with their gids) they belong to

id userid

Regular Expression for password validation

Try this ( also corrected check for upper case and lower case, it had a bug since you grouped them as [a-zA-Z] it only looks for atleast one lower or upper. So separated them out ):

(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)^(.{8,15})$

Update: I found that the regex doesn't really work as expected and this is not how it is supposed to be written too!

Try something like this:

(?=^.{8,15}$)(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?!.*\s).*$

(Between 8 and 15 inclusive, contains atleast one digit, atleast one upper case and atleast one lower case and no whitespace.)

And I think this is easier to understand as well.

Daylight saving time and time zone best practices

For those struggling with this on .NET, see if using DateTimeOffset and/or TimeZoneInfo are worth your while.

If you want to use IANA/Olson time zones, or find the built in types are insufficient for your needs, check out Noda Time, which offers a much smarter date and time API for .NET.

How to write header row with csv.DictWriter?

A few options:

(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

(2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

dw.writer.writerow(dw.fieldnames)

(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

Writing data:

w.writerow([d[k] for k in fieldnames])

or

w.writerow([d.get(k, restval) for k in fieldnames])

Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

wrong_fields = [k for k in rowdict if k not in self.fieldnames]

============

>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python26\lib\csv.py", line 144, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\python26\lib\csv.py", line 141, in _dict_to_list
    return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>

How to Compare a long value is equal to Long value

On the one hand Long is an object, while on the other hand long is a primitive type. In order to compare them you could get the primitive type out of the Long type:

public static void main(String[] args) {
    long a = 1111;
    Long b = 1113;

    if ((b!=null)&&
        (a == b.longValue())) 
    {
        System.out.println("Equals");
    } 
    else 
    {
        System.out.println("not equals");
    }
}

javascript windows alert with redirect function

Use this if you also want to consider non-javascript users:

echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('Succesfully Updated')
           window.location.href='http://someplace.com';
       </SCRIPT>
       <NOSCRIPT>
           <a href='http://someplace.com'>Successfully Updated. Click here if you are not redirected.</a>
       </NOSCRIPT>");

Increase number of axis ticks

The upcoming version v3.3.0 of ggplot2 will have an option n.breaks to automatically generate breaks for scale_x_continuous and scale_y_continuous

    devtools::install_github("tidyverse/ggplot2")

    library(ggplot2)

    plt <- ggplot(mtcars, aes(x = mpg, y = disp)) +
      geom_point()

    plt + 
      scale_x_continuous(n.breaks = 5)

enter image description here

    plt + 
      scale_x_continuous(n.breaks = 10) +
      scale_y_continuous(n.breaks = 10)

enter image description here

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

force line break in html table cell

I think what you're trying to do is wrap loooooooooooooong words or URLs so they don't push the size of the table out. (I've just been trying to do the same thing!)

You can do this easily with a DIV by giving it the style word-wrap: break-word (and you may need to set its width, too).

div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you must either wrap the content in a DIV (or other block tag) or apply: table-layout: fixed. This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.

Sample code:

table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

Hope that helps somebody.

Formatting Numbers by padding with leading zeros in SQL Server

SELECT 
    cast(replace(str(EmployeeID,6),' ','0')as char(6)) 
FROM dbo.RequestItems
WHERE ID=0

How can I programmatically check whether a keyboard is present in iOS app?

drawnonward's code is very close, but collides with UIKit's namespace and could be made easier to use.

@interface KeyboardStateListener : NSObject {
    BOOL _isVisible;
}
+ (KeyboardStateListener *)sharedInstance;
@property (nonatomic, readonly, getter=isVisible) BOOL visible;
@end

static KeyboardStateListener *sharedInstance;

@implementation KeyboardStateListener

+ (KeyboardStateListener *)sharedInstance
{
    return sharedInstance;
}

+ (void)load
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    sharedInstance = [[self alloc] init];
    [pool release];
}

- (BOOL)isVisible
{
    return _isVisible;
}

- (void)didShow
{
    _isVisible = YES;
}

- (void)didHide
{
    _isVisible = NO;
}

- (id)init
{
    if ((self = [super init])) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(didShow) name:UIKeyboardDidShowNotification object:nil];
        [center addObserver:self selector:@selector(didHide) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

@end

Python Loop: List Index Out of Range

When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like

for i in range(0, len(a)-1): Do something

Your current code won't work yet for the do something part though ;)

Get width height of remote image from url

Get image size with jQuery
(depending on which formatting method is more suitable for your preferences):

function getMeta(url){
    $('<img/>',{
        src: url,
        on: {
            load: (e) => {
                console.log('image size:', $(e.target).width(), $(e.target).height());
            },
        }
    });
}

or

function getMeta(url){
    $('<img/>',{
        src: url,
    }).on({
        load: (e) => {
            console.log('image size:', $(e.target).width(), $(e.target).height());
        },
    });
}

Remove old Fragment from fragment manager

Probably you instance old fragment it is keeping a reference. See this interesting article Memory leaks in Android — identify, treat and avoid

If you use addToBackStack, this keeps a reference to instance fragment avoiding to Garbage Collector erase the instance. The instance remains in fragments list in fragment manager. You can see the list by

ArrayList<Fragment> fragmentList = fragmentManager.getFragments();

The next code is not the best solution (because don´t remove the old fragment instance in order to avoid memory leaks) but removes the old fragment from fragmentManger fragment list

int index = fragmentManager.getFragments().indexOf(oldFragment);
fragmentManager.getFragments().set(index, null);

You cannot remove the entry in the arrayList because apparenly FragmentManager works with index ArrayList to get fragment.

I usually use this code for working with fragmentManager

public void replaceFragment(Fragment fragment, Bundle bundle) {

    if (bundle != null)
        fragment.setArguments(bundle);

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment oldFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());

    //if oldFragment already exits in fragmentManager use it
    if (oldFragment != null) {
        fragment = oldFragment;
    }

    fragmentTransaction.replace(R.id.frame_content_main, fragment, fragment.getClass().getName());

    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

    fragmentTransaction.commit();
}

Changing ImageView source

myImgView.setImageResource(R.drawable.monkey);

is used for setting image in the current image view, but if want to delete this image then you can use this code like:

((ImageView) v.findViewById(R.id.ImageView1)).setImageResource(0);

now this will delete the image from your image view, because it has set the resources value to zero.

How to escape special characters of a string with single backslashes

re.escape doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.

When using the repl, try using print to see what is really in the string.

$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\\w\$arr=1")
'\\\\\\^stack\\\\\\.\\\\\\*\\/overflo\\\\w\\\\\\$arr\\=1'
>>> print re.escape("\^stack\.\*/overflo\\w\$arr=1")
\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1
>>>

Detecting EOF in C

as a starting point you could try replacing

while(!EOF)

with

while(!feof(stdin))

Delete item from array and shrink array

You can't resize the array, per se, but you can create a new array and efficiently copy the elements from the old array to the new array using some utility function like this:

public static int[] removeElement(int[] original, int element){
    int[] n = new int[original.length - 1];
    System.arraycopy(original, 0, n, 0, element );
    System.arraycopy(original, element+1, n, element, original.length - element-1);
    return n;
}

A better approach, however, would be to use an ArrayList (or similar List structure) to store your data and then use its methods to remove elements as needed.

ASP.NET DateTime Picker

There is an easy, out of the box implementation: the HTML 5 input type="date" and the other date-related input types.

Okay, you can't style the controls that much and it doesn't work on every browser, but still it can be a very good option in the long term if all modern browsers support it and don't want to include heavy libraries that don't always work that good on mobile devices.

Create a File object in memory from a string in Java

No; instances of class File represent a path in a filesystem. Therefore, you can use that function only with a file. But perhaps there is an overload that takes an InputStream instead?

Create a new line in Java's FileWriter

If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
        writer.write(jTextField1.getText());
        writer.write(jTextField2.getText());
        writer.newLine();
        writer.flush();
        writer.close();
} catch (IOException ex) {
    System.out.println("File could not be created");
}

Length of the String without using length() method

Even more slower one

public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
    lol++;
}
return (lol-1)
}

Or even slower,

public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
    lol += s.toCharArray().length;
}
return lol
}

The difference between the Runnable and Callable interfaces in Java

Callable interface declares call() method and you need to provide generics as type of Object call() should return -

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Runnable on the other hand is interface that declares run() method that is called when you create a Thread with the runnable and call start() on it. You can also directly call run() but that just executes the run() method is same thread.

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used 
     * to create a thread, starting the thread causes the object's 
     * <code>run</code> method to be called in that separately executing 
     * thread. 
     * <p>
     * The general contract of the method <code>run</code> is that it may 
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

To summarize few notable Difference are

  1. A Runnable object does not return a result whereas a Callable object returns a result.
  2. A Runnable object cannot throw a checked exception wheras a Callable object can throw an exception.
  3. The Runnable interface has been around since Java 1.0 whereas Callable was only introduced in Java 1.5.

Few similarities include

  1. Instances of the classes that implement Runnable or Callable interfaces are potentially executed by another thread.
  2. Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.
  3. Both are functional interfaces and can be used in Lambda expressions since Java8.

Methods in ExecutorService interface are

<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);

Delete directory with files in it?

What about this:

function recursiveDelete($dirPath, $deleteParent = true){
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
        $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
    }
    if($deleteParent) rmdir($dirPath);
}

How to nicely format floating numbers to string without unnecessary decimal 0's

I made a DoubleFormatter to efficiently convert a great numbers of double values to a nice/presentable string:

double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4, 6); // 4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
  • If the integer part of V has more than MaxInteger => display V in scientific format (1.2345E+30). Otherwise, display in normal format (124.45678).
  • the MaxDecimal decide numbers of decimal digits (trim with bankers' rounding)

Here the code:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * Convert a double to a beautiful String (US-local):
 *
 * double horribleNumber = 3598945.141658554548844;
 * DoubleFormatter df = new DoubleFormatter(4,6);
 * String beautyDisplay = df.format(horribleNumber);
 * String beautyLabel = df.formatHtml(horribleNumber);
 *
 * Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.
 * (avoid to create an object NumberFormat each call of format()).
 *
 * 3 instances of NumberFormat will be reused to format a value v:
 *
 * if v < EXP_DOWN, uses nfBelow
 * if EXP_DOWN <= v <= EXP_UP, uses nfNormal
 * if EXP_UP < v, uses nfAbove
 *
 * nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.
 *
 * @author: DUONG Phu-Hiep
 */
public class DoubleFormatter
{
    private static final double EXP_DOWN = 1.e-3;
    private double EXP_UP; // always = 10^maxInteger
    private int maxInteger_;
    private int maxFraction_;
    private NumberFormat nfBelow_;
    private NumberFormat nfNormal_;
    private NumberFormat nfAbove_;

    private enum NumberFormatKind {Below, Normal, Above}

    public DoubleFormatter(int maxInteger, int maxFraction){
        setPrecision(maxInteger, maxFraction);
    }

    public void setPrecision(int maxInteger, int maxFraction){
        Preconditions.checkArgument(maxFraction>=0);
        Preconditions.checkArgument(maxInteger>0 && maxInteger<17);

        if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {
            return;
        }

        maxFraction_ = maxFraction;
        maxInteger_ = maxInteger;
        EXP_UP =  Math.pow(10, maxInteger);
        nfBelow_ = createNumberFormat(NumberFormatKind.Below);
        nfNormal_ = createNumberFormat(NumberFormatKind.Normal);
        nfAbove_ = createNumberFormat(NumberFormatKind.Above);
    }

    private NumberFormat createNumberFormat(NumberFormatKind kind) {

        // If you do not use the Guava library, replace it with createSharp(precision);
        final String sharpByPrecision = Strings.repeat("#", maxFraction_);

        NumberFormat f = NumberFormat.getInstance(Locale.US);

        // Apply bankers' rounding:  this is the rounding mode that
        // statistically minimizes cumulative error when applied
        // repeatedly over a sequence of calculations
        f.setRoundingMode(RoundingMode.HALF_EVEN);

        if (f instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat) f;
            DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();

            // Set group separator to space instead of comma

            //dfs.setGroupingSeparator(' ');

            // Set Exponent symbol to minus 'e' instead of 'E'
            if (kind == NumberFormatKind.Above) {
                dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
            } else {
                dfs.setExponentSeparator("e");
            }

            df.setDecimalFormatSymbols(dfs);

            // Use exponent format if v is outside of [EXP_DOWN,EXP_UP]

            if (kind == NumberFormatKind.Normal) {
                if (maxFraction_ == 0) {
                    df.applyPattern("#,##0");
                } else {
                    df.applyPattern("#,##0."+sharpByPrecision);
                }
            } else {
                if (maxFraction_ == 0) {
                    df.applyPattern("0E0");
                } else {
                    df.applyPattern("0."+sharpByPrecision+"E0");
                }
            }
        }
        return f;
    }

    public String format(double v) {
        if (Double.isNaN(v)) {
            return "-";
        }
        if (v==0) {
            return "0";
        }
        final double absv = Math.abs(v);

        if (absv<EXP_DOWN) {
            return nfBelow_.format(v);
        }

        if (absv>EXP_UP) {
            return nfAbove_.format(v);
        }

        return nfNormal_.format(v);
    }

    /**
     * Format and higlight the important part (integer part & exponent part)
     */
    public String formatHtml(double v) {
        if (Double.isNaN(v)) {
            return "-";
        }
        return htmlize(format(v));
    }

    /**
     * This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should
     * not be used to format a great numbers of value
     *
     * We will never use this methode, it is here only to understanding the Algo principal:
     *
     * format v to string. precision_ is numbers of digits after decimal.
     * if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678
     * otherwise display scientist format with: 1.2345e+30
     *
     * pre-condition: precision >= 1
     */
    @Deprecated
    public String formatInefficient(double v) {

        // If you do not use Guava library, replace with createSharp(precision);
        final String sharpByPrecision = Strings.repeat("#", maxFraction_);

        final double absv = Math.abs(v);

        NumberFormat f = NumberFormat.getInstance(Locale.US);

        // Apply bankers' rounding:  this is the rounding mode that
        // statistically minimizes cumulative error when applied
        // repeatedly over a sequence of calculations
        f.setRoundingMode(RoundingMode.HALF_EVEN);

        if (f instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat) f;
            DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();

            // Set group separator to space instead of comma

            dfs.setGroupingSeparator(' ');

            // Set Exponent symbol to minus 'e' instead of 'E'

            if (absv>EXP_UP) {
                dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
            } else {
                dfs.setExponentSeparator("e");
            }
            df.setDecimalFormatSymbols(dfs);

            //use exponent format if v is out side of [EXP_DOWN,EXP_UP]

            if (absv<EXP_DOWN || absv>EXP_UP) {
                df.applyPattern("0."+sharpByPrecision+"E0");
            } else {
                df.applyPattern("#,##0."+sharpByPrecision);
            }
        }
        return f.format(v);
    }

    /**
     * Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"
     * It is a html format of a number which highlight the integer and exponent part
     */
    private static String htmlize(String s) {
        StringBuilder resu = new StringBuilder("<b>");
        int p1 = s.indexOf('.');

        if (p1>0) {
            resu.append(s.substring(0, p1));
            resu.append("</b>");
        } else {
            p1 = 0;
        }

        int p2 = s.lastIndexOf('e');
        if (p2>0) {
            resu.append(s.substring(p1, p2));
            resu.append("<b>");
            resu.append(s.substring(p2, s.length()));
            resu.append("</b>");
        } else {
            resu.append(s.substring(p1, s.length()));
            if (p1==0){
                resu.append("</b>");
            }
        }
        return resu.toString();
    }
}

Note: I used two functions from the Guava library. If you don't use Guava, code it yourself:

/**
 * Equivalent to Strings.repeat("#", n) of the Guava library:
 */
private static String createSharp(int n) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<n; i++) {
        sb.append('#');
    }
    return sb.toString();
}

Get hours difference between two dates in Moment Js

In my case, I wanted hours and minutes:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours(); //hours instead of asHours
var minutes = duration.minutes(); //minutes instead of asMinutes

For more info refer to the official docs.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

To answer your question, there is no "proper way" to do that. Now if it's just the warning that bothers you, the best way to avoid its proliferation is to wrap the Query.list() method into a DAO :

public class MyDAO {

    @SuppressWarnings("unchecked")
    public static <T> List<T> list(Query q){
        return q.list();
    }
}

This way you get to use the @SuppressWarnings("unchecked") only once.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

What is the string concatenation operator in Oracle?

DECLARE
     a      VARCHAR2(30);
     b      VARCHAR2(30);
     c      VARCHAR2(30);
 BEGIN
      a  := ' Abc '; 
      b  := ' def ';
      c  := a || b;
 DBMS_OUTPUT.PUT_LINE(c);  
   END;

output:: Abc def

Finding the mode of a list

For those looking for the minimum mode, e.g:case of bi-modal distribution, using numpy.

import numpy as np
mode = np.argmax(np.bincount(your_list))

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

Binding to static property

Look at my project CalcBinding, which provides to you writing complex expressions in Path property value, including static properties, source properties, Math and other. So, you can write this:

<TextBox Text="{c:Binding local:VersionManager.FilterString}"/>

Goodluck!

Android load from URL to Bitmap

Please try this following steps.

1) Create AsyncTask in class or adapter(if you want to change the list item image).

public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
        private final static String TAG = "AsyncTaskLoadImage";
        private ImageView imageView;

        public AsyncTaskLoadImage(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
                URL url = new URL(params[0]);
                bitmap = BitmapFactory.decodeStream((InputStream) url.getContent());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            try {
                int width, height;
                height = bitmap.getHeight();
                width = bitmap.getWidth();

                Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(bmpGrayscale);
                Paint paint = new Paint();
                ColorMatrix cm = new ColorMatrix();
                cm.setSaturation(0);
                ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
                paint.setColorFilter(f);
                c.drawBitmap(bitmap, 0, 0, paint);
                imageView.setImageBitmap(bmpGrayscale);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

2) Call the AsyncTask from your activity, fragment or adapter(inside onBindViewHolder).

2.a) For adapter:

    String src = current.getProductImage();
    new AsyncTaskLoadImage(holder.icon).execute(src);

2.b) For activity and fragment:

**Activity:**
  ImageView imagview= (ImageView) findViewById(R.Id.imageview);
  String src = (your image string);
  new AsyncTaskLoadImage(imagview).execute(src);

**Fragment:**
  ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
  String src = (your image string);
  new AsyncTaskLoadImage(imagview).execute(src);

3) Kindly run the app and check the image.

Happy coding....:)

How do I get class name in PHP?

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

X: X, X
Y: Y, X
Z: Z, X

Set Label Text with JQuery

You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');

Using app.config in .Net Core

To get started with dotnet core, SqlServer and EF core the below DBContextOptionsBuilder would sufice and you do not need to create App.config file. Do not forget to change the sever address and database name in the below code.

protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=TestDB;Trusted_Connection=True;");

To use the EF core SqlServer provider and compile the above code install the EF SqlServer package

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

After compilation before running the code do the following for the first time

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef migrations add InitialCreate
dotnet ef database update

To run the code

dotnet run

Write a number with two decimal places SQL Server

This is how the kids are doing it today:

DECLARE @test DECIMAL(18,6) = 123.456789
SELECT FORMAT(@test, '##.##')

123.46

Unable to show a Git tree in terminal

I would suggest anyone to write down the full command

git log --all --decorate --oneline --graph

rather than create an alias.

It's good to get the commands into your head, so you know it by heart i.e. do not depend on aliases when you change machines.

Linux command for extracting war file?

Or

jar xvf myproject.war

How to load Spring Application Context

Add this at the start of main

ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");

JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");

//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

How to get value by key from JObject?

You can also get the value of an item in the jObject like this:

JToken value;
if (json.TryGetValue(key, out value))
{
   DoSomething(value);
}

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

How do I put an already-running process under nohup?

Simple and easiest steps

  1. Ctrl + Z ----------> Suspends the process
  2. bg --------------> Resumes and runs background
  3. disown %1 -------------> required only if you need to detach from the terminal

SSH to Elastic Beanstalk instance

I came here looking for a way to add a key to an instance Beanstalk creates during provisioning (we're using Terraform). You can do the following in Terraform:

resource "aws_elastic_beanstalk_environment" "your-beanstalk" {
   ... 
   setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name      = "EC2KeyName"
      value     = "${aws_key_pair.your-ssh-key.key_name}"
   }
   ...
}

You can then use that key to SSH into the box.

Compiling php with curl, where is curl installed?

If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/

For architectures (i386 ... i686) use /usr/lib/

I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.

Thread pooling in C++11

You can use C++ Thread Pool Library, https://github.com/vit-vit/ctpl.

Then the code your wrote can be replaced with the following

#include <ctpl.h>  // or <ctpl_stl.h> if ou do not have Boost library

int main (int argc, char *argv[]) {
    ctpl::thread_pool p(2 /* two threads in the pool */);
    int arr[4] = {0};
    std::vector<std::future<void>> results(4);
    for (int i = 0; i < 8; ++i) { // for 8 iterations,
        for (int j = 0; j < 4; ++j) {
            results[j] = p.push([&arr, j](int){ arr[j] +=2; });
        }
        for (int j = 0; j < 4; ++j) {
            results[j].get();
        }
        arr[4] = std::min_element(arr, arr + 4);
    }
}

You will get the desired number of threads and will not create and delete them over and over again on the iterations.

Prevent browser caching of AJAX call result

Of course "cache-breaking" techniques will get the job done, but this would not happen in the first place if the server indicated to the client that the response should not be cached. In some cases it is beneficial to cache responses, some times not. Let the server decide the correct lifetime of the data. You may want to change it later. Much easier to do from the server than from many different places in your UI code.

Of course this doesn't help if you have no control over the server.

How can I convert JSON to CSV?

This code should work for you, assuming that your JSON data is in a file called data.json.

import json
import csv

with open("data.json") as file:
    data = json.load(file)

with open("data.csv", "w") as file:
    csv_file = csv.writer(file)
    for item in data:
        fields = list(item['fields'].values())
        csv_file.writerow([item['pk'], item['model']] + fields)

Javascript Print iframe contents only

an alternate option, which may or may not be suitable, but cleaner if it is:

If you always want to just print the iframe from the page, you can have a separate "@media print{}" stylesheet that hides everything besides the iframe. Then you can just print the page normally.

Effect of NOLOCK hint in SELECT statements

1) Yes, a select with NOLOCK will complete faster than a normal select.

2) Yes, a select with NOLOCK will allow other queries against the effected table to complete faster than a normal select.

Why would this be?

NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.

You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a NOLOCK read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.

You really have no way to know what the state of the data is.

If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then NOLOCK is a good way to boost performance for these queries and avoid having them negatively impact database performance.

Always use the NOLOCK hint with great caution and treat any data it returns suspiciously.

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

What is size_t in C?

size_t is an unsigned integer data type which can assign only 0 and greater than 0 integer values. It measure bytes of any object's size and returned by sizeof operator. const is the syntax representation of size_t, but without const you can run the programm.

const size_t number;

size_t regularly used for array indexing and loop counting. If the compiler is 32-bit it would work on unsigned int. If the compiler is 64-bit it would work on unsigned long long int also. There for maximum size of size_t depending on compiler type.

size_t already define on <stdio.h> header file, but It can also define by <stddef.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h> headers.

  • Example (with const)
#include <stdio.h>

int main()
{
    const size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800


  • Example (without const)
#include <stdio.h>

int main()
{
    size_t value = 200;
    size_t i;
    int arr[value];

    for (i = 0 ; i < value ; ++i)
    {
        arr[i] = i;
    }

    size_t size = sizeof(arr);
    printf("size = %zu\n", size);
}

Output -: size = 800

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

getOutputStream() has already been called for this response

Ok, you should be using a servlet not a JSP but if you really need to... add this directive at the top of your page:

<%@ page trimDirectiveWhitespaces="true" %>

Or in the jsp-config section your web.xml

<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <trim-directive-whitespaces>true</trim-directive-whitespaces>
  </jsp-property-group>
</jsp-config>

Also flush/close the OutputStream and return when done.

dataOutput.flush();
dataOutput.close();
return;

Failed to resolve version for org.apache.maven.archetypes

I had the same problem i solved it by only adding remote catalog in eclipse go to Window -> Preferences ->Maven ->Archetypes ->click on add remote Catalog then a window will open in that paste
http://repo.maven.apache.org/maven2/archetype-catalog.xml in that catalog file then hit ok restart eclipse now all working fine

How to achieve ripple animation using support library?

It's very simple ;-)

First you must create two drawable file one for old api version and another one for newest version, Of course! if you create the drawable file for newest api version android studio suggest you to create old one automatically. and finally set this drawable to your background view.

Sample drawable for new api version (res/drawable-v21/ripple.xml):

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
            <corners android:radius="@dimen/round_corner" />
        </shape>
    </item>
</ripple>

Sample drawable for old api version (res/drawable/ripple.xml)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/colorPrimary" />
    <corners android:radius="@dimen/round_corner" />
</shape>

For more info about ripple drawable just visit this: https://developer.android.com/reference/android/graphics/drawable/RippleDrawable.html

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

How do I get an animated gif to work in WPF?

Basically the same PictureBox solution above, but this time with the code-behind to use an Embedded Resource in your project:

In XAML:

<WindowsFormsHost x:Name="_loadingHost">
  <Forms:PictureBox x:Name="_loadingPictureBox"/>
</WindowsFormsHost>

In Code-Behind:

public partial class ProgressIcon
{
    public ProgressIcon()
    {
        InitializeComponent();
        var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("My.Namespace.ProgressIcon.gif");
        var image = System.Drawing.Image.FromStream(stream);
        Loaded += (s, e) => _loadingPictureBox.Image = image;
    }
}

Testing if a checkbox is checked with jQuery

$('input:checkbox:checked').val();        // get the value from a checked checkbox

JavaScript equivalent of PHP's in_array()

Add this code to you project and use the object-style inArray methods

if (!Array.prototype.inArray) {
    Array.prototype.inArray = function(element) {
        return this.indexOf(element) > -1;
    };
} 
//How it work
var array = ["one", "two", "three"];
//Return true
array.inArray("one");

Returning Month Name in SQL Server Query

Have you tried DATENAME(MONTH, S0.OrderDateTime) ?

Retrieve last 100 lines logs

You can use tail command as follows:

tail -100 <log file>   > newLogfile

Now last 100 lines will be present in newLogfile

EDIT:

More recent versions of tail as mentioned by twalberg use command:

tail -n 100 <log file>   > newLogfile

Stretch and scale a CSS image in the background - with CSS only

You can actually achieve the same effect as a background image with the img tag. You just have to set its z-index lower than everything else, set position:absolute and use a transparent background for every box in the foreground.

Difference between jQuery’s .hide() and setting CSS to display: none

Looking at the jQuery code, this is what happens:

hide: function( speed, easing, callback ) {
    if ( speed || speed === 0 ) {
        return this.animate( genFx("hide", 3), speed, easing, callback);

    } else {
        for ( var i = 0, j = this.length; i < j; i++ ) {
            var display = jQuery.css( this[i], "display" );

            if ( display !== "none" ) {
                jQuery.data( this[i], "olddisplay", display );
            }
        }

        // Set the display of the elements in a second loop
        // to avoid the constant reflow
        for ( i = 0; i < j; i++ ) {
            this[i].style.display = "none";
        }

        return this;
    }
},

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

I include definitions for computed columns

    select 'CREATE TABLE [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name  + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END, name
from    sysobjects so
cross apply
    (SELECT

case when comps.definition is not null then '  ['+column_name+'] AS ' + comps.definition 
else
        '  ['+column_name+'] ' + data_type + 
        case
        when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')
            then ''
        when data_type in ('float')
            then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'
        when data_type in ('datetime2', 'datetimeoffset', 'time')
            then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'
        when data_type in ('decimal', 'numeric')
            then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'
        when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1
            then '(max)'
        when character_maximum_length is not null
            then '(' + cast(character_maximum_length as varchar(11)) + ')'
        else ''
        end + ' ' +
        case when exists ( 
        select id from syscolumns
        where object_name(id)=so.name
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1 
        ) then
        'IDENTITY(' + 
        cast(ident_seed(so.name) as varchar) + ',' + 
        cast(ident_incr(so.name) as varchar) + ')'
        else ''
        end + ' ' +
         (case when information_schema.columns.IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + 
          case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END 
end + ', ' 

     from information_schema.columns 
     left join sys.computed_columns comps 
     on OBJECT_ID(information_schema.columns.TABLE_NAME)=comps.object_id and information_schema.columns.COLUMN_NAME=comps.name

     where table_name = so.name
     order by ordinal_position
    FOR XML PATH('')) o (list)
left join
    information_schema.table_constraints tc
on  tc.Table_name       = so.Name
AND tc.Constraint_Type  = 'PRIMARY KEY'
cross apply
    (select '[' + Column_Name + '], '
     FROM   information_schema.key_column_usage kcu
     WHERE  kcu.Constraint_Name = tc.Constraint_Name
     ORDER BY
        ORDINAL_POSITION
     FOR XML PATH('')) j (list)
where   xtype = 'U'
AND name    NOT IN ('dtproperties')

Change size of axes title and labels in ggplot2

If you are creating many graphs, you could be tired of typing for each graph the lines of code controlling for the size of the titles and texts. What I typically do is creating an object (of class "theme" "gg") that defines the desired theme characteristics. You can do that at the beginning of your code.

My_Theme = theme(
  axis.title.x = element_text(size = 16),
  axis.text.x = element_text(size = 14),
  axis.title.y = element_text(size = 16))

Next, all you will have to do is adding My_Theme to your graphs.

g + My_Theme
if you have another graph, g1, just write:
g1 + My_Theme 
and so on.

CSS background image to fit height, width should auto-scale in proportion

I know this is an old answer but for others searching for this; in your CSS try:

background-size: auto 100%;

Calculating powers of integers

No, there is not something as short as a**b

Here is a simple loop, if you want to avoid doubles:

long result = 1;
for (int i = 1; i <= b; i++) {
   result *= a;
}

If you want to use pow and convert the result in to integer, cast the result as follows:

int result = (int)Math.pow(a, b);

Draw radius around a point in Google map

I've had this problem in the past, so I bookmarked this discussion.

To summarize it, you can:

  1. Take a look at this circle filter's source code and figure out how to incorporate it into your project.
  2. Draw a GPolygon with enough points to simulate a circle.
  3. Generate a KML file by modifying http://www.nearby.org.uk/google/circle.kml.php?radius=30miles&lat=40.173&long=-105.1024 and then importing it. In Google Maps, you can just paste the URI in the search box and it will display on the map. I'm not sure how you might do it using the API though.

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

What is the difference between substr and substring?

The main difference is that

substr() allows you to specify the maximum length to return

substring() allows you to specify the indices and the second argument is NOT inclusive

There are some additional subtleties between substr() and substring() such as the handling of equal arguments and negative arguments. Also note substring() and slice() are similar but not always the same.

  //*** length vs indices:
    "string".substring(2,4);  // "ri"   (start, end) indices / second value is NOT inclusive
    "string".substr(2,4);     // "ring" (start, length) length is the maximum length to return
    "string".slice(2,4);      // "ri"   (start, end) indices / second value is NOT inclusive

  //*** watch out for substring swap:
    "string".substring(3,2);  // "r"    (swaps the larger and the smaller number)
    "string".substr(3,2);     // "in"
    "string".slice(3,2);      // ""     (just returns "")

  //*** negative second argument:
    "string".substring(2,-4); // "st"   (converts negative numbers to 0, then swaps first and second position)
    "string".substr(2,-4);    // ""
    "string".slice(2,-4);     // ""

  //*** negative first argument:
    "string".substring(-3);   // "string"        
    "string".substr(-3);      // "ing"  (read from end of string)
    "string".slice(-3);       // "ing"        

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

How can I set the focus (and display the keyboard) on my EditText programmatically

This worked for me, Thanks to ungalcrys

Show keyboard:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

Hide keyboard:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Like the other answers said, sp_reset_connection indicates that connection pool is being reused. Be aware of one particular consequence!

Jimmy Mays' MSDN Blog said:

sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.

UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.

ref: SQL Server: Isolation level leaks across pooled connections

Here is some additional information:

What does sp_reset_connection do?

Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.

sp_reset_connection resets the following aspects of a connection:

  • All error states and numbers (like @@error)

  • Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query

  • Waits for any outstanding I/O operations that is outstanding

  • Frees any held buffers on the server by the connection

  • Unlocks any buffer resources that are used by the connection

  • Releases all allocated memory owned by the connection

  • Clears any work or temporary tables that are created by the connection

  • Kills all global cursors owned by the connection

  • Closes any open SQL-XML handles that are open

  • Deletes any open SQL-XML related work tables

  • Closes all system tables

  • Closes all user tables

  • Drops all temporary objects

  • Aborts open transactions

  • Defects from a distributed transaction when enlisted

  • Decrements the reference count for users in current database which releases shared database locks

  • Frees acquired locks

  • Releases any acquired handles

  • Resets all SET options to the default values

  • Resets the @@rowcount value

  • Resets the @@identity value

  • Resets any session level trace options using dbcc traceon()

  • Resets CONTEXT_INFO to NULL in SQL Server 2005 and newer [ not part of the original article ]

sp_reset_connection will NOT reset:

  • Security context, which is why connection pooling matches connections based on the exact connection string

  • Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when sp_setapprole is executed.

Note: I am including the list here as I do not want it to be lost in the ever transient web.

How to concatenate two MP4 files using FFmpeg?

FOR MP4 FILES

For .mp4 files (which I obtained from DailyMotion.com: a 50 minute tv episode, downloadable only in three parts, as three .mp4 video files) the following was an effective solution for Windows 7, and does NOT involve re-encoding the files.

I renamed the files (as file1.mp4, file2.mp4, file3.mp4) such that the parts were in the correct order for viewing the complete tv episode.

Then I created a simple batch file (concat.bat), with the following contents:

:: Create File List
echo file file1.mp4 >  mylist.txt 
echo file file2.mp4 >> mylist.txt
echo file file3.mp4 >> mylist.txt

:: Concatenate Files
ffmpeg -f concat -i mylist.txt -c copy output.mp4

The batch file, and ffmpeg.exe, must both be put in the same folder as the .mp4 files to be joined. Then run the batch file. It will typically take less than ten seconds to run.
.

Addendum (2018/10/21) -

If what you were looking for is a method for specifying all the mp4 files in the current folder without a lot of retyping, try this in your Windows batch file instead (MUST include the option -safe 0):

:: Create File List
for %%i in (*.mp4) do echo file '%%i'>> mylist.txt

:: Concatenate Files
ffmpeg -f concat -safe 0 -i mylist.txt -c copy output.mp4

This works on Windows 7, in a batch file. Don't try using it on the command line, because it only works in a batch file!

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

CMD: Export all the screen content to a text file

From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:

net start > c:\netstart.txt

You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\ drive.

Access Database opens as read only

If someone else has the database open, then ask them to close it. If the database was not closed cleanly (Access or a computer crashed), then you can try to Compact and Repair the file.

I have also noticed that if the file is opened or put in a read-only state at any time, it might get 'stuck' like that. So try this:

  1. Open Access, but no database
  2. Open the file in question, but explicitly open it in read-only mode (the 'Open' button is actually a dropdown button. Use the button to open read-only
  3. Close the file (but not Access)
  4. Open the file again, but open normally.

Not sure it that's a bug or a feature, but I've seen it frustrate many a user.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

Disable resizing of a Windows Forms form

Take a look at the FormBorderStyle property

form1.FormBorderStyle = FormBorderStyle.FixedSingle;

You may also want to remove the minimize and maximize buttons:

form1.MaximizeBox = false;
form1.MinimizeBox = false;

Angular JS Uncaught Error: [$injector:modulerr]

I got this error because I had a dependency on another module that was not loaded.

angular.module("app", ["kendo.directives"]).controller("MyCtrl", function(){}...

so even though I had all the Angular modules, I didn't have the kendo one.

How to disable the back button in the browser using JavaScript

Our approach is simple, but it works! :)

When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.

<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
    function logOut() {
        window.close = function () { 
            window.open('Default.aspx', '_blank'); 
        };
    }
</script>

How to remove the border highlight on an input text element

This is a common concern.

The default outline that browsers render is ugly.

See this for example:

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}
_x000D_
<form>_x000D_
  <label>Click to see the input below to see the outline</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_


The most common "fix" that most recommend is outline:none - which if used incorrectly - is disaster for accessibility.


So...of what use is the outline anyway?

There's a very dry-cut website I found which explains everything well.

It provides visual feedback for links that have "focus" when navigating a web document using the TAB key (or equivalent). This is especially useful for folks who can't use a mouse or have a visual impairment. If you remove the outline you are making your site inaccessible for these people.

Ok, let's try it out same example as above, now use the TAB key to navigate.

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}
_x000D_
<form>_x000D_
  <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Notice how you can tell where the focus is even without clicking the input?

Now, let's try outline:none on our trusty <input>

So, once again, use the TAB key to navigate after clicking the text and see what happens.

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none;_x000D_
}
_x000D_
<form>_x000D_
  <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

See how it's more difficult to figure out where the focus is? The only telling sign is the cursor blinking. My example above is overly simplistic. In real-world situations, you wouldn't have only one element on the page. Something more along the lines of this.

_x000D_
_x000D_
.wrapper {_x000D_
  width: 500px;_x000D_
  max-width: 100%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
  <form>_x000D_
    <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
  </form>_x000D_
_x000D_
  <form>_x000D_
    First name:<br>_x000D_
    <input type="text" name="firstname"><br> Last name:<br>_x000D_
    <input type="text" name="lastname">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <input type="radio" name="gender" value="male" checked> Male<br>_x000D_
    <input type="radio" name="gender" value="female"> Female<br>_x000D_
    <input type="radio" name="gender" value="other"> Other_x000D_
  </form>_x000D_
_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="GET-name">Name:</label>_x000D_
    <input id="GET-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="POST-name">Name:</label>_x000D_
    <input id="POST-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <fieldset>_x000D_
      <legend>Title</legend>_x000D_
      <input type="radio" name="radio" id="radio">_x000D_
      <label for="radio">Click me</label>_x000D_
    </fieldset>_x000D_
  </form>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now compare that to the same template if we keep the outline:

_x000D_
_x000D_
.wrapper {_x000D_
  width: 500px;_x000D_
  max-width: 100%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
  <form>_x000D_
    <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
  </form>_x000D_
_x000D_
  <form>_x000D_
    First name:<br>_x000D_
    <input type="text" name="firstname"><br> Last name:<br>_x000D_
    <input type="text" name="lastname">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <input type="radio" name="gender" value="male" checked> Male<br>_x000D_
    <input type="radio" name="gender" value="female"> Female<br>_x000D_
    <input type="radio" name="gender" value="other"> Other_x000D_
  </form>_x000D_
_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="GET-name">Name:</label>_x000D_
    <input id="GET-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="POST-name">Name:</label>_x000D_
    <input id="POST-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <fieldset>_x000D_
      <legend>Title</legend>_x000D_
      <input type="radio" name="radio" id="radio">_x000D_
      <label for="radio">Click me</label>_x000D_
    </fieldset>_x000D_
  </form>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

So we have established the following

  1. Outlines are ugly
  2. Removing them makes life more difficult.

So what's the answer?

Remove the ugly outline and add your own visual cues to indicate focus.

Here's a very simple example of what I mean.

I remove the outline and add a bottom border on :focus and :active. I also remove the default borders on the top, left and right sides by setting them to transparent on :focus and :active (personal preference)

_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none_x000D_
}_x000D_
_x000D_
input:focus,_x000D_
input:active {_x000D_
  border-color: transparent;_x000D_
  border-bottom: 2px solid red_x000D_
}
_x000D_
<form>_x000D_
  <label>Click to see the input below to see the outline</label>_x000D_
  <input type="text" placeholder="placeholder text" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

So, we try the approach above with our "real-world" example from earlier:

_x000D_
_x000D_
.wrapper {_x000D_
  width: 500px;_x000D_
  max-width: 100%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
form,_x000D_
label {_x000D_
  margin: 1em auto;_x000D_
}_x000D_
_x000D_
label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  outline: none_x000D_
}_x000D_
_x000D_
input:focus,_x000D_
input:active {_x000D_
  border-color: transparent;_x000D_
  border-bottom: 2px solid red_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
  <form>_x000D_
    <label>Click on this text and then use the TAB key to naviagte inside the snippet.</label>_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
    <input type="text" placeholder="placeholder text" />_x000D_
  </form>_x000D_
_x000D_
  <form>_x000D_
    First name:<br>_x000D_
    <input type="text" name="firstname"><br> Last name:<br>_x000D_
    <input type="text" name="lastname">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <input type="radio" name="gender" value="male" checked> Male<br>_x000D_
    <input type="radio" name="gender" value="female"> Female<br>_x000D_
    <input type="radio" name="gender" value="other"> Other_x000D_
  </form>_x000D_
_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="GET-name">Name:</label>_x000D_
    <input id="GET-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <label for="POST-name">Name:</label>_x000D_
    <input id="POST-name" type="text" name="name">_x000D_
  </form>_x000D_
_x000D_
_x000D_
  <form>_x000D_
    <fieldset>_x000D_
      <legend>Title</legend>_x000D_
      <input type="radio" name="radio" id="radio">_x000D_
      <label for="radio">Click me</label>_x000D_
    </fieldset>_x000D_
  </form>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

This can be extended further by using external libraries that build on the idea of modifying the "outline" as opposed to removing it entirely like Materialize

You can end up with something that is not ugly and works with very little effort

_x000D_
_x000D_
body {_x000D_
  background: #444_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2em;_x000D_
  width: 400px;_x000D_
  max-width: 100%;_x000D_
  text-align: center;_x000D_
  margin: 2em auto;_x000D_
  border: 1px solid #555_x000D_
}_x000D_
_x000D_
button,_x000D_
.wrapper {_x000D_
  border-radius: 3px;_x000D_
}_x000D_
_x000D_
button {_x000D_
  padding: .25em 1em;_x000D_
}_x000D_
_x000D_
input,_x000D_
label {_x000D_
  color: white !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.1/css/materialize.min.css" />_x000D_
_x000D_
<div class="wrapper">_x000D_
  <form>_x000D_
    <input type="text" placeholder="Enter Username" name="uname" required>_x000D_
    <input type="password" placeholder="Enter Password" name="psw" required>_x000D_
    <button type="submit">Login</button>_x000D_
  </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

C++ int to byte array

You don't need a whole function for this; a simple cast will suffice:

int x;
static_cast<char*>(static_cast<void*>(&x));

Any object in C++ can be reinterpreted as an array of bytes. If you want to actually make a copy of the bytes into a separate array, you can use std::copy:

int x;
char bytes[sizeof x];
std::copy(static_cast<const char*>(static_cast<const void*>(&x)),
          static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x,
          bytes);

Neither of these methods takes byte ordering into account, but since you can reinterpret the int as an array of bytes, it is trivial to perform any necessary modifications yourself.

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

i use that function and it works fine

$(document).ready(function () {
        $("#txt_Price").keypress(function (e) {
            //if the letter is not digit then display error and don't type anything
            //if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
            if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
                //display error message
                $("#errmsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
        });
    }); 

How to fix "Attempted relative import in non-package" even with __init__.py

Yes. You're not using it as a package.

python -m pkg.tests.core_test

What is the best way to declare global variable in Vue.js?

A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.

An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478

Substring a string from the end of the string

string s = "Hello Marco !";
s = s.Remove(s.length - 2, 2);

Return multiple values to a method caller

You can use three different ways

1. ref / out parameters

using ref:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add = 0;
    int multiply = 0;
    Add_Multiply(a, b, ref add, ref multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
    add = a + b;
    multiply = a * b;
}

using out:

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    int add;
    int multiply;
    Add_Multiply(a, b, out add, out multiply);
    Console.WriteLine(add);
    Console.WriteLine(multiply);
}

private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
    add = a + b;
    multiply = a * b;
}

2. struct / class

using struct:

struct Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

using class:

class Result
{
    public int add;
    public int multiply;
}
static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.add);
    Console.WriteLine(result.multiply);
}

private static Result Add_Multiply(int a, int b)
{
    var result = new Result
    {
        add = a * b,
        multiply = a + b
    };
    return result;
}

3. Tuple

Tuple class

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    var result = Add_Multiply(a, b);
    Console.WriteLine(result.Item1);
    Console.WriteLine(result.Item2);
}

private static Tuple<int, int> Add_Multiply(int a, int b)
{
    var tuple = new Tuple<int, int>(a + b, a * b);
    return tuple;
}

C# 7 Tuples

static void Main(string[] args)
{
    int a = 10;
    int b = 20;
    (int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
    Console.WriteLine(a_plus_b);
    Console.WriteLine(a_mult_b);
}

private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
    return(a + b, a * b);
}

Excel VBA Loop on columns

If you want to stick with the same sort of loop then this will work:

Option Explicit

Sub selectColumns()

Dim topSelection As Integer
Dim endSelection As Integer
topSelection = 2
endSelection = 10

Dim columnSelected As Integer
columnSelected = 1
Do
   With Excel.ThisWorkbook.ActiveSheet
        .Range(.Cells(columnSelected, columnSelected), .Cells(endSelection, columnSelected)).Select
   End With
   columnSelected = columnSelected + 1
Loop Until columnSelected > 10

End Sub

EDIT

If in reality you just want to loop through every cell in an area of the spreadsheet then use something like this:

Sub loopThroughCells()

'=============
'this is the starting point
Dim rwMin As Integer
Dim colMin As Integer
rwMin = 2
colMin = 2
'=============

'=============
'this is the ending point
Dim rwMax As Integer
Dim colMax As Integer
rwMax = 10
colMax = 5
'=============

'=============
'iterator
Dim rwIndex As Integer
Dim colIndex As Integer
'=============

For rwIndex = rwMin To rwMax
        For colIndex = colMin To colMax
            Cells(rwIndex, colIndex).Select
        Next colIndex
Next rwIndex

End Sub

How to change the MySQL root account password on CentOS7?

Please stop all services MySQL with following command /etc/init.d/mysqld stop After it use this

mysqld_safe --skip-grant-tables

its may work properly

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

Making Python loggers output all messages to stdout in addition to log file

The simplest way to log to stdout:

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

My personal favorite when using jQuery is short and sweet:

function capitalize(word) {
   return $.camelCase("-" + word);
}

There's a jQuery plugin that does this too. I'll call it... jCap.js

$.fn.extend($, { 
    capitalize: function() {
        return $.camelCase("-"+arguments[0]); 
    } 
});

Adding blank spaces to layout

Below is the simple way to create blank line with line size. Here we can adjust size of the blank line. Try this one.

           <TextView
            android:id="@id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="5dp"/>

jQuery .live() vs .on() method for adding a click event after loading dynamic html

$(document).on('click', '.selector', function() { /* do stuff */ });

EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.

When you click on any element(s) matching .selector, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation() method -- which would top the bubbling of an event to parent elements.

Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.

This is smart for a few reasons, including performance and memory utilization (in large scale applications)

EDIT:

Obviously, the closest parent element you can listen on is better, and you can use any element in place of document as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.

How do I run a program with commandline arguments using GDB within a Bash script?

In addition to the answer of Hugo Ideler. When using arguments having themself prefix like -- or -, I was not sure to conflict with gdb one.

It seems gdb takes all after args option as arguments for the program.

At first I wanted to be sure, I ran gdb with quotes around your args, it is removed at launch.

This works too, but optional:

gdb --args executablename "--arg1" "--arg2" "--arg3"

This doesn't work :

gdb --args executablename "--arg1" "--arg2" "--arg3" -tui

In that case, -tui is used as my program parameter not as gdb one.

how to stop a for loop

Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.

Get specific object by id from array of objects in AngularJS

Using ES6 solution

For those still reading this answer, if you are using ES6 the find method was added in arrays. So assuming the same collection, the solution'd be:

const foo = { "results": [
    {
        "id": 12,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] };
foo.results.find(item => item.id === 2)

I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.

Angular solution (old solution)

I aimed to solve this problem by doing the following:

$filter('filter')(foo.results, {id: 1})[0];

A use case example:

app.controller('FooCtrl', ['$filter', function($filter) {
    var foo = { "results": [
        {
            "id": 12,
            "name": "Test"
        },
        {
            "id": 2,
            "name": "Beispiel"
        },
        {
            "id": 3,
            "name": "Sample"
        }
    ] };

    // We filter the array by id, the result is an array
    // so we select the element 0

    single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];

    // If you want to see the result, just check the log
    console.log(single_object);
}]);

Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview

How do I set default values for functions parameters in Matlab?

Matlab doesn't provide a mechanism for this, but you can construct one in userland code that's terser than inputParser or "if nargin < 1..." sequences.

function varargout = getargs(args, defaults)
%GETARGS Parse function arguments, with defaults
%
% args is varargin from the caller. By convention, a [] means "use default".
% defaults (optional) is a cell vector of corresponding default values

if nargin < 2;  defaults = {}; end

varargout = cell(1, nargout);
for i = 1:nargout
    if numel(args) >= i && ~isequal(args{i}, [])
        varargout{i} = args{i};
    elseif numel(defaults) >= i
        varargout{i} = defaults{i};
    end
end

Then you can call it in your functions like this:

function y = foo(varargin)
%FOO 
%
% y = foo(a, b, c, d, e, f, g)

[a, b,  c,       d, e, f, g] = getargs(varargin,...
{1, 14, 'dfltc'});

The formatting is a convention that lets you read down from parameter names to their default values. You can extend your getargs() with optional parameter type specifications (for error detection or implicit conversion) and argument count ranges.

There are two drawbacks to this approach. First, it's slow, so you don't want to use it for functions that are called in loops. Second, Matlab's function help - the autocompletion hints on the command line - don't work for varargin functions. But it is pretty convenient.

Python AttributeError: 'module' object has no attribute 'Serial'

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Problem occurs when you import 'something' when your python file name is 'something.py'.

How to simulate browsing from various locations?

Well, DNS should be the same worldwide, wouldn't it? Of course it can take up to a day or so until your new DNS record is propagated around the world. So either something is wrong on your colleague's end or the DNS record still takes some time...

I usually use online DNS lookup tools for that, e.g. http://network-tools.com/

It can check your HTTP header as well. Only a proxy located in Europe would be better.

What is an index in SQL?

An index is used for several different reasons. The main reason is to speed up querying so that you can get rows or sort rows faster. Another reason is to define a primary-key or unique index which will guarantee that no other columns have the same values.

Datatables - Setting column width

you should use "bAutoWidth" property of datatable and give width to each td/column in %

 $(".table").dataTable({"bAutoWidth": false , 
aoColumns : [
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "10%"},
    ]
});

Hope this will help.

Elegant solution for line-breaks (PHP)

Well, as with any language there are several ways to do it.

As previous answerers have mentioned, "<br/>" is not a linebreak in the traditional sense, it's an HTML line break. I don't know of a built in PHP constant for this, but you can always define your own:

// Something like this, but call it whatever you like
const HTML_LINEBREAK = "<br/>";

If you're outputting a bunch of lines (from an array of strings for example), you can use it this way:

// Output an array of strings
$myStrings = Array('Line1','Line2','Line3');
echo implode(HTML_LINEBREAK,$myStrings);

However, generally speaking I would say avoid hard coding HTML inside your PHP echo/print statements. If you can keep the HTML outside of the code, it makes things much more flexible and maintainable in the long run.

Getting values from JSON using Python

If you want to iterate over both keys and values of the dictionary, do this:

for key, value in data.items():
    print key, value

How can I determine the status of a job?

SELECT sj.name
  FROM msdb..sysjobactivity aj
  JOIN msdb..sysjobs sj
    on sj.job_id = aj.job_id
 WHERE aj.stop_execution_date  IS NULL     -- job hasn't stopped running
   AND aj.start_execution_date IS NOT NULL -- job is currently running
   AND sj.name = '<your Job Name>'
   AND NOT EXISTS( -- make sure this is the most recent run
                   select 1
                     from msdb..sysjobactivity new
                    where new.job_id = aj.job_id
                      and new.start_execution_date > aj.start_execution_date ) )
print 'running'

I can not find my.cnf on my windows computer

you can search this file : resetroot.bat

just double click it so that your root accout will be reset and all the privileges are turned into YES

docker : invalid reference format

I had the same issue when I copy-pasted the command. Instead, when I typed-in the entire command, it worked!

Good Luck...

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

myenv:

python 2.7.14

pip 9.0.1

mac osx 10.9.4


mysolution:

  1. download get-pip.py manually from https://packaging.python.org/tutorials/installing-packages/

  2. run python get-pip.py


refs:

https://github.com/pypa/warehouse/issues/3293#issuecomment-378468534

https://packaging.python.org/tutorials/installing-packages/

Securely Download get-pip.py [1]

Run python get-pip.py. [2] This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.

Ensure pip, setuptools, and wheel are up to date

While pip alone is sufficient to install from pre-built binary archives, up to date copies of the setuptools and wheel projects are useful to ensure you can also install from source archives:

python -m pip install --upgrade pip setuptools wheel

How can I simulate an anchor click via jquery?

I've recently found how to trigger mouse click event via jQuery.

    <script type="text/javascript">
    var a = $('.path > .to > .element > a')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
    </script>

What is best tool to compare two SQL Server databases (schema and data)?

I use schema and data comparison functionality built into the latest version Microsoft Visual Studio 2015 Community Edition (Free) or Professional / Premium / Ultimate edition. Works like a charm!

img

http://channel9.msdn.com/Events/Visual-Studio/Launch-2013/VS108

Red-Gate's SQL data comparison tool is my second alternative:

img
(source: spaanjaars.com)

Visual C++ executable and missing MSVCR100d.dll

This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.

But sometimes the following solution can be used (as developer's side solution):

In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation and change option Runtime Library to /MT instead of /MD

READ_EXTERNAL_STORAGE permission for Android

Has your problem been resolved? What is your target SDK? Try adding android;maxSDKVersion="21" to <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

How to add an image to a JPanel?

Create a source folder in your project directory, in this case I called it Images.

JFrame snakeFrame = new JFrame();
snakeFrame.setBounds(100, 200, 800, 800);
snakeFrame.setVisible(true);
snakeFrame.add(new JLabel(new ImageIcon("Images/Snake.png")));
snakeFrame.pack();

Stylesheet not updating

This may not have been the OP's problem, but I had the same problem and solved it by flushing then disabling Supercache on my cpanel. Perhaps some other newbies like myself won't know that many hosting providers cache CSS and some other static files, and these cached old versions of CSS files will persist in the cloud for hours after you edit the file on your server. If your site serves up old versions of CSS files after you edit them, and you're certain you've cleared your browser cache, and you don't know whether your host is caching stuff, check that first before you try any other more complicated suggestions.

Removing all non-numeric characters from string in Python

This should work for both strings and unicode objects in Python2, and both strings and bytes in Python3:

# python <3.0
def only_numerics(seq):
    return filter(type(seq).isdigit, seq)

# python =3.0
def only_numerics(seq):
    seq_type= type(seq)
    return seq_type().join(filter(seq_type.isdigit, seq))

This version of the application is not configured for billing through Google Play

SOLUTION

Just hold on a while after uploading your app on play store because google takes some time to update app versions.It will work !

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

Printing column separated by comma using Awk command line

If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:

cut -d, -f3 file
  • -d, sets the delimiter to a comma
  • -f3 specifies that only the third field is to be printed

Convert DataTable to CSV stream

public void CreateCSVFile(DataTable dt, string strFilePath,string separator)
        {               
            #region Export Grid to CSV
            // Create the CSV file to which grid data will be exported.

            StreamWriter sw = new StreamWriter(strFilePath, false); 
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {    
                sw.Write(dt.Columns[i]);    
                if (i < iColCount - 1)
                {
                    sw.Write(separator);
                }  
            }    

            sw.Write(sw.NewLine);

            // Now write all the rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());  
                    }

                    if (i < iColCount - 1)
                    {
                        sw.Write(separator);
                    }
                }
                sw.Write(sw.NewLine);
            }

            sw.Close();
            #endregion
        }

How to convert empty spaces into null values, using SQL Server?

Maybe something like this?

UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0

Replace \n with <br />

You could also have problems if the string has <, > or & chars in it, etc. Pass it to cgi.escape() to deal with those.

http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I solved it with the following:

Go to View-> Property Pages -> Configuration Properties -> Linker -> Input

Under additional dependencies add the thelibrary.lib. Don't use any quotations.

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

How to declare a variable in SQL Server and use it in the same Stored Procedure

None of the above methods worked for me so i'm posting the way i did

DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN 

DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID  int;
SELECT BrandID = BrandID FROM tblBrand 
WHERE BrandName = BrandName;

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (CategoryID, BrandID);
END$$

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Is Button1 visible? I mean, from the server side. Make sure Button1.Visible is true.

Controls that aren't Visible won't be rendered in HTML, so although they are assigned a ClientID, they don't actually exist on the client side.

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

How do I fix "Expected to return a value at the end of arrow function" warning?

A map() creates an array, so a return is expected for all code paths (if/elses).

If you don't want an array or to return data, use forEach instead.

AngularJS - value attribute for select

It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):

HTML:

<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>

Javascript:

App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}

Then, in my server-side code I just looked for params[:profile_id] (this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.

Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:

<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>

and

<input name="profile_id" type="hidden" ng-model="profile"/>

I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

Add below code in your client code :

static {
    Security.insertProviderAt(new BouncyCastleProvider(),1);
 }

with this there is no need to add any entry in java.security file.

How to submit a form when the return key is pressed?

Why don't you just apply the div submit styles to a submit button? I'm sure there's a javascript for this but that would be easier.

Is it correct to use DIV inside FORM?

I noticed that whenever I would start the form tag inside a div the subsequent div siblings would not be part of the form when I inspect (chrome inspect) henceforth my form would never submit.

<div>
<form>
<input name='1st input'/>
</div>
<div>
<input name='2nd input'/>
</div>
<input type='submit'/>
</form>

I figured that if I put the form tag outside the DIVs it worked. The form tag should be placed at the start of the parent DIV. Like shown below.

<form>
<div>
<input name='1st input'/>
</div>
<div>
<input name='2nd input'/>
</div>
<input type='submit'/>
</form>

Cannot simply use PostgreSQL table name ("relation does not exist")

You have to add the schema first e.g.

SELECT * FROM place.user_place;

If you don't want to add that in all queries then try this:

SET search_path TO place;

Now it will works:

SELECT * FROM user_place;

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

As Sonars sonar.jacoco.reportPath, sonar.jacoco.itReportPath and sonar.jacoco.reportPaths have all been deprecated, you should use sonar.coverage.jacoco.xmlReportPaths now. This also has some impact if you want to configure a multi module maven project with Sonar and Jacoco.

As @Lonzak pointed out, since Sonar 0.7.7, you can use Sonars report aggragation goal. Just put in you parent pom the following dependency:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.5</version>
    <executions>
        <execution>
            <id>report</id>
            <goals>
                <goal>report-aggregate</goal>
            </goals>
            <phase>verify</phase>
        </execution>
    </executions>
</plugin>

As current versions of the jacoco-maven-plugin are compatible with the xml-reports, this will create for every module in it's own target folder a site/jacoco-aggregate folder containing a jacoco.xml file.

To let Sonar combine all the modules, use following command:

mvn -Dsonar.coverage.jacoco.xmlReportPaths=full-path-to-module1/target/site/jacoco-aggregate/jacoco.xml,module2...,module3... clean verify sonar:sonar

To keep my answer short and precise, I did not mention the maven-surefire-plugin and maven-failsafe-plugin dependencies. You can just add them without any other configuration:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.22.2</version>
    <executions>
        <execution>
        <id>integration-test</id>
            <goals>
                <goal>integration-test</goal>
            </goals>
        </execution>
    </executions>
</plugin>

403 - Forbidden: Access is denied. ASP.Net MVC

Are you hosting the site on iis? if so make sure the account your website runs under has access to local file system?

Straight from msdn .....

The Network Service account has Read and Execute permissions on the IIS server root folder by default. The IIS server root folder is named Wwwroot. This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

To provide access to an ASP.NET application running as Network Service, you must grant access to the Network Service account.

To grant read, write, and modify permissions to a specific file

  • In Windows Explorer, locate and select the required file.
  • Right-click the file, and then click Properties.
  • In the Properties dialog box, click the Security tab.
  • On the Security tab, examine the list of users. If the Network Service
  • account is not listed, add it.
  • In the Properties dialog box, click the Network Service user name, and in the Permissions for NETWORK SERVICE section, select the Read, Write, and Modify permissions.
  • Click Apply, and then click OK.

Click here for more

Python float to int conversion

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:

>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994

If you use int, which truncates the numbers, you get:

250
401

Have a look at the Decimal type.

Shortest way to print current year in a website

TJ's answer is excellent but I ran into one scenario where my HTML was already rendered and the document.write script would overwrite all of the page contents with just the date year.

For this scenario, you can append a text node to the existing element using the following code:

<div>
    &copy;
    <span id="copyright">
        <script>document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear()))</script>
    </span>
    Company Name
</div>

In which case do you use the JPA @JoinTable annotation?

@ManyToMany associations

Most often, you will need to use @JoinTable annotation to specify the mapping of a many-to-many table relationship:

  • the name of the link table and
  • the two Foreign Key columns

So, assuming you have the following database tables:

Many-to-many table relationship

In the Post entity, you would map this relationship, like this:

@ManyToMany(cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE
})
@JoinTable(
    name = "post_tag",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();

The @JoinTable annotation is used to specify the table name via the name attribute, as well as the Foreign Key column that references the post table (e.g., joinColumns) and the Foreign Key column in the post_tag link table that references the Tag entity via the inverseJoinColumns attribute.

Notice that the cascade attribute of the @ManyToMany annotation is set to PERSIST and MERGE only because cascading REMOVE is a bad idea since we the DELETE statement will be issued for the other parent record, tag in our case, not to the post_tag record.

Unidirectional @OneToMany associations

The unidirectional @OneToMany associations, that lack a @JoinColumn mapping, behave like many-to-many table relationships, rather than one-to-many.

So, assuming you have the following entity mappings:

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;
 
    @OneToMany(
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
 
    //Constructors, getters and setters removed for brevity
}
 
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String review;
 
    //Constructors, getters and setters removed for brevity
}

Hibernate will assume the following database schema for the above entity mapping:

Unidirectional @OneToMany JPA association database tables

As already explained, the unidirectional @OneToMany JPA mapping behaves like a many-to-many association.

To customize the link table, you can also use the @JoinTable annotation:

@OneToMany(
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
@JoinTable(
    name = "post_comment_ref",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();

And now, the link table is going to be called post_comment_ref and the Foreign Key columns will be post_id, for the post table, and post_comment_id, for the post_comment table.

Unidirectional @OneToMany associations are not efficient, so you are better off using bidirectional @OneToMany associations or just the @ManyToOne side.

What is the use of the JavaScript 'bind' method?

The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.

setInterval(this.animate_to.bind(this), 1000/this.difference);

Project vs Repository in GitHub

The conceptual difference in my understanding it that a project can contain many repo's and that are independent of each other, while simultaneously a repo may contain many projects. Repo's being just a storage place for code while a project being a collection of tasks for a certain feature.

Does that make sense? A large repo can have many projects being worked on by different people at the same time (lots of difference features being added to a monolith), a large project may have many small repos that are separate but part of the same project that interact with each other - microservices? Its a personal take on what you want to do. I think that repo (storage) vs project (tasks) is the main difference - if i am wrong please let me know / explain! Thanks.

Random color generator

The top voted comment of the top answer suggests that Martin Ankerl's approach is better than random hex numbers, and although I haven't improved on Ankerl's methodology, I have successfully translated it to JavaScript.

I figured I'd post an additional answer to this already mega-sized Stack Overflow question because the top answer has another comment linking to a Gist with the JavaScript implementation of Ankerl's logic and that link is broken (404). If I had the reputation, I would have simply commented the jsbin link I created.

// Adapted from
// http://jsfiddle.net/Mottie/xcqpF/1/light/
const rgb2hex = (rgb) => {
  return (rgb && rgb.length === 3) ? "#" +
    ("0" + parseInt(rgb[0],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) : '';
}

// The next two methods are converted from Ruby to JavaScript.
// It is sourced from http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

// # HSV values in [0..1[
// # returns [r, g, b] values from 0 to 255
const hsv_to_rgb = (h, s, v) => {
  const h_i = Math.floor(h*6)
  const f = h*6 - h_i
  const p = v * (1 - s)
  const q = v * (1 - (f * s))
  const t = v * (1 - (1 - f) * s)
  let r, g, b
  switch(h_i) {
    case(0):
      [r, g, b] = [v, t, p]
      break
    case(1):
      [r, g, b] = [q, v, p]
      break
    case(2):
      [r, g, b] = [p, v, t]
      break
    case(3):
      [r, g, b] = [p, q, v]
      break
    case(4):
      [r, g, b] = [t, p, v]
      break
    case(5):
      [r, g, b] = [v, p, q]
      break
  }
  return [Math.floor(r * 256), Math.floor(g * 256), Math.floor(b * 256)]
}

// # Use the golden ratio
const golden_ratio_conjugate = 0.618033988749895
let h = Math.random() // # Use a random start value
const gen_hex = (numberOfColors) => {
  const colorArray = []
  while (numberOfColors > 0) {
    h += golden_ratio_conjugate
    h %= 1
    colorArray.push(rgb2hex(hsv_to_rgb(h, 0.99, 0.99)))
    numberOfColors -= 1
  }
  console.log(colorArray)
  return colorArray
}

gen_hex(100)

https://jsbin.com/qeyevoj/edit?js,console

How to find indices of all occurrences of one string in another in JavaScript?

One liner using String.protype.matchAll (ES2020):

[...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index)

Using your values:

const sourceStr = 'I learned to play the Ukulele in Lebanon.';
const searchStr = 'le';
const indexes = [...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index);
console.log(indexes); // [2, 25, 27, 33]

If you're worried about doing a spread and a map() in one line, I ran it with a for...of loop for a million iterations (using your strings). The one liner averages 1420ms while the for...of averages 1150ms on my machine. That's not an insignificant difference, but the one liner will work fine if you're only doing a handful of matches.

See matchAll on caniuse

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

The gcf method is depricated in V 0.14, The below code works for me:

plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

Open this Link and select follow the instructions google servers blocks any attempts from unknown servers so once you click on captcha check every thing will be fine

Change Schema Name Of Table In SQL

Create Schema :

IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe')) 
BEGIN
    EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END

ALTER Schema :

ALTER SCHEMA exe 
    TRANSFER dbo.Employees

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

What is copy-on-write?

I found this good article about zval in PHP, which mentioned COW too:

Copy On Write (abbreviated as ‘COW’) is a trick designed to save memory. It is used more generally in software engineering. It means that PHP will copy the memory (or allocate new memory region) when you write to a symbol, if this one was already pointing to a zval.

Read a zipped file as a pandas DataFrame

I think you want to open the ZipFile, which returns a file-like object, rather than read:

In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
BUSINESSIMPROVEMENTDISTRICT    3613  non-null values
dtypes: float64(4), int64(1), object(10)

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

How do I center a window onscreen in C#?

In case of multi monitor and If you prefer to center on correct monitor/screen then you might like to try these lines:

// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;

// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

How to get 30 days prior to current date?

Get next 30 days from today

_x000D_
_x000D_
let now = new Date()_x000D_
console.log('Today: ' + now.toUTCString())_x000D_
let next30days = new Date(now.setDate(now.getDate() + 30))_x000D_
console.log('Next 30th day: ' + next30days.toUTCString())
_x000D_
_x000D_
_x000D_

Get last 30 days form today

_x000D_
_x000D_
let now = new Date()_x000D_
console.log('Today: ' + now.toUTCString())_x000D_
let last30days = new Date(now.setDate(now.getDate() - 30))_x000D_
console.log('Last 30th day: ' + last30days.toUTCString())
_x000D_
_x000D_
_x000D_

AES Encrypt and Decrypt

There is an interesting "pure-swift" Open Source library:

Example with AES decrypt (got from project README.md file):

import CryptoSwift
let setup = (key: keyData, iv: ivData)
let decryptedAES = AES(setup).decrypt(encryptedData)

Spring cannot find bean xml configuration file when it does exist

Beans.xml or file.XML is not placed under proper path. You should add the XML file under the resource folder, if you have a Maven project. src -> main -> java -> resources

Google Maps API warning: NoApiKeys

A key currently still is not required ("required" in the meaning "it will not work without"), but I think there is a good reason for the warning.

But in the documentation you may read now : "All JavaScript API applications require authentication."

I'm sure that it's planned for the future , that Javascript API Applications will not work without a key(as it has been in V2).

You better use a key when you want to be sure that your application will still work in 1 or 2 years.

How to include vars file in a vars file with ansible?

I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :

cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or 
#cat release_vars.yml >> vars.yml
mvn ....

Is there a list of screen resolutions for all Android based phones and tablets?

These are the sizes. Try to take a look in Supporting Mutiple Screens

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

I use this to make more than one layout:

res/layout/main_activity.xml           # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

Radio buttons not checked in jQuery

If my firebug profiler work fine (and i know how to use it well), this:

$('#communitymode').attr('checked')

is faster than

$('#communitymode').is('checked')

You can try on this page :)

And then you can use it like

if($('#communitymode').attr('checked')===true) { 
// do something
}

Cheap way to search a large text file for a string

I've had a go at putting together a multiprocessing example of file text searching. This is my first effort at using the multiprocessing module; and I'm a python n00b. Comments quite welcome. I'll have to wait until at work to test on really big files. It should be faster on multi core systems than single core searching. Bleagh! How do I stop the processes once the text has been found and reliably report line number?

import multiprocessing, os, time
NUMBER_OF_PROCESSES = multiprocessing.cpu_count()

def FindText( host, file_name, text):
    file_size = os.stat(file_name ).st_size 
    m1 = open(file_name, "r")

    #work out file size to divide up to farm out line counting

    chunk = (file_size / NUMBER_OF_PROCESSES ) + 1
    lines = 0
    line_found_at = -1

    seekStart = chunk * (host)
    seekEnd = chunk * (host+1)
    if seekEnd > file_size:
        seekEnd = file_size

    if host > 0:
        m1.seek( seekStart )
        m1.readline()

    line = m1.readline()

    while len(line) > 0:
        lines += 1
        if text in line:
            #found the line
            line_found_at = lines
            break
        if m1.tell() > seekEnd or len(line) == 0:
            break
        line = m1.readline()
    m1.close()
    return host,lines,line_found_at

# Function run by worker processes
def worker(input, output):
    for host,file_name,text in iter(input.get, 'STOP'):
        output.put(FindText( host,file_name,text ))

def main(file_name,text):
    t_start = time.time()
    # Create queues
    task_queue = multiprocessing.Queue()
    done_queue = multiprocessing.Queue()
    #submit file to open and text to find
    print 'Starting', NUMBER_OF_PROCESSES, 'searching workers'
    for h in range( NUMBER_OF_PROCESSES ):
        t = (h,file_name,text)
        task_queue.put(t)

    #Start worker processes
    for _i in range(NUMBER_OF_PROCESSES):
        multiprocessing.Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results

    results = {}
    for _i in range(NUMBER_OF_PROCESSES):
        host,lines,line_found = done_queue.get()
        results[host] = (lines,line_found)

    # Tell child processes to stop
    for _i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')
#        print "Stopping Process #%s" % i

    total_lines = 0
    for h in range(NUMBER_OF_PROCESSES):
        if results[h][1] > -1:
            print text, 'Found at', total_lines + results[h][1], 'in', time.time() - t_start, 'seconds'
            break
        total_lines += results[h][0]

if __name__ == "__main__":
    main( file_name = 'testFile.txt', text = 'IPI1520' )

How to find the users list in oracle 11g db?

You can try the following: (This may be duplicate of the answers posted but I have added description)

Display all users that can be seen by the current user:

SELECT * FROM all_users;

Display all users in the Database:

SELECT * FROM dba_users;

Display the information of the current user:

SELECT * FROM user_users;

Lastly, this will display all users that can be seen by current users based on creation date:

SELECT * FROM all_users
ORDER BY created;

Manually map column names with class properties

An easy way to achieve this is to just use aliases on the columns in your query.

If your database column is PERSON_ID and your object's property is ID, you can just do

select PERSON_ID as Id ...

in your query and Dapper will pick it up as expected.

How to increase buffer size in Oracle SQL Developer to view all records?

press f5 for running queries instead of f9. It will give you all the results in one go...

Get a json via Http Request in NodeJS

Just tell request that you are using json:true and forget about header and parse

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'GET',
    json:true
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

and the same for post

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'POST',
    json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

How to set UICollectionViewCell Width and Height programmatically

Swift 5, Programmatic UICollectionView setting Cell width and height

// MARK: MyViewController

final class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        let spacing: CGFloat = 1
        let numOfColumns: CGFloat = 3
        let itemSize: CGFloat = (UIScreen.main.bounds.width - (numOfColumns - spacing) - 2) / 3
        layout.itemSize = CGSize(width: itemSize, height: itemSize)
        layout.minimumInteritemSpacing = spacing
        layout.minimumLineSpacing = spacing
        layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureCollectionView()
    }
    
    private func configureCollectionView() {
        view.addSubview(collectionView)
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
        ])
        collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell")
    }
    
    // MARK: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
        cell.backgroundColor = .red
        return cell
    }
    
}

// MARK: PhotoCell

final class PhotoCell: UICollectionViewCell {
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init?(coder:) not implemented")
    }
    
    func setupViews() {
        addSubview(imageView)
        NSLayoutConstraint.activate([
            topAnchor.constraint(equalTo: topAnchor),
            bottomAnchor.constraint(equalTo: bottomAnchor),
            leadingAnchor.constraint(equalTo: leadingAnchor),
            trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
    }
    
}

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

This was caused because of something like this in my case:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/headerfooter/header.jsp</include-prelude>
        <include-coda>/headerfooter/footer.jsp</include-coda>
    </jsp-property-group>
</jsp-config>

The problem was actually I did not have header.jsp in my project. However the error message was still saying index_jsp was not found.

gcc makefile error: "No rule to make target ..."

There are multiple reasons for this error.

One of the reason where i encountered this error is while building for linux and windows.

I have a filename with caps BaseClass.h SubClass.h Unix maintains has case-sensitive filenaming convention and windows is case-insensitive.

C++ why people don't use uppercase in name of header files?

Try compiling clean build using gmake clean if you are using gmake

Some text editors has default settings to ignore case-sensitive filenames. This could also lead to the same error.

how to add a c++ file in Qt Creator whose name starts with capital letters ? It automatically makes it small letter

What is the use of BindingResult interface in spring MVC?

Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.

Then, you can check this object looking for validation errors:

validator.validate(modelObject, bindingResult);  
if (bindingResult.hasErrors()) {  
    // do something  
}

Stopping Excel Macro executution when pressing Esc won't work

You can also try pressing the "FN" or function key with the button "Break" or with the button "sys rq" - system request as this - must be pressed together and this stops any running macro

jQuery scroll() detect when user stops scrolling

Ok this is something that I've used before. Basically you look a hold a ref to the last scrollTop(). Once your timeout clears, you check the current scrollTop() and if they are the same, you are done scrolling.

$(window).scroll((e) ->
  clearTimeout(scrollTimer)
  $('header').addClass('hidden')

  scrollTimer = setTimeout((() ->
    if $(this).scrollTop() is currentScrollTop
      $('header').removeClass('hidden') 
  ), animationDuration)

  currentScrollTop = $(this).scrollTop()
)

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

There's actually a way to do this without javascript.

If you set an <input>'s required selector to true, you can check if there's text in it with the CSS :valid tag.

References:

MDN Docs
CSS Tricks

_x000D_
_x000D_
input {
  background: red;
}

input:valid {
  background: lightgreen;
}
_x000D_
<input type="text" required>
_x000D_
_x000D_
_x000D_

PHP's array_map including keys

By "manual loop" I meant write a custom function that uses foreach. This returns a new array like array_map does because the function's scope causes $array to be a copy—not a reference:

function map($array, callable $fn) {
  foreach ($array as $k => &$v) $v = call_user_func($fn, $k, $v);
  return $array;
}

Your technique using array_map with array_keys though actually seems simpler and is more powerful because you can use null as a callback to return the key-value pairs:

function map($array, callable $fn = null) {
  return array_map($fn, array_keys($array), $array);
}

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

Get just the filename from a path in a Bash script

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns test.old.img like basename.

This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns test.old.

And following statement gives the full path like dirname command.

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns /opt/datastores/sda2

How To Make Circle Custom Progress Bar in Android

A very useful lib for custom progress bar in android.

In your layout file

<com.lylc.widget.circularprogressbar.example.CircularProgressBar
android:id="@+id/mycustom_progressbar"
.
.
.
 />

and Java file

CircularProgressBar progressBar = (CircularProgressBar) findViewById(R.id.mycustom_progressbar);
progressBar.setTitle("Circular Progress Bar");

Does Python have a ternary conditional operator?

is_spacial=True if gender = "Female" else (True if age >= 65 else False)

**

it can be nested as your need. best of luck

**

Loop through all the files with a specific extension

No fancy tricks needed:

for i in *.java; do
    [ -f "$i" ] || break
    ...
done

The guard ensures that if there are no matching files, the loop will exit without trying to process a non-existent file name *.java. In bash (or shells supporting something similar), you can use the nullglob option to simply ignore a failed match and not enter the body of the loop.

shopt -s nullglob
for i in *.java; do
    ...
done