Programs & Examples On #Constructor overloading

Constructor overloading is used to increase the flexibility of a class by having alternative constructors for a single class. Having more than one way of initializing objects can be achieved using overloading constructors.

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

Constructor overloading in Java - best practice

While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.

public class Simple {

    public Simple() {
        this(null);
    }

    public Simple(Resource r) {
        this(r, null);
    }

    public Simple(Resource r1, Resource r2) {
        // Guard statements, initialize resources or throw exceptions if
        // the resources are wrong
        if (r1 == null) {
            r1 = new Resource();
        }
        if (r2 == null) {
            r2 = new Resource();
        }

        // do whatever with resources
    }

}

From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:

Make a parameter class

public class SimpleParams {
    Resource r1;
    Resource r2;
    // Imagine there are setters and getters here but I'm too lazy 
    // to write it out. you can make it the parameter class 
    // "immutable" if you don't have setters and only set the 
    // resources through the SimpleParams constructor
}

The constructor in Simple only either needs to split the SimpleParams parameter:

public Simple(SimpleParams params) {
    this(params.getR1(), params.getR2());
}

…or make SimpleParams an attribute:

public Simple(Resource r1, Resource r2) {
    this(new SimpleParams(r1, r2));
}

public Simple(SimpleParams params) {
    this.params = params;
}

Make a factory class

Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:

public interface ResourceFactory {
    public Resource createR1();
    public Resource createR2();
}

The constructor is then done in the same manner as with the parameter class:

public Simple(ResourceFactory factory) {
    this(factory.createR1(), factory.createR2());
} 

Make a combination of both

Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple class that they're used the same way.

Write to .txt file?

Well, you need to first get a good book on C and understand the language.

FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
   return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

How can I do SELECT UNIQUE with LINQ?

Using query comprehension syntax you could achieve the orderby as follows:

var uniqueColors = (from dbo in database.MainTable
                    where dbo.Property
                    orderby dbo.Color.Name ascending
                    select dbo.Color.Name).Distinct();

Simplest way to detect keypresses in javascript

Don't over complicate.

  document.addEventListener('keydown', logKey);
    function logKey(e) {
      if (`${e.code}` == "ArrowRight") {
        //code here
      }
          if (`${e.code}` == "ArrowLeft") {
        //code here
      }
          if (`${e.code}` == "ArrowDown") {
        //code here
      }
          if (`${e.code}` == "ArrowUp") {
        //code here
      }
    }

Git Cherry-Pick and Conflicts

Do, I need to resolve all the conflicts before proceeding to next cherry -pick

Yes, at least with the standard git setup. You cannot cherry-pick while there are conflicts.

Furthermore, in general conflicts get harder to resolve the more you have, so it's generally better to resolve them one by one.

That said, you can cherry-pick multiple commits at once, which would do what you are asking for. See e.g. How to cherry-pick multiple commits . This is useful if for example some commits undo earlier commits. Then you'd want to cherry-pick all in one go, so you don't have to resolve conflicts for changes that are undone by later commits.

Further, is it suggested to do cherry-pick or branch merge in this case?

Generally, if you want to keep a feature branch up to date with main development, you just merge master -> feature branch. The main advantage is that a later merge feature branch -> master will be much less painful.

Cherry-picking is only useful if you must exclude some changes in master from your feature branch. Still, this will be painful so I'd try to avoid it.

How to fill OpenCV image with one solid color?

color=(200, 100, 255) # sample of a color 
img = np.full((100, 100, 3), color, np.uint8)

Combining two expressions (Expression<Func<T, bool>>)

Nothing new here but married this answer with this answer and slightly refactored it so that even I understand what's going on:

public static class ExpressionExtensions
{
    public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
    {
        ParameterExpression parameter1 = expr1.Parameters[0];
        var visitor = new ReplaceParameterVisitor(expr2.Parameters[0], parameter1);
        var body2WithParam1 = visitor.Visit(expr2.Body);
        return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, body2WithParam1), parameter1);
    }

    private class ReplaceParameterVisitor : ExpressionVisitor
    {
        private ParameterExpression _oldParameter;
        private ParameterExpression _newParameter;

        public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
        {
            _oldParameter = oldParameter;
            _newParameter = newParameter;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if (ReferenceEquals(node, _oldParameter))
                return _newParameter;

            return base.VisitParameter(node);
        }
    }
}

PHP function overloading

<?php

    class abs
    {
        public function volume($arg1=null, $arg2=null, $arg3=null)
        {   
            if($arg1 == null && $arg2 == null && $arg3 == null)
        {
            echo "function has no arguments. <br>";
        }

        else if($arg1 != null && $arg2 != null && $arg3 != null)
            {
            $volume=$arg1*$arg2*$arg3;
            echo "volume of a cuboid ".$volume ."<br>";
            }
            else if($arg1 != null && $arg2 != null)
            {
            $area=$arg1*$arg2;
            echo "area of square  = " .$area ."<br>";
            }
            else if($arg1 != null)
            {
            $volume=$arg1*$arg1*$arg1; 
            echo "volume of a cube = ".$volume ."<br>";
            }


        }


    }

    $obj=new abs();
    echo "For no arguments. <br>";
    $obj->volume();
    echo "For one arguments. <br>";
    $obj->volume(3);
    echo "For two arguments. <br>";
    $obj->volume(3,4);
    echo "For three arguments. <br>";
    $obj->volume(3,4,5);
    ?>

How to create timer in angular2

If you look to run a method on ngOnInit you could do something like this:

import this 2 libraries from RXJS:

import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";

Then declare timer and private subscription, example:

timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;

Last but not least run method when timer stops

ngOnInit() {
  this.subscription = this.timer.subscribe(ticks=> {
    this.populatecombobox();  //example calling a method that populates a combobox
    this.subscription.unsubscribe();  //you need to unsubscribe or it will run infinite times
  });
}

That's all, Angular 5

Proper way to rename solution (and directories) in Visual Studio

To rename a website:

http://www.c-sharpcorner.com/Blogs/46334/rename-website-project-in-visual-studio-2013.aspx

locate and edit IISExpress's applicationhost.config, found here: C:\Users{username}\Documents\IISExpress\config

Windows batch: call more than one command in a FOR loop?

SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)).

A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.

FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF

:loopbody
ECHO %1
DEL %1
GOTO :EOF

Bootstrap 3 - jumbotron background image effect

Example: http://bootply.com/103783

One way to achieve this is using a position:fixed container for the background image and place it outside of the .jumbotron. Make the bg container the same height as the .jumbotron and center the background image:

background: url('/assets/example/...jpg') no-repeat center center;

CSS

.bg {
  background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
  position: fixed;
  width: 100%;
  height: 350px; /*same height as jumbotron */
  top:0;
  left:0;
  z-index: -1;
}

.jumbotron {
  margin-bottom: 0px;
  height: 350px;
  color: white;
  text-shadow: black 0.3em 0.3em 0.3em;
  background:transparent;
}

Then use jQuery to decrease the height of the .jumbtron as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.

JavaScript

var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
    var scrolled = $(window).scrollTop();
    $('.bg').css('height', (jumboHeight-scrolled) + 'px');
}

$(window).scroll(function(e){
    parallax();
});

Demo

http://bootply.com/103783

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

Error handling in getJSON calls

Someone give Luciano these points :) I just tested his answer -had a similar question- and worked perfectly...

I even add my 50 cents:

.error(function(jqXHR, textStatus, errorThrown) {
        console.log("error " + textStatus);
        console.log("incoming Text " + jqXHR.responseText);
    })

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

These issue arise generally due to mismatch between @ngx-translate/core version and Angular .Before installing check compatible version of corresponding ngx_trnalsate/Core, @ngx-translate/http-loader and Angular at https://www.npmjs.com/package/@ngx-translate/core

Eg: For Angular 6.X versions,

npm install @ngx-translate/core@10 @ngx-translate/http-loader@3 rxjs --save

Like as above, follow below command and rest of code part is common for all versions(Note: Version can obtain from( https://www.npmjs.com/package/@ngx-translate/core)

npm install @ngx-translate/core@version @ngx-translate/http-loader@version rxjs --save

Eclipse C++ : "Program "g++" not found in PATH"

For me it got fixed with:

Go to: Window -> Preferences -> C/C++ -> Build -> Environment

Then press "Add..."

Name: MINGW_HOME

Value: C:\MinGW (yours might be different if you choose a custom path)

Hit "Apply and Close"

Now, it shoud work if you did everything correctly

allowing only alphabets in text box using java script

You can use HTML5 pattern attribute to do this:

<form>
    <input type='text' pattern='[A-Za-z\\s]*'/>
</form>

If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.

Convert string with comma to integer

String count = count.replace(",", "");

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

go to config/environments/test.rb

Rails.application.routes.default_url_options[:host] = 'localhost:3000'

How to set custom favicon in Express?

The code listed below works:

var favicon = require('serve-favicon');

app.use(favicon(__dirname + '/public/images/favicon.ico'));

Just make sure to refresh your browser or clear your cache.

How to hide app title in android?

use

<activity android:name=".ActivityName" 
          android:theme="@android:style/Theme.NoTitleBar">

What is the "double tilde" (~~) operator in JavaScript?

The diffrence is very simple:

Long version

If you want to have better readability, use Math.floor. But if you want to minimize it, use tilde ~~.

There are a lot of sources on the internet saying Math.floor is faster, but sometimes ~~. I would not recommend you think about speed because it is not going to be noticed when running the code. Maybe in tests etc, but no human can see a diffrence here. What would be faster is to use ~~ for a faster load time.

Short version

~~ is shorter/takes less space. Math.floor improves the readability. Sometimes tilde is faster, sometimes Math.floor is faster, but it is not noticeable.

How do I read from parameters.yml in a controller in symfony2?

In Symfony 4.3.1 I use this:

services.yaml

HTTP_USERNAME: 'admin'
HTTP_PASSWORD: 'password123'

FrontController.php

$username = $this->container->getParameter('HTTP_USERNAME');
$password = $this->container->getParameter('HTTP_PASSWORD');

What is the "hasClass" function with plain JavaScript?

You can check whether element.className matches /\bthatClass\b/.
\b matches a word break.

Or, you can use jQuery's own implementation:

var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 ) 

To answer your more general question, you can look at jQuery's source code on github or at the source for hasClass specifically in this source viewer.

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

Returning value from Thread

What you are looking for is probably the Callable<V> interface in place of Runnable, and retrieving the value with a Future<V> object, which also lets you wait until the value has been computed. You can achieve this with an ExecutorService, which you can get from Executors.newSingleThreadExecutor() .

public void test() {
    int x;
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Integer> result = es.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            // the other thread
            return 2;
        }
    });
    try {
        x = result.get();
    } catch (Exception e) {
        // failed
    }
    es.shutdown();
}

Importing Excel into a DataTable Quickly

In case anyone else is using EPPlus. This implementation is pretty naive, but there are comments that draw attention to such. If you were to layer one more method GetWorkbookAsDataSet() on top it would do what the OP is asking for.

    /// <summary>
    /// Assumption: Worksheet is in table format with no weird padding or blank column headers.
    /// 
    /// Assertion: Duplicate column names will be aliased by appending a sequence number (eg. Column, Column1, Column2)
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    public static DataTable GetWorksheetAsDataTable(ExcelWorksheet worksheet)
    {
        var dt = new DataTable(worksheet.Name);
        dt.Columns.AddRange(GetDataColumns(worksheet).ToArray());
        var headerOffset = 1; //have to skip header row
        var width = dt.Columns.Count;
        var depth = GetTableDepth(worksheet, headerOffset);
        for (var i = 1; i <= depth; i++)
        {
            var row = dt.NewRow();
            for (var j = 1; j <= width; j++)
            {
                var currentValue = worksheet.Cells[i + headerOffset, j].Value;

                //have to decrement b/c excel is 1 based and datatable is 0 based.
                row[j - 1] = currentValue == null ? null : currentValue.ToString();
            }

            dt.Rows.Add(row);
        }

        return dt;
    }

    /// <summary>
    /// Assumption: There are no null or empty cells in the first column
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    private static int GetTableDepth(ExcelWorksheet worksheet, int headerOffset)
    {
        var i = 1;
        var j = 1;
        var cellValue = worksheet.Cells[i + headerOffset, j].Value;
        while (cellValue != null)
        {
            i++;
            cellValue = worksheet.Cells[i + headerOffset, j].Value;
        }

        return i - 1; //subtract one because we're going from rownumber (1 based) to depth (0 based)
    }

    private static IEnumerable<DataColumn> GetDataColumns(ExcelWorksheet worksheet)
    {
        return GatherColumnNames(worksheet).Select(x => new DataColumn(x));
    }

    private static IEnumerable<string> GatherColumnNames(ExcelWorksheet worksheet)
    {
        var columns = new List<string>();

        var i = 1;
        var j = 1;
        var columnName = worksheet.Cells[i, j].Value;
        while (columnName != null)
        {
            columns.Add(GetUniqueColumnName(columns, columnName.ToString()));
            j++;
            columnName = worksheet.Cells[i, j].Value;
        }

        return columns;
    }

    private static string GetUniqueColumnName(IEnumerable<string> columnNames, string columnName)
    {
        var colName = columnName;
        var i = 1;
        while (columnNames.Contains(colName))
        {
            colName = columnName + i.ToString();
            i++;
        }

        return colName;
    }

Does Python support short-circuiting?

Short-circuiting behavior in operator and, or:

Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.

>>> def fun(i):
...     print "executed"
...     return i
... 

One can observe the Python's short-circuiting behavior of and, or operators in the following example:

>>> fun(1)
executed
1
>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
1
>>> 1 and fun(1)   # fun(1) called and "executed" printed 
executed
1
>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 
0

Note: The following values are considered by the interpreter to mean false:

        False    None    0    ""    ()    []     {}

Short-circuiting behavior in function: any(), all():

Python's any() and all() functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.

The function any() checks if any element is True. It stops executing as soon as a True is encountered and returns True.

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])   
executed                               # bool(0) = False
executed                               # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True

The function all() checks all elements are True and stops executing as soon as a False is encountered:

>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False

Short-circuiting behavior in Chained Comparison:

Additionally, in Python

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3)    # 5 < 6 is True 
executed              # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7)   # 4 <= 6 is True  
executed              # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3    # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False

Edit:
One more interesting point to note :- Logical and, or operators in Python returns an operand's value instead of a Boolean (True or False). For example:

Operation x and y gives the result if x is false, then x, else y

Unlike in other languages e.g. &&, || operators in C that return either 0 or 1.

Examples:

>>> 3 and 5    # Second operand evaluated and returned 
5                   
>>> 3  and ()
()
>>> () and 5   # Second operand NOT evaluated as first operand () is  false
()             # so first operand returned 

Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples:

>>> 2 or 5    # left most operand bool(2) == True
2    
>>> 0 or 5    # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()

So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'. You could use an if statement, but you could also state things very succinctly:

In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name: 

In [172]: name
Out[172]: '<Unknown>'

In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>' is assigned to name.

How to debug when Kubernetes nodes are in 'Not Ready' state

First, describe nodes and see if it reports anything:

$ kubectl describe nodes

Look for conditions, capacity and allocatable:

Conditions:
  Type              Status
  ----              ------
  OutOfDisk         False
  MemoryPressure    False
  DiskPressure      False
  Ready             True
Capacity:
 cpu:       2
 memory:    2052588Ki
 pods:      110
Allocatable:
 cpu:       2
 memory:    1950188Ki
 pods:      110

If everything is alright here, SSH into the node and observe kubelet logs to see if it reports anything. Like certificate erros, authentication errors etc.

If kubelet is running as a systemd service, you can use

$ journalctl -u kubelet

Android changing Floating Action Button color

Thanks to autocomplete. I got lucky after a few hit and trials:

    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:backgroundTint="@color/whicheverColorYouLike"

-- or -- (both are basically the same thing)

    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:backgroundTint="@color/whicheverColorYouLike"

This worked for me on API Version 17 with design library 23.1.0.

What's the best way to add a drop shadow to my UIView

You can set shadow to your view from storyboard also

enter image description here

Clear MySQL query cache without restarting server

In my system (Ubuntu 12.04) I found RESET QUERY CACHE and even restarting mysql server not enough. This was due to memory disc caching.
After each query, I clean the disc cache in the terminal:

sync && echo 3 | sudo tee /proc/sys/vm/drop_caches

and then reset the query cache in mysql client:

RESET QUERY CACHE;

Cannot refer to a non-final variable inside an inner class defined in a different method

You cannot refer to non-final variables because Java Language Specification says so. From 8.1.3:
"Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final." Whole paragraph.
I can see only part of your code - according to me scheduling modification of local variables is a strange idea. Local variables cease to exist when you leave the function. Maybe static fields of a class would be better?

Sum the digits of a number

reduce(op.add,map(int,list(str(number))))

Test:

from datetime import datetime
number=49263985629356279356927356923569976549123548126856926293658923658923658923658972365297865987236523786598236592386592386589236592365293865923876592385623987659238756239875692387659238756239875692856239856238563286598237592875498259826592356923659283756982375692835692385653418923564912354687123548712354827354827354823548723548235482735482354827354823548235482354823548235482735482735482735482354823548235489235648293548235492185348235481235482354823548235482354823548235482354823548234



startTime = datetime.now()

for _ in  range(0,100000) :
    out=reduce(op.add,map(int,list(str(number))))

now=datetime.now()
runningTime=(now - startTime)

print ("Running time:%s" % runningTime)
print(out)

Running time:0:00:13.122560 2462

react-router (v4) how to go back?

For use with React Router v4 and a functional component anywhere in the dom-tree.

import React from 'react';
import { withRouter } from 'react-router-dom';

const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;

export default withRouter(GoBack);

How does functools partial do what it does?

Roughly, partial does something like this (apart from keyword args support etc):

def partial(func, *part_args):
    def wrapper(*extra_args):
        args = list(part_args)
        args.extend(extra_args)
        return func(*args)

    return wrapper

So, by calling partial(sum2, 4) you create a new function (a callable, to be precise) that behaves like sum2, but has one positional argument less. That missing argument is always substituted by 4, so that partial(sum2, 4)(2) == sum2(4, 2)

As for why it's needed, there's a variety of cases. Just for one, suppose you have to pass a function somewhere where it's expected to have 2 arguments:

class EventNotifier(object):
    def __init__(self):
        self._listeners = []

    def add_listener(self, callback):
        ''' callback should accept two positional arguments, event and params '''
        self._listeners.append(callback)
        # ...

    def notify(self, event, *params):
        for f in self._listeners:
            f(event, params)

But a function you already have needs access to some third context object to do its job:

def log_event(context, event, params):
    context.log_event("Something happened %s, %s", event, params)

So, there are several solutions:

A custom object:

class Listener(object):
   def __init__(self, context):
       self._context = context

   def __call__(self, event, params):
       self._context.log_event("Something happened %s, %s", event, params)


 notifier.add_listener(Listener(context))

Lambda:

log_listener = lambda event, params: log_event(context, event, params)
notifier.add_listener(log_listener)

With partials:

context = get_context()  # whatever
notifier.add_listener(partial(log_event, context))

Of those three, partial is the shortest and the fastest. (For a more complex case you might want a custom object though).

Is there a "theirs" version of "git merge -s ours"?

A possible and tested solution for merging branchB into our checked-out branchA:

# in case branchA is not our current branch
git checkout branchA

# make merge commit but without conflicts!!
# the contents of 'ours' will be discarded later
git merge -s ours branchB    

# make temporary branch to merged commit
git branch branchTEMP         

# get contents of working tree and index to the one of branchB
git reset --hard branchB

# reset to our merged commit but 
# keep contents of working tree and index
git reset --soft branchTEMP

# change the contents of the merged commit
# with the contents of branchB
git commit --amend

# get rid off our temporary branch
git branch -D branchTEMP

# verify that the merge commit contains only contents of branchB
git diff HEAD branchB

To automate it you can wrap it into a script using branchA and branchB as arguments.

This solution preserves the first and second parent of the merge commit, just as you would expect of git merge -s theirs branchB.

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

How to call a method in another class of the same package?

From the Notes of Fred Swartz (fredosaurus) :

There are two types of methods.

  • Instance methods are associated with an object and use the instance variables of that object. This is the default.

  • Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class.

Qualifying a static call

From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");

A static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.

Example

Here is a typical static method:

class MyUtils {
    . . .
    //================================================= mean
    public static double mean(int[] p) {
        int sum = 0;  // sum of all the elements
        for (int i=0; i<p.length; i++) {
            sum += p[i];
        }
        return ((double)sum) / p.length;
    }//endmethod mean
    . . .
}

The only data this method uses or changes is from parameters (or local variables of course).

Why declare a method static

The above mean() method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.

  • Documentation. Anyone seeing that a method is static will know how to call it (see below). Similarly, any programmer looking at the code will know that a static method can't interact with instance variables, which makes reading and debugging easier.
  • Efficiency. A compiler will usually produce slightly more efficient code because no implicit object parameter has to be passed to the method.

Calling static methods

There are two cases.

Called from within the same class

Just write the static method name. Eg:

// Called from inside the MyUtils class
double avgAtt = mean(attendance);

Called from outside the class

If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg:

// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance); 

If an object is specified before it, the object value will be ignored and the the class of the object will be used.

Accessing static variables

Altho a static method can't access instance variables, it can access static variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI or Color.RED. They are qualified with the class name, so you know they are static. Any method, static or not, can access static variables. Instance variables can be accessed only by instance methods.

Alternate Call

What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.

GetElementByID - Multiple IDs

Dunno if something like this works in js, in PHP and Python which i use quite often it is possible. Maybe just use for loop like:

function doStuff(){
    for(i=1; i<=4; i++){
        var i = document.getElementById("myCiricle"+i);
    }
}

Failed to connect to mailserver at "localhost" port 25

You need to be running a mail server locally. If this is Unix, enable sendmail If this is Windows install the Simple Mail Transfer Server (not sure if the name is correct) component of IIs. E.g. for windows 2003 follow this: http://msdn.microsoft.com/en-us/library/8b83ac7t.aspx

How to convert float value to integer in php?

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

Multiple queries executed in java in single statement

Based on my testing, the correct flag is "allowMultiQueries=true"

How to get param from url in angular 4?

use paramMap

This will provide param names and their values

//http://localhost:4200/categories/1
//{ path: 'categories/:category', component: CategoryComponent },

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) { }

ngOnInit() {

  this.route.paramMap.subscribe(params => {
        console.log(params)
  })
}

Clear form after submission with jQuery

Better way to reset your form with jQuery is Simply trigger a reset event on your form.

$("#btn1").click(function () {
        $("form").trigger("reset");
    });

Need table of key codes for android and presenter

They are ASCII dec codes. A full table can be found here.

Does Ruby have a string.startswith("abc") built in method?

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Further reading for any of the topics here: The Definitive Guide to Linux System Calls


I verified these using GNU Assembler (gas) on Linux.

Kernel Interface

x86-32 aka i386 Linux System Call convention:

In x86-32 parameters for Linux system call are passed using registers. %eax for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.

The return value is in %eax. All other registers (including EFLAGS) are preserved across the int $0x80.

I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.

If there are more than six arguments, %ebx must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.

For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80: Hello, world in assembly language with Linux system calls?

There is a faster way to make 32-bit system calls: using sysenter. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80. You should normally call into the vDSO instead of using sysenter directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter, and everything else to do with system calls.)

x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:

Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80

http://www.int80h.org/bsdasm/#default-calling-convention


x86-64 Linux System Call convention:

(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)

Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)

Here is the snippet from this section:

  1. User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
  2. A system-call is done via the syscall instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.
  3. The number of the syscall has to be passed in register %rax.
  4. System-calls are limited to six arguments, no argument is passed directly on the stack.
  5. Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.
  6. Only values of class INTEGER or class MEMORY are passed to the kernel.

Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)

This 32-bit int $0x80 ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.

User Interface: function calling

x86-32 Function Calling convention:

In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.

Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp before a call, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double or something.

Some other modern 32-bit systems still don't require more than 4 byte stack alignment.


x86-64 System V user-space Function Calling convention:

x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).

In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.

For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:

Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used

So %rdi, %rsi, %rdx, %rcx, %r8 and %r9 are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call instruction should be given. The stack (%rsp) must be 16B-aligned when call executes.

If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)

The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)

Variadic functions (like printf) always need %al = the number of FP register args.

There are rules for when to pack structs into registers (rdx:rax on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.


Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.

Android Studio was unable to find a valid Jvm (Related to MAC OS)

I was able to get it to work by editing the info.plist changing 16* to 16+. Tried using the recommended method but that failed.

Is nested function a good approach when required by only one function?

Function In function python

def Greater(a,b):
    if a>b:
        return a
    return b

def Greater_new(a,b,c,d):
    return Greater(Greater(a,b),Greater(c,d))

print("Greater Number is :-",Greater_new(212,33,11,999))

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

  • Open Task Manager
  • Go to Details
  • Find and kill Skype... apps

Restart WampServer and it should work

How do you use the ? : (conditional) operator in JavaScript?

z = (x == y ? 1 : 2);

is equivalent to

if (x == y)
    z = 1;
else
    z = 2;

except, of course, it's shorter.

How to select all and copy in vim?

There are a few important informations missing from your question:

  • output of $ vim --version?
  • OS?
  • CLI or GUI?
  • local or remote?
  • do you use tmux? screen?

If your Vim was built with clipboard support, you are supposed to use the clipboard register like this, in normal mode:

gg"+yG

If your Vim doesn't have clipboard support, you can manage to copy text from Vim to your OS clipboard via other programs. This pretty much depends on your OS but you didn't say what it is so we can't really help.

However, if your Vim is crippled, the best thing to do is to install a proper build with clipboard support but I can't tell you how either because I don't know what OS you use.

edit

On debian based systems, the following command will install a proper Vim with clipboard, ruby, python… support.

$ sudo apt-get install vim-gnome

How to make sure that string is valid JSON using JSON.NET

Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:

public static bool IsValidJson<T>(this string strInput)
{
    if(string.IsNullOrWhiteSpace(strInput)) return false;

    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JsonConvert.DeserializeObject<T>(strInput);
            return true;
        }
        catch // not valid
        {             
            return false;
        }
    }
    else
    {
        return false;
    }
}

How to remove an element from the flow?

Another option is to set height: 0; overflow: visible; to an element, though it won't be really outside the flow and therefore may break margin collapsing.

How can I pad a value with leading zeros?

just wanted to make the comment (but i don't have enough points) that the highest voted answer fails with negative numbers and decimals

function padNumber(n,pad) {
    p = Math.pow(10,pad);
    a = Math.abs(n);
    g = (n<0);
    return (a < p) ?  ((g ? '-' : '') + (p+a).toString().substring(1)) : n;
}

padNumber( -31.235, 5);

"-00031.235"

python tuple to dict

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

Get difference between 2 dates in JavaScript?

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);

PostgreSQL column 'foo' does not exist

I also ran into this error when I was using Dapper and forgot to input a parameterized value.

To fix I had to ensure that the object passed in as a parameter had properties matching the parameterised values in the SQL string.

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Faced same problem after migrating to python 3. Apparently, MySQL-python is incompatible, so as per official django docs, installed mysqlclient using pip install mysqlclient on Mac. Note that there are some OS specific issues mentioned in docs.

Quoting from docs:

Prerequisites

You may need to install the Python and MySQL development headers and libraries like so:

sudo apt-get install python-dev default-libmysqlclient-dev # Debian / Ubuntu

sudo yum install python-devel mysql-devel # Red Hat / CentOS

brew install mysql-connector-c # macOS (Homebrew) (Currently, it has bug. See below)

On Windows, there are binary wheels you can install without MySQLConnector/C or MSVC.

Note on Python 3 : if you are using python3 then you need to install python3-dev using the following command :

sudo apt-get install python3-dev # debian / Ubuntu

sudo yum install python3-devel # Red Hat / CentOS

Note about bug of MySQL Connector/C on macOS

See also: https://bugs.mysql.com/bug.php?id=86971

Versions of MySQL Connector/C may have incorrect default configuration options that cause compilation errors when mysqlclient-python is installed. (As of November 2017, this is known to be true for homebrew's mysql-connector-c and official package)

Modification of mysql_config resolves these issues as follows.

Change

# on macOS, on or about line 112:
# Create options
libs="-L$pkglibdir"
libs="$libs -l "

to

# Create options
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

An improper ssl configuration may also create issues; see, e.g, brew info openssl for details on macOS.

Install from PyPI

pip install mysqlclient

NOTE: Wheels for Windows may be not released with source package. You should pin version in your requirements.txt to avoid trying to install newest source package.

Install from source

  1. Download source by git clone or zipfile.
  2. Customize site.cfg
  3. python setup.py install

How to remove padding around buttons in Android?

For me the problem turned out to be minHeight and minWidth on some of the Android themes.

On the Button element, add:

<Button android:minHeight="0dp" android:minWidth="0dp" ...

Or in your button's style:

<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>

AngularJS accessing DOM elements inside directive template

I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:

{
     template: '<div>' +
    '<div class="title">{{title}}</div>' +
    '<div class="body" ng-transclude></div>' +
    '</div>',

    link: function(scope, element, attrs) {
        // Title element
        var title = angular.element(element.children()[0]),
        // ...
    }
}

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How to check whether a string contains a substring in Ruby

If case is irrelevant, then a case-insensitive regular expression is a good solution:

'aBcDe' =~ /bcd/i  # evaluates as true

This will also work for multi-line strings.

See Ruby's Regexp class for more information.

How to get css background color on <tr> tag to span entire row

Try this:

    .rowhighlight > td { background: green;}

Python unittest passing arguments

Another method for those who really want to do this in spite of the correct remarks that you shouldn't:

import unittest

class MyTest(unittest.TestCase):

    def __init__(self, testName, extraArg):
        super(MyTest, self).__init__(testName)  # calling the super class init varies for different python versions.  This works for 2.7
        self.myExtraArg = extraArg

    def test_something(self):
        print(self.myExtraArg)

# call your test
suite = unittest.TestSuite()
suite.addTest(MyTest('test_something', extraArg))
unittest.TextTestRunner(verbosity=2).run(suite)

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

How can I make IntelliJ IDEA update my dependencies from Maven?

Apart from checking 'Import Maven projects automatically', make sure that settings.xml file from File > Settings > Maven > User Settings file exist, If doesn't exist then override and provide your settings.xml file path.

How to find a number in a string using JavaScript?

var str = "you can enter maximum 500 choices";
str.replace(/[^0-9]/g, "");
console.log(str); // "500"

Multi-statement Table Valued Function vs Inline Table Valued Function

In researching Matt's comment, I have revised my original statement. He is correct, there will be a difference in performance between an inline table valued function (ITVF) and a multi-statement table valued function (MSTVF) even if they both simply execute a SELECT statement. SQL Server will treat an ITVF somewhat like a VIEW in that it will calculate an execution plan using the latest statistics on the tables in question. A MSTVF is equivalent to stuffing the entire contents of your SELECT statement into a table variable and then joining to that. Thus, the compiler cannot use any table statistics on the tables in the MSTVF. So, all things being equal, (which they rarely are), the ITVF will perform better than the MSTVF. In my tests, the performance difference in completion time was negligible however from a statistics standpoint, it was noticeable.

In your case, the two functions are not functionally equivalent. The MSTV function does an extra query each time it is called and, most importantly, filters on the customer id. In a large query, the optimizer would not be able to take advantage of other types of joins as it would need to call the function for each customerId passed. However, if you re-wrote your MSTV function like so:

CREATE FUNCTION MyNS.GetLastShipped()
RETURNS @CustomerOrder TABLE
    (
    SaleOrderID    INT         NOT NULL,
    CustomerID      INT         NOT NULL,
    OrderDate       DATETIME    NOT NULL,
    OrderQty        INT         NOT NULL
    )
AS
BEGIN
    INSERT @CustomerOrder
    SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
    FROM Sales.SalesOrderHeader a 
        INNER JOIN Sales.SalesOrderHeader b
            ON a.SalesOrderID = b.SalesOrderID
        INNER JOIN Production.Product c 
            ON b.ProductID = c.ProductID
    WHERE a.OrderDate = (
                        Select Max(SH1.OrderDate)
                        FROM Sales.SalesOrderHeader As SH1
                        WHERE SH1.CustomerID = A.CustomerId
                        )
    RETURN
END
GO

In a query, the optimizer would be able to call that function once and build a better execution plan but it still would not be better than an equivalent, non-parameterized ITVS or a VIEW.

ITVFs should be preferred over a MSTVFs when feasible because the datatypes, nullability and collation from the columns in the table whereas you declare those properties in a multi-statement table valued function and, importantly, you will get better execution plans from the ITVF. In my experience, I have not found many circumstances where an ITVF was a better option than a VIEW but mileage may vary.

Thanks to Matt.

Addition

Since I saw this come up recently, here is an excellent analysis done by Wayne Sheffield comparing the performance difference between Inline Table Valued functions and Multi-Statement functions.

His original blog post.

Copy on SQL Server Central

Reading CSV file and storing values into an array

Here's a special case where one of data field has semicolon (";") as part of it's data in that case most of answers above will fail.

Solution it that case will be

string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
string[] fields = null;
List<string> lstFields;
string field;
bool quoteStarted = false;
foreach (string csvRow in csvRows)
{
    lstFields = new List<string>();
    field = "";
    for (int i = 0; i < csvRow.Length; i++)
    {
        string tmp = csvRow.ElementAt(i).ToString();
        if(String.Compare(tmp,"\"")==0)
        {
            quoteStarted = !quoteStarted;
        }
        if (String.Compare(tmp, ";") == 0 && !quoteStarted)
        {
            lstFields.Add(field);
            field = "";
        }
        else if (String.Compare(tmp, "\"") != 0)
        {
            field += tmp;
        }
    }
    if(!string.IsNullOrEmpty(field))
    {
        lstFields.Add(field);
        field = "";
    }
// This will hold values for each column for current row under processing
    fields = lstFields.ToArray(); 
}

How to add headers to OkHttp request interceptor?

If you are using Retrofit library then you can directly pass header to api request using @Header annotation without use of Interceptor. Here is example that shows how to add header to Retrofit api request.

@POST(apiURL)
void methodName(
        @Header(HeadersContract.HEADER_AUTHONRIZATION) String token,
        @Header(HeadersContract.HEADER_CLIENT_ID) String token,
        @Body TypedInput body,
        Callback<String> callback);

Hope it helps!

How can I install an older version of a package via NuGet?

I've used Xavier's answer quite a bit. I want to add that restricting the package version to a specified range is easy and useful in the latest versions of NuGet.

For example, if you never want Newtonsoft.Json to be updated past version 3.x.x in your project, change the corresponding package element in your packages.config file to look like this:

<package id="Newtonsoft.Json" version="3.5.8" allowedVersions="[3.0, 4.0)" targetFramework="net40" />

Notice the allowedVersions attribute. This will limit the version of that package to versions between 3.0 (inclusive) and 4.0 (exclusive). Then, when you do an Update-Package on the whole solution, you don't need to worry about that particular package being updated past version 3.x.x.

The documentation for this functionality is here.

How do I replace whitespaces with underscore?

Using the re module:

import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this

Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace as others have suggested.

Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

def self.search(query, page=1)
  query = "%#{query}%"
  name_match = arel_table[:name].matches(query)
  postal_match = arel_table[:postal_code].matches(query)
  where(name_match.or(postal_match)).page(page).per_page(5)
end

Loop through each cell in a range of cells when given a Range object

To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).

See the following for more discussion:

How do I properly clean up Excel interop objects?

To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).

A cleaner way to handle this is to query the spreadsheet using ADO:

http://technet.microsoft.com/en-us/library/ee692882.aspx

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

My problem ended up being that I did not understand the signtool options. I had provided the /n option with something that did not match my certificate. When I removed that it stopped complaining.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

When I have this problem it is because the client.config had its endpoints like:

 https://myserver/myservice.svc 

but the certificate was expecting

 https://myserver.mydomain.com/myservice.svc

Changing the endpoints to match the FQDN of the server resolves my problem. I know this is not the only cause of this problem.

Appending to an object

You should really go with the array of alerts suggestions, but otherwise adding to the object you mentioned would look like this:

alerts[3]={"app":"goodbyeworld","message":"cya"};

But since you shouldn't use literal numbers as names quote everything and go with

alerts['3']={"app":"goodbyeworld","message":"cya"};

or you can make it an array of objects.

Accessing it looks like

alerts['1'].app
=> "helloworld"

Maximum number of threads per process in Linux?

Depends on your system, just write a sample program [ by creating processes in a loop ] and check using ps axo pid,ppid,rss,vsz,nlwp,cmd. When it can no more create threads check nlwp count [ nlwp is the number threads ] voila you got your fool proof answer instead of going thru books

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

Please

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

If there will still be the same error after that, try to increase the value for the max_execution_time further more.

Why is Visual Studio 2010 not able to find/open PDB files?

For VS2013 users who find themselves here as I did:

Tools -> Options -> Debugging -> Symbols

You'll see that the Cache symbols in this directory: field is empty; you can either browse/enter the path yourself or just go ahead and click the Load all symbols button. An alert window will appear saying "Since you haven't selected a symbol-cache directory the default will be used". You'll now see C:\Users\XXXX\AppData\Local\Temp\SymbolCache in the previously empty path-field. Click Load all symbols a second time and you should be set. Hit ok, and just for the sake of diligence, clean and rebuild your solution.

PHP 7: Missing VCRUNTIME140.dll

If you've followed Adam's instructions and you're still getting this error make sure you've installed the right variants (x86 or x64).

I had VC14x64 with PHP7x86 and I still got this error. Changing PHP7 to x64 fixed it. It's easy to miss you accidentally installed the wrong version.

The pipe ' ' could not be found angular2 custom pipe

Make sure you are not facing a "cross module" problem

If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.

In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.

I have declared a that the component in which you are using the pipe is

the Pipe Module

 import { NgModule }      from '@angular/core';
 import { myDateFormat }          from '../directives/myDateFormat';

 @NgModule({
     imports:        [],
     declarations:   [myDateFormat],
     exports:        [myDateFormat],
 })

 export class PipeModule {

   static forRoot() {
      return {
          ngModule: PipeModule,
          providers: [],
      };
   }
 } 

Usage in another module (e.g. app.module)

  // Import APPLICATION MODULES
  ...
  import { PipeModule }    from './tools/PipeModule';

  @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

Reading a resource file from within jar

If you are using spring, then you can use the the following method to read file from src/main/resources:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.core.io.ClassPathResource;

  public String readFileToString(String path) throws IOException {

    StringBuilder resultBuilder = new StringBuilder("");
    ClassPathResource resource = new ClassPathResource(path);

    try (
        InputStream inputStream = resource.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

      String line;

      while ((line = bufferedReader.readLine()) != null) {
        resultBuilder.append(line);
      }

    }

    return resultBuilder.toString();
  }

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

How to get current available GPUs in tensorflow?

Use this way and check all parts :

from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds


version = tf.__version__
executing_eagerly = tf.executing_eagerly()
hub_version = hub.__version__
available = tf.config.experimental.list_physical_devices("GPU")

print("Version: ", version)
print("Eager mode: ", executing_eagerly)
print("Hub Version: ", h_version)
print("GPU is", "available" if avai else "NOT AVAILABLE")

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

How can I connect to a Tor hidden service using cURL in PHP?

You need to set option CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7:

curl_setopt($ch, CURLOPT_PROXYTYPE, 7);

How do I find files with a path length greater than 260 characters in Windows?

From http://www.powershellmagazine.com/2012/07/24/jaap-brassers-favorite-powershell-tips-and-tricks/:

Get-ChildItem –Force –Recurse –ErrorAction SilentlyContinue –ErrorVariable AccessDenied

the first part just iterates through this and sub-folders; using -ErrorVariable AccessDenied means push the offending items into the powershell variable AccessDenied.

You can then scan through the variable like so

$AccessDenied |
Where-Object { $_.Exception -match "must be less than 260 characters" } |
ForEach-Object { $_.TargetObject }

If you don't care about these files (may be applicable in some cases), simply drop the -ErrorVariable AccessDenied part.

Get last record of a table in Postgres

Use the following

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

Shortcut key for commenting out lines of Python code in Spyder

Yes, there is a shortcut for commenting out lines in Python 3.6 (Spyder).

For Single Line Comment, you can use Ctrl+1. It will look like this #This is a sample piece of code

For multi-line comments, you can use Ctrl+4. It will look like this

#============= \#your piece of code \#some more code \#=============

Note : \ represents that the code is carried to another line.

What is Java String interning?

JLS

JLS 7 3.10.5 defines it and gives a practical example:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Example 3.10.5-1. String Literals

The program consisting of the compilation unit (§7.3):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }

and the compilation unit:

package other;
public class Other { public static String hello = "Hello"; }

produces the output:

true true true true false true

JVMS

JVMS 7 5.1 says says that interning is implemented magically and efficiently with a dedicated CONSTANT_String_info struct (unlike most other objects which have more generic representations):

A string literal is a reference to an instance of class String, and is derived from a CONSTANT_String_info structure (§4.4.3) in the binary representation of a class or interface. The CONSTANT_String_info structure gives the sequence of Unicode code points constituting the string literal.

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of code points) must refer to the same instance of class String (JLS §3.10.5). In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal. Thus, the following expression must have the value true:

("a" + "b" + "c").intern() == "abc"

To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.

  • If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.

  • Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.

Bytecode

Let's decompile some OpenJDK 7 bytecode to see interning in action.

If we decompile:

public class StringPool {
    public static void main(String[] args) {
        String a = "abc";
        String b = "abc";
        String c = new String("abc");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == c);
    }
}

we have on the constant pool:

#2 = String             #32   // abc
[...]
#32 = Utf8               abc

and main:

 0: ldc           #2          // String abc
 2: astore_1
 3: ldc           #2          // String abc
 5: astore_2
 6: new           #3          // class java/lang/String
 9: dup
10: ldc           #2          // String abc
12: invokespecial #4          // Method java/lang/String."<init>":(Ljava/lang/String;)V
15: astore_3
16: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_2
27: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_1
34: aload_3
35: if_acmpne     42
38: iconst_1
39: goto          43
42: iconst_0
43: invokevirtual #7          // Method java/io/PrintStream.println:(Z)V

Note how:

  • 0 and 3: the same ldc #2 constant is loaded (the literals)
  • 12: a new string instance is created (with #2 as argument)
  • 35: a and c are compared as regular objects with if_acmpne

The representation of constant strings is quite magic on the bytecode:

and the JVMS quote above seems to say that whenever the Utf8 pointed to is the same, then identical instances are loaded by ldc.

I have done similar tests for fields, and:

  • static final String s = "abc" points to the constant table through the ConstantValue Attribute
  • non-final fields don't have that attribute, but can still be initialized with ldc

Conclusion: there is direct bytecode support for the string pool, and the memory representation is efficient.

Bonus: compare that to the Integer pool, which does not have direct bytecode support (i.e. no CONSTANT_String_info analogue).

What is the most accurate way to retrieve a user's correct IP address in PHP?

/**
 * Sanitizes IPv4 address according to Ilia Alshanetsky's book
 * "php|architect?s Guide to PHP Security", chapter 2, page 67.
 *
 * @param string $ip An IPv4 address
 */
public static function sanitizeIpAddress($ip = '')
{
if ($ip == '')
    {
    $rtnStr = '0.0.0.0';
    }
else
    {
    $rtnStr = long2ip(ip2long($ip));
    }

return $rtnStr;
}

//---------------------------------------------------

/**
 * Returns the sanitized HTTP_X_FORWARDED_FOR server variable.
 *
 */
public static function getXForwardedFor()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
    $rtnStr = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
elseif (isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR']))
    {
    $rtnStr = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'];
    }
elseif (getenv('HTTP_X_FORWARDED_FOR'))
    {
    $rtnStr = getenv('HTTP_X_FORWARDED_FOR');
    }
else
    {
    $rtnStr = '';
    }

// Sanitize IPv4 address (Ilia Alshanetsky):
if ($rtnStr != '')
    {
    $rtnStr = explode(', ', $rtnStr);
    $rtnStr = self::sanitizeIpAddress($rtnStr[0]);
    }

return $rtnStr;
}

//---------------------------------------------------

/**
 * Returns the sanitized REMOTE_ADDR server variable.
 *
 */
public static function getRemoteAddr()
{
if (isset($_SERVER['REMOTE_ADDR']))
    {
    $rtnStr = $_SERVER['REMOTE_ADDR'];
    }
elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
    {
    $rtnStr = $HTTP_SERVER_VARS['REMOTE_ADDR'];
    }
elseif (getenv('REMOTE_ADDR'))
    {
    $rtnStr = getenv('REMOTE_ADDR');
    }
else
    {
    $rtnStr = '';
    }

// Sanitize IPv4 address (Ilia Alshanetsky):
if ($rtnStr != '')
    {
    $rtnStr = explode(', ', $rtnStr);
    $rtnStr = self::sanitizeIpAddress($rtnStr[0]);
    }

return $rtnStr;
}

//---------------------------------------------------

/**
 * Returns the sanitized remote user and proxy IP addresses.
 *
 */
public static function getIpAndProxy()
{
$xForwarded = self::getXForwardedFor();
$remoteAddr = self::getRemoteAddr();

if ($xForwarded != '')
    {
    $ip    = $xForwarded;
    $proxy = $remoteAddr;
    }
else
    {
    $ip    = $remoteAddr;
    $proxy = '';
    }

return array($ip, $proxy);
}

How to efficiently concatenate strings in go

In Go 1.10+ there is strings.Builder, here.

A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use.


Example

It's almost the same with bytes.Buffer.

package main

import (
    "strings"
    "fmt"
)

func main() {
    // ZERO-VALUE:
    //
    // It's ready to use from the get-go.
    // You don't need to initialize it.
    var sb strings.Builder

    for i := 0; i < 1000; i++ {
        sb.WriteString("a")
    }

    fmt.Println(sb.String())
}

Click to see this on the playground.


Supported Interfaces

StringBuilder's methods are being implemented with the existing interfaces in mind. So that you can switch to the new Builder type easily in your code.


Differences from bytes.Buffer

  • It can only grow or reset.

  • It has a copyCheck mechanism built-in that prevents accidentially copying it:

    func (b *Builder) copyCheck() { ... }

  • In bytes.Buffer, one can access the underlying bytes like this: (*Buffer).Bytes().

    • strings.Builder prevents this problem.
    • Sometimes, this is not a problem though and desired instead.
    • For example: For the peeking behavior when the bytes are passed to an io.Reader etc.
  • bytes.Buffer.Reset() rewinds and reuses the underlying buffer whereas the strings.Builder.Reset() does not, it detaches the buffer.


Note

  • Do not copy a StringBuilder value as it caches the underlying data.
  • If you want to share a StringBuilder value, use a pointer to it.

Check out its source code for more details, here.

Make child visible outside an overflow:hidden parent

Neither of the posted answers worked for me. Setting position: absolute for the child element did work however.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

function deltree_cat($folder)
{
    if (is_dir($folder))
    {
             $handle = opendir($folder);
             while ($subfile = readdir($handle))
             {
                     if ($subfile == '.' or $subfile == '..') continue;
                     if (is_file($subfile)) unlink("{$folder}/{$subfile}");
                     else deltree_cat("{$folder}/{$subfile}");
             }
             closedir($handle);
             rmdir ($folder);
     }
     else
     {
        unlink($folder);
     }
}

Gradle Build Android Project "Could not resolve all dependencies" error

  1. Install android sdk manager
  2. check if building tools installed. install api 23.
  3. from the Android SDK Manager download the 'Android Support Repository'
  4. remove cordova-plugin-android-support-v4
  5. build

How to destroy JWT Tokens on logout?

On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
    .then((token)=>{
            // your code
    })
    .catch((error)=>{
            // error handling
    });

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -

jwtr.destroy(token)

Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

Can I stop 100% Width Text Boxes from extending beyond their containers?

What you could do is to remove the default "extras" on the input:

input.wide {display:block; width:100%;padding:0;border-width:0}

This will keep the input inside its container. Now if you do want the borders, wrap the input in a div, with the borders set on the div (that way you can remove the display:block from the input too). Something like:

<div style="border:1px solid gray;">
 <input type="text" class="wide" />
</div>

Edit: Another option is to, instead of removing the style from the input, compensate for it in the wrapped div:

input.wide {width:100%;}

<div style="padding-right:4px;padding-left:1px;margin-right:2px">
  <input type="text" class="wide" />
</div>

This will give you somewhat different results in different browsers, but they will not overlap the container. The values in the div depend on how large the border is on the input and how much space you want between the input and the border.

Define global constants

All solutions seems to be complicated. I'm looking for the simplest solution for this case and I just want to use constants. Constants are simple. Is there anything which speaks against the following solution?

app.const.ts

'use strict';

export const dist = '../path/to/dist/';

app.service.ts

import * as AppConst from '../app.const'; 

@Injectable()
export class AppService {

    constructor (
    ) {
        console.log('dist path', AppConst.dist );
    }

}

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

Change color of Back button in navigation bar

This code changes the arrow color

self.navigationController.navigationBar.tintColor = UIColor.whiteColor();

If this does not work, use the code below:

self.navigationBar.barStyle = UIBarStyle.Black
self.navigationBar.tintColor = UIColor.whiteColor()

Swift 3 Notes

UIColor.whiteColor() and similar have been simplified to UIColor.white

Also, many previously implicit optionals have been changed to explicit, so you might need:

self.navigationController?.navigationBar =

What is the difference between varchar and varchar2 in Oracle?

Currently, they are the same. but previously

  1. Somewhere on the net, I read that,

VARCHAR is reserved by Oracle to support distinction between NULL and empty string in future, as ANSI standard prescribes.

VARCHAR2 does not distinguish between a NULL and empty string, and never will.

  1. Also,

Emp_name varchar(10) - if you enter value less than 10 digits then remaining space cannot be deleted. it used total of 10 spaces.

Emp_name varchar2(10) - if you enter value less than 10 digits then remaining space is automatically deleted

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

How do I auto-submit an upload form when a file is selected?

You can put this code to make your code work with just single line of code

<input type="file" onchange="javascript:this.form.submit()">

This will upload the file on server without clicking on submit button

Access to the requested object is only available from the local network phpmyadmin

on osx log into your terminal and execute

sudo nano /opt/lampp/etc/extra/httpd-xampp.conf

and replace

<Directory "/opt/lampp/phpmyadmin">
    AllowOverride AuthConfig Limit
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

with this

<Directory "/opt/lampp/phpmyadmin">
    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

and then restart apache and mysql

or use this command

 /opt/lampp/xampp restart

I want to use CASE statement to update some records in sql server 2005

If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN in the UPDATE:

declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
 ('AAA','BBB'),
 ('CCC','DDD'),
 ('EEE','FFF')

update ts set LastName = ToName
from dbo.TestStudents ts
       inner join
     @ToDo t
       on
         ts.LastName = t.FromName

Recyclerview inside ScrollView not scrolling smoothly

You can try with both the ways with XML and programmatically. But the issue you may face is (below API 21) by doing it with XML will not work . So it's better to set it programmatically in your Activity / Fragment.

XML code:

<android.support.v7.widget.RecyclerView
      android:id="@+id/recycleView"
      android:layout_width="match_parent"
      android:visibility="gone"
      android:nestedScrollingEnabled="false"
      android:layout_height="wrap_content"
      android:layout_below="@+id/linearLayoutBottomText" /> 

Programmatically:

 recycleView = (RecyclerView) findViewById(R.id.recycleView);
 recycleView.setNestedScrollingEnabled(false);

import android packages cannot be resolved

RightClick on the Project > Properties > Android > Fix project properties

This solved it for me. easy.

docker : invalid reference format

For others come to here:
If you happen to put your docker command in a file, say run.sh, check your line separator. In Linux, it should be LR, otherwise you would get the same error.

How to grep (search) committed code in the Git history

So are you trying to grep through older versions of the code looking to see where something last exists?

If I were doing this, I would probably use git bisect. Using bisect, you can specify a known good version, a known bad version, and a simple script that does a check to see if the version is good or bad (in this case a grep to see if the code you are looking for is present). Running this will find when the code was removed.

Referencing Row Number in R

This is probably the simplest way:

data$rownumber = 1:dim(data)[1]

It's probably worth noting that if you want to select a row by its row index, you can do this with simple bracket notation

data[3,]

vs.

data[data$rownumber==3,]

So I'm not really sure what this new column accomplishes.

Add a new element to an array without specifying the index in Bash

With an indexed array, you can to something like this:

declare -a a=()
a+=('foo' 'bar')

Change CSS class properties with jQuery

Didn't find the answer I wanted, so I solved it myself:
modify a container div!

<div class="rotation"> <!-- Set the container div's css -->
  <div class="content" id='content-1'>This div gets scaled on hover</div>
</div>

<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>

css you want to persist after executing $target.css()

.content:hover {
    transform: scale(1.5);
}

modify content's containing div with css()

$(".rotation").css("transform", "rotate(" + degrees + "deg)");

Codepen example

Get Application Directory

For current Android application package:

public String getDataDir(Context context) throws Exception {
    return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
}

For any package:

public String getAnyDataDir(Context context, String packageName) throws Exception {
    return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.dataDir;
}

How to get DataGridView cell value in messagebox?

I added this to the Button of a datagrid to get the values of the cells in the row that the user is clicking:


string DGCell = dataGridView1.Rows[e.RowIndex].Cells[X].Value.ToString();

where X is the cell you want to check. Datagrid column count starts at 1 not 0 in my case. Not sure if it is default of a datagrid or because I am using SQL to populate the info.

Can't bind to 'routerLink' since it isn't a known property

You need to add RouterMoudle into imports sections of the module containing the Header component

Traits vs. interfaces

If you know English and know what trait means, it is exactly what the name says. It is a class-less pack of methods and properties you attach to existing classes by typing use.

Basically, you could compare it to a single variable. Closures functions can use these variables from outside of the scope and that way they have the value inside. They are powerful and can be used in everything. Same happens to traits if they are being used.

Using "Object.create" instead of "new"

new Operator

  • This is used to create object from a constructor function
  • The new keywords also executes the constructor function
function Car() {
  console.log(this) // this points to myCar
  this.name = "Honda";
}

var myCar = new Car()
console.log(myCar) // Car {name: "Honda", constructor: Object}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // true
console.log(myCar.constructor) // function Car() {}
console.log(myCar.constructor === Car) // true
console.log(typeof myCar) // object

Object.create

  • You can also use Object.create to create a new object
  • But, it does not execute the constructor function
  • Object.create is used to create an object from another object
const Car = {
  name: "Honda"
}

var myCar = Object.create(Car)
console.log(myCar) // Object {}
console.log(myCar.name) // Honda
console.log(myCar instanceof Car) // ERROR
console.log(myCar.constructor) // Anonymous function object
console.log(myCar.constructor === Car) // false
console.log(typeof myCar) // object

"Multiple definition", "first defined here" errors

I had a similar issue when not using inline for my global function that was included in two places.

Why are C++ inline functions in the header?

This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)

String delimiter in string.split method

StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
             "||");
while(st.hasMoreTokens()){
     System.out.println(st.nextElement());
}

Answer will print

1 1 Abdul-Jabbar Karim 1996 1974

Defining a HTML template to append using JQuery

In order to solve this problem, I recognize two solutions:

  • The first one goes with AJAX, with which you'll have to load the template from another file and just add everytime you want with .clone().

    $.get('url/to/template', function(data) {
        temp = data
        $('.search').keyup(function() {
            $('.list-items').html(null);
    
            $.each(items, function(index) {
                 $(this).append(temp.clone())
            });
    
        });
    });
    

    Take into account that the event should be added once the ajax has completed to be sure the data is available!

  • The second one would be to directly add it anywhere in the original html, select it and hide it in jQuery:

    temp = $('.list_group_item').hide()
    

    You can after add a new instance of the template with

    $('.search').keyup(function() {
        $('.list-items').html(null);
    
        $.each(items, function(index) {
            $(this).append(temp.clone())
        });
    });
    
  • Same as the previous one, but if you don't want the template to remain there, but just in the javascript, I think you can use (have not tested it!) .detach() instead of hide.

    temp = $('.list_group_item').detach()
    

    .detach() removes elements from the DOM while keeping the data and events alive (.remove() does not!).

How do I run Visual Studio as an administrator by default?

image showing how to run visual studio as adminstrator by mhamri step 1 to 3

1- either from start menu or when visual studio is open in the task bar, right click on the VS icon

2- in the context menu, right click again on the visual studio icon

3- left click on prorperties

image showing how to run visual studio as adminstrator by mhamri step 4

4- choose advanced

image showing how to run visual studio as adminstrator by mhamri step 5

5- choose Run as Administrator

click ok all the windows, close the visual studio and reopen again.

How to redirect to a different domain using NGINX?

You can simply write a if condition inside server {} block:

server { 

    if ($host = mydomain.com) {
        return 301 http://www.adifferentdomain.com;
    } 
}

How do I get a Cron like scheduler in Python?

I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html

The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

java.util.regex - importance of Pattern.compile()?

Pattern class is the entry point of the regex engine.You can use it through Pattern.matches() and Pattern.comiple(). #Difference between these two. matches()- for quickly check if a text (String) matches a given regular expression comiple()- create the reference of Pattern. So can use multiple times to match the regular expression against multiple texts.

For reference:

public static void main(String[] args) {
     //single time uses
     String text="The Moon is far away from the Earth";
     String pattern = ".*is.*";
     boolean matches=Pattern.matches(pattern,text);
     System.out.println("Matches::"+matches);

    //multiple time uses
     Pattern p= Pattern.compile("ab");
     Matcher  m=p.matcher("abaaaba");
     while(m.find()) {
         System.out.println(m.start()+ " ");
     }
}

Unable to execute dex: method ID not in [0, 0xffff]: 65536

The perfect solution for this would be to work with Proguard. as aleb mentioned in the comment. It will decrease the size of the dex file by half.

How to declare a static const char* in your header file?

If you're using Visual C++, you can non-portably do this using hints to the linker...

// In foo.h...

class Foo
{
public:
   static const char *Bar;
};

// Still in foo.h; doesn't need to be in a .cpp file...

__declspec(selectany)
const char *Foo::Bar = "Blah";

__declspec(selectany) means that even though Foo::Bar will get declared in multiple object files, the linker will only pick up one.

Keep in mind this will only work with the Microsoft toolchain. Don't expect this to be portable.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

My guess is it's an encoding problem, for instance your file is UTF-8 but SQL will not read it the way it should, so it attempts to insert 100ÿ or something along these lines into your table.

Possible fixes:

  1. Specify Codepage
  2. Change the Encoding of the source using Powershell

Code samples:

1.
BULK INSERT myTable FROM 'c:\Temp\myfile.csv' WITH (
  FIELDTERMINATOR = '£',
  ROWTERMINATOR = '\n',
  CODEPAGE = 'ACP' -- ACP corresponds to ANSI, also try UTF-8 or 65001 for Unicode
);

2.
get-content "myfile.csv" | Set-content -Path "myfile.csv" -Encoding String
# String = ANSI, also try Ascii, Oem, Unicode, UTF7, UTF8, UTF32

Subtract two variables in Bash

White space is important, expr expects its operands and operators as separate arguments. You also have to capture the output. Like this:

COUNT=$(expr $FIRSTV - $SECONDV)

but it's more common to use the builtin arithmetic expansion:

COUNT=$((FIRSTV - SECONDV))

Focusable EditText inside ListView

Just try this

android:windowSoftInputMode="adjustNothing"

in the

activity

section of your manifest. Yes, it adjusts nothings, which means the editText will stay where it is when IME is opening. But that's just an little inconvenience that still completely solves the problem of losing focus.

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

How to enable zoom controls and pinch zoom in a WebView?

Check if you don't have a ScrollView wrapping your Webview.

In my case that was the problem. It seems ScrollView gets in the way of the pinch gesture.

To fix it, just take your Webview outside the ScrollView.

How do I work with dynamic multi-dimensional arrays in C?

There's no way to allocate the whole thing in one go. Instead, create an array of pointers, then, for each pointer, create the memory for it. For example:

int** array;
array = (int**)malloc(sizeof(int*) * 50);
for(int i = 0; i < 50; i++)
    array[i] = (int*)malloc(sizeof(int) * 50);

Of course, you can also declare the array as int* array[50] and skip the first malloc, but the second set is needed in order to dynamically allocate the required storage.

It is possible to hack a way to allocate it in a single step, but it would require a custom lookup function, but writing that in such a way that it will always work can be annoying. An example could be L(arr,x,y,max_x) arr[(y)*(max_x) + (x)], then malloc a block of 50*50 ints or whatever and access using that L macro, e.g.

#define L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]

int dim_x = 50;
int dim_y = 50;

int* array = malloc(dim_x*dim_y*sizeof(int));

int foo = L(array, 4, 6, dim_x);

But that's much nastier unless you know the effects of what you're doing with the preprocessor macro.

SQLite UPSERT / UPDATE OR INSERT

You can also just add an ON CONFLICT REPLACE clause to your user_name unique constraint and then just INSERT away, leaving it to SQLite to figure out what to do in case of a conflict. See:https://sqlite.org/lang_conflict.html.

Also note the sentence regarding delete triggers: When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

MVC Razor Hidden input and passing values

First of all ASP.NET MVC does not work the same way WebForms does. You don't have the whole runat="server" thing. MVC does not offer the abstraction layer that WebForms offered. Probabaly you should try to understand what controllers and actions are and then you should look at model binding. Any beginner level tutorial about MVC shows how you can pass data between the client and the server.

How to rename a file using Python

os.chdir(r"D:\Folder1\Folder2")
os.rename(src,dst)
#src and dst should be inside Folder2

Count textarea characters

textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);

You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:

textarea.addEventListener("keypress",textareaLengthCheck,false);

Aside from that:

var length = textarea.length;

textarea is the actual textarea, not the value. Try this instead:

var length = textarea.value.length;

Combined with the previous suggestion, your function should be:

function textareaLengthCheck() {
    var length = this.value.length;
    // rest of code
};

Get month name from date in Oracle

Try this

select to_char(SYSDATE,'Month') from dual;

for full name and try this

select to_char(SYSDATE,'Mon') from dual;

for abbreviation

you can find more option here:

https://www.techonthenet.com/oracle/functions/to_char.php

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Datatable date sorting dd/mm/yyyy issue

You can resolve this issue with php.

$mydate = strtotime($startdate);
$newformat = date('d-m-Y',$mydate);
echo '<tr>';
echo '  <td data-sort="'. $mydate .'">'.$newformat .'</td>';

MongoDB Aggregation: How to get total records count?

Here are some ways to get total records count while doing MongoDB Aggregation:


  • Using $count:

    db.collection.aggregate([
       // Other stages here
       { $count: "Total" }
    ])
    

    For getting 1000 records this takes on average 2 ms and is the fastest way.


  • Using .toArray():

    db.collection.aggregate([...]).toArray().length
    

    For getting 1000 records this takes on average 18 ms.


  • Using .itcount():

    db.collection.aggregate([...]).itcount()
    

    For getting 1000 records this takes on average 14 ms.

insert data from one table to another in mysql

If there is a primary key like "id" you have to exclude it for example my php table has: id, col2,col3,col4 columns. id is primary key so if I run this code:

INSERT INTO php  (SELECT * FROM php);

I probably get this error:

#1062 - Duplicate entry '1' for key 'PRIMARY'

So here is the solution, I excluded "id" key:

INSERT INTO php ( col2,col3,col4)  (SELECT col2,col3,col4 FROM php2);

So my new php table has all php2 table rows anymore.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

Facebook user url by id

As of now (NOV-2019), graph.api V5.0

graph API says, refer graph api

A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.

doc

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I am using wildfly 10 for javaee container . I had experienced "Target Unreachable, 'entity' returned null" issue. Thanks for suggestions by BalusC but the my issue out of the solutions explained. Accidentally using "import com.sun.istack.logging.Logger;" instead of "import org.jboss.logging.Logger;" caused CDI implemented JSF EL. Hope it helps to improve solution .

Bootstrap dropdown not working

Working demo: http://codebins.com/bin/4ldqp73

try this

<ul class='nav'>
  <li class='active'>Home</li>
  <li>
    <div class="dropdown">
      <a class="dropdown-toggle" data-toggle="dropdown" href="#">Personal asset loans</a>
      <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">            
        <li><a href="#">asds</a></li>
        <li class="divider"></li>
      </ul>
    </div>   
    </li>
    <li>Payday loans</li>
  <li>About</li>
  <li>Contact</li>
</ul>

Excel VBA Run Time Error '424' object required

Simply remove the .value from your code.

Set envFrmwrkPath = ActiveSheet.Range("D6").Value

instead of this, use:

Set envFrmwrkPath = ActiveSheet.Range("D6")

Java ResultSet how to check if there are any results

That would work if you want to see if there are any rows in the result set yes.

Note that next() always moves to the next row, so if you are planning on doing any reading from the result set you need to take that into account.

Usual usage with ResultSet (when simply reading) is:

while (resultSet.next())
{
   ... read from the row here ...
}

Which obviously won't work correctly if you invoked next() once already to check if the result set was empty, so watch out for that. Although there are methods for "backing up", they are not supported for all types of result sets.

Where is the documentation for the values() method of Enum?

Run this

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

you will see

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

These are all public methods that "sex" class has. They are not in the source code, javac.exe added them

Notes:

  1. never use sex as a class name, it's difficult to read your code, we use Sex in Java

  2. when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class

How to watch for form changes in Angular

For angular 5+ version. Putting version helps as angular makes lot of changes.

ngOnInit() {

 this.myForm = formBuilder.group({
      firstName: 'Thomas',
      lastName: 'Mann'
    })
this.formControlValueChanged() // Note if you are doing an edit/fetching data from an observer this must be called only after your form is properly initialized otherwise you will get error.
}

formControlValueChanged(): void {       
        this.myForm.valueChanges.subscribe(value => {
            console.log('value changed', value)
        })
}

using favicon with css

There is no explicit way to change the favicon globally using CSS that I know of. But you can use a simple trick to change it on the fly.

First just name, or rename, the favicon to "favicon.ico" or something similar that will be easy to remember, or is relevant for the site you're working on. Then add the link to the favicon in the head as you usually would. Then when you drop in a new favicon just make sure it's in the same directory as the old one, and that it has the same name, and there you go!

It's not a very elegant solution, and it requires some effort. But dropping in a new favicon in one place is far easier than doing a find and replace of all the links, or worse, changing them manually. At least this way doesn't involve messing with the code.

Of course dropping in a new favicon with the same name will delete the old one, so make sure to backup the old favicon in case of disaster, or if you ever want to go back to the old design.

In Python, what does dict.pop(a,b) mean?

>>> def func(a, *args, **kwargs):
...   print 'a %s, args %s, kwargs %s' % (a, args, kwargs)
... 
>>> func('one', 'two', 'three', four='four', five='five')
a one, args ('two', 'three'), kwargs {'four': 'four', 'five': 'five'}

>>> def anotherfunct(beta, *args):
...   print 'beta %s, args %s' % (beta, args)
... 
>>> def func(a, *args, **kwargs):
...   anotherfunct(a, *args)
... 
>>> func('one', 'two', 'three', four='four', five='five')
beta one, args ('two', 'three')
>>> 

Methods vs Constructors in Java

In Java, classes you write are Objects. Constructors construct those objects. For example if I have an Apple.class like so:

public class Apple {
    //instance variables
    String type; // macintosh, green, red, ...

    /**
     * This is the default constructor that gets called when you use
     * Apple a = new Apple(); which creates an Apple object named a.
     */

    public Apple() {
        // in here you initialize instance variables, and sometimes but rarely
        // do other functionality (at least with basic objects)
        this.type = "macintosh"; // the 'this' keyword refers to 'this' object. so this.type refers to Apple's 'type' instance variable.
    }

    /**
     * this is another constructor with a parameter. You can have more than one
     * constructor as long as they have different parameters. It creates an Apple
     * object when called using Apple a = new Apple("someAppleType");
     */
    public Apple(String t) {
        // when the constructor is called (i.e new Apple() ) this code is executed
        this.type = t;
    }

    /**
     * methods in a class are functions. They are whatever functionality needed
     * for the object
     */
    public String someAppleRelatedMethod(){
        return "hello, Apple class!";
    }

    public static void main(String[] args) {
        // construct an apple
        Apple a = new Apple("green");
        // 'a' is now an Apple object and has all the methods and
        // variables of the Apple class.
        // To use a method from 'a':
        String temp = a.someAppleRelatedMethod();
        System.out.println(temp);
        System.out.println("a's type is " + a.type);
    }
}

Hopefully I explained everything in the comments of the code, but here is a summary: Constructors 'construct' an object of type of the class. The constructor must be named the same thing as the class. They are mostly used for initializing instance varibales Methods are functionality of the objects.

What is the proper way to re-throw an exception in C#?

The first is better. If you try to debug the second and look at the call stack you won't see where the original exception came from. There are tricks to keep the call-stack intact (try search, it's been answered before) if you really need to rethrow.

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

If you get this error in CollectionView try to create CustomCell file and Custom xib also.

add this code in ViewDidLoad() at mainVC.

    let nib = UINib(nibName: "CustomnibName", bundle: nil)
    self.collectionView.register(nib, forCellWithReuseIdentifier: "cell")

jQuery Scroll To bottom of the page

You can just animate to scroll down the page by animating the scrollTop property, no plugin required, like this:

$(window).load(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, 1000);
});

Note the use of window.onload (when images are loaded...which occupy height) rather than document.ready.

To be technically correct, you need to subtract the window's height, but the above works:

$("html, body").animate({ scrollTop: $(document).height()-$(window).height() });

To scroll to a particular ID, use its .scrollTop(), like this:

$("html, body").animate({ scrollTop: $("#myID").scrollTop() }, 1000);

Convert javascript array to string

convert an array to a GET param string that can be appended to a url could be done as follows

function encodeGet(array){
    return getParams = $.map(array , function(val,index) {                    
        var str = index + "=" + escape(val);
        return str;
   }).join("&");
}

call this function as

var getStr = encodeGet({
    search:     $('input[name="search"]').val(),
    location:   $('input[name="location"]').val(),
    dod:        $('input[name="dod"]').val(),
    type:       $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;

which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.

Change border-bottom color using jquery?

If you have this in your CSS file:

.myApp
{
    border-bottom-color:#FF0000;
}

and a div for instance of:

<div id="myDiv">test text</div>

you can use:

$("#myDiv").addClass('myApp');// to add the style

$("#myDiv").removeClass('myApp');// to remove the style

or you can just use

$("#myDiv").css( 'border-bottom-color','#FF0000');

I prefer the first example, keeping all the CSS related items in the CSS files.

How to add headers to a multicolumn listbox in an Excel userform using VBA

Here's my solution.

I noticed that when I specify the listbox's rowsource via the properties window in the VBE, the headers pop up no problem. Its only when we try define the rowsource through VBA code that the headers get lost.

So I first went a defined the listboxes rowsource as a named range in the VBE for via the properties window, then I can reset the rowsource in VBA code after that. The headers still show up every time.

I am using this in combination with an advanced filter macro from a listobject, which then creates another (filtered) listobject on which the rowsource is based.

This worked for me

Howto? Parameters and LIKE statement SQL

Well, I'd go with:

 Dim cmd as New SqlCommand(
 "SELECT * FROM compliance_corner"_
  + " WHERE (body LIKE @query )"_ 
  + " OR (title LIKE @query)")

 cmd.Parameters.Add("@query", "%" +searchString +"%")

jQuery Change event on an <input> element - any way to retain previous value?

$('#element').on('change', function() {
    $(this).val($(this).prop("defaultValue"));
});

How to automatically reload a page after a given period of inactivity

I am doing it like this:

let lastActionTaken = new Date().getTime();
function checkLastAction() {
  let now = new Date().getTime();
  if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
  else lastActionTaken = now;
}
window.addEventListener("mousemove", checkLastAction);
window.addEventListener("touchstart", checkLastAction);
window.addEventListener("keydown", checkLastAction);

This will reload the page as soon as the user moves their mouse, hits a key or touches a touchscreen if it has been inactive for 1 hour. Also, this takes care of the focus as well, so if a user is moving their mouse in a different program and then come back to this window it will reload, which is good because the point is to not have old data being shown.

How do I perform the SQL Join equivalent in MongoDB?

We can merge/join all data inside only one collection with a easy function in few lines using the mongodb client console, and now we could be able of perform the desired query. Below a complete example,

.- Authors:

db.authors.insert([
    {
        _id: 'a1',
        name: { first: 'orlando', last: 'becerra' },
        age: 27
    },
    {
        _id: 'a2',
        name: { first: 'mayra', last: 'sanchez' },
        age: 21
    }
]);

.- Categories:

db.categories.insert([
    {
        _id: 'c1',
        name: 'sci-fi'
    },
    {
        _id: 'c2',
        name: 'romance'
    }
]);

.- Books

db.books.insert([
    {
        _id: 'b1',
        name: 'Groovy Book',
        category: 'c1',
        authors: ['a1']
    },
    {
        _id: 'b2',
        name: 'Java Book',
        category: 'c2',
        authors: ['a1','a2']
    },
]);

.- Book lending

db.lendings.insert([
    {
        _id: 'l1',
        book: 'b1',
        date: new Date('01/01/11'),
        lendingBy: 'jose'
    },
    {
        _id: 'l2',
        book: 'b1',
        date: new Date('02/02/12'),
        lendingBy: 'maria'
    }
]);

.- The magic:

db.books.find().forEach(
    function (newBook) {
        newBook.category = db.categories.findOne( { "_id": newBook.category } );
        newBook.lendings = db.lendings.find( { "book": newBook._id  } ).toArray();
        newBook.authors = db.authors.find( { "_id": { $in: newBook.authors }  } ).toArray();
        db.booksReloaded.insert(newBook);
    }
);

.- Get the new collection data:

db.booksReloaded.find().pretty()

.- Response :)

{
    "_id" : "b1",
    "name" : "Groovy Book",
    "category" : {
        "_id" : "c1",
        "name" : "sci-fi"
    },
    "authors" : [
        {
            "_id" : "a1",
            "name" : {
                "first" : "orlando",
                "last" : "becerra"
            },
            "age" : 27
        }
    ],
    "lendings" : [
        {
            "_id" : "l1",
            "book" : "b1",
            "date" : ISODate("2011-01-01T00:00:00Z"),
            "lendingBy" : "jose"
        },
        {
            "_id" : "l2",
            "book" : "b1",
            "date" : ISODate("2012-02-02T00:00:00Z"),
            "lendingBy" : "maria"
        }
    ]
}
{
    "_id" : "b2",
    "name" : "Java Book",
    "category" : {
        "_id" : "c2",
        "name" : "romance"
    },
    "authors" : [
        {
            "_id" : "a1",
            "name" : {
                "first" : "orlando",
                "last" : "becerra"
            },
            "age" : 27
        },
        {
            "_id" : "a2",
            "name" : {
                "first" : "mayra",
                "last" : "sanchez"
            },
            "age" : 21
        }
    ],
    "lendings" : [ ]
}

I hope this lines can help you.

How to properly assert that an exception gets raised in pytest?

If you want to test for a specific error type, use a combination of try, catch and raise:

#-- test for TypeError
try:
  myList.append_number("a")
  assert False
except TypeError: pass
except: assert False

What is time(NULL) in C?

You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.

Nb:time(&timer); is equivalent to timer = time(NULL);

call javascript function on hyperlink click

The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:

<div class="menu">
    <a href="http://example.org">Example</a>
    <a href="http://foobar.com">Foobar.com</a>
</div>

<script>
jQuery( 'div.menu a' )
    .click(function() {
        do_the_click( this.href );
        return false;
    });

// play the funky music white boy
function do_the_click( url )
{
    alert( url );
}
</script>

Interop type cannot be embedded

I ran into this issue when pulling down a TFS project to my local machine. Allegedly, it was working fine on the guy's machine who wrote it. I simply changed this...

WshShellClass shellClass = new WshShellClass();

To this...

WshShell shellClass = new WshShell();

Now, it is working like a champ!

How to use php serialize() and unserialize()

Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.

A good example of serialize() and unserialize() could be like this:

$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");

Unserialize on the page

if($_GET['x']) {
   // unpack serialize and encoded URL
   $_POST = unserialize(base64_decode($_GET['x']));
}

Error - trustAnchors parameter must be non-empty

I expected things like this, being that I use an alternate JVM in my Talend Open Studio (support at the moment exists only until JDK 1.7). I use 8 for security purposes... anyway

  • Update your certificate store:

    sudo update-ca-certificates -f
    

then

  • add a new value in your initialization parameters

    sudo gedit $(path to your architecture specific ini i.e. TOS_DI...ini)
    
    Djavax.net.ssl.trustStore=/etc/ssl/certs/java/cacerts
    

For me, the second entry worked. I think, depending on the version of Talend Open Studio/TEnt + JVM, it has a different parameter name, but it looks for the same keystore file.

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

Copy mysql database from remote server to local computer

Copy mysql database from remote server to local computer

I ran into the same problem. And I could not get it done with the other answers. So here is how I finally did it (yes, a beginner tutorial):

Step 1: Create a new database in your local phpmyadmin.

Step 2: Dump the database on the remote server into a sql file (here I used Putty/SSH):

mysqldump --host="mysql5.domain.com" --user="db231231" --password="DBPASSWORD" databasename > dbdump.sql

Step 3: Download the dbdump.sql file via FTP client (should be located in the root folder)

Step 4: Move the sql file to the folder of your localhost installation, where mysql.exe is located. I am using uniform-server, this would be at C:\uniserver\core\mysql\bin\, with XAMPP it would be C:\xampp\mysql\bin

Step 5: Execute the mysql.exe as follows:

 mysql.exe -u root -pYOURPASSWORD YOURLOCALDBNAME < dbdump.sql

Step 6: Wait... depending on the file size. You can check the progress in phpmyadmin, seeing newly created tables.

Step 7: Done. Go to your local phpmyadmin to check if the database has been filled with the entire data.

Hope that helps. Good luck!


Note 1: When starting the uniformer-server you can specify a password for mysql. This is the one you have to use above for YOURPASSWORD.

Note 2: If the login does not work and you run into password problems, check your password if it contains special characters like !. If so, then you probably need to escape them \!.

Note 3: In case not all mysql data can be found in the local db after the import, it could be that there is a problem with the mysql directives of your dbdump.sql

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

How do I rename a column in a database table using SQL?

Specifically for SQL Server, use sp_rename

USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO

Modifying CSS class property values on the fly with JavaScript / jQuery

This solution modifies Cycne's to use ES6 syntax and exit the loop early for external stylesheets. This solution does not modify external stylesheets

_x000D_
_x000D_
function changeStyle(findSelector, newDeclarations) {_x000D_
    // Change original css style declaration._x000D_
    document.styleSheets.forEach((sheet) => {_x000D_
      if (sheet.href) return;_x000D_
      const cssRulesList = sheet.cssRules;_x000D_
      cssRulesList.forEach((styleRule) => {_x000D_
        if (styleRule.selectorText === findSelector) {_x000D_
          Object.keys(newDeclarations).forEach((cssProp) => {_x000D_
            styleRule.style[cssProp] = newDeclarations[cssProp];_x000D_
          });_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  }_x000D_
_x000D_
  const styleDeclarations = {_x000D_
    'width': '200px',_x000D_
    'height': '400px',_x000D_
    'color': '#F00'_x000D_
  };_x000D_
  changeStyle('.paintBox', styleDeclarations);
_x000D_
_x000D_
_x000D_

You must also have at least one style tag in your HTML head section, for example

<style> .paintBox {background-color: white;}</style>

What's the best way to use R scripts on the command line (terminal)?

Try littler. littler provides hash-bang (i.e. script starting with #!/some/path) capability for GNU R, as well as simple command-line and piping use.

Named capturing groups in JavaScript regex?

As Tim Pietzcker said ECMAScript 2018 introduces named capturing groups into JavaScript regexes. But what I did not find in the above answers was how to use the named captured group in the regex itself.

you can use named captured group with this syntax: \k<name>. for example

var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/

and as Forivin said you can use captured group in object result as follow:

let result = regexObj.exec('2019-28-06 year is 2019');
// result.groups.year === '2019';
// result.groups.month === '06';
// result.groups.day === '28';

_x000D_
_x000D_
  var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/mgi;_x000D_
_x000D_
function check(){_x000D_
    var inp = document.getElementById("tinput").value;_x000D_
    let result = regexObj.exec(inp);_x000D_
    document.getElementById("year").innerHTML = result.groups.year;_x000D_
    document.getElementById("month").innerHTML = result.groups.month;_x000D_
    document.getElementById("day").innerHTML = result.groups.day;_x000D_
}
_x000D_
td, th{_x000D_
  border: solid 2px #ccc;_x000D_
}
_x000D_
<input id="tinput" type="text" value="2019-28-06 year is 2019"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span>Pattern: "(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>";_x000D_
<br/>_x000D_
<br/>_x000D_
<button onclick="check()">Check!</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>Year</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Month</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Day</span>_x000D_
      </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <span id="year"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="month"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="day"></span>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

How to open mail app from Swift

While other answers are all correct, you can never know if the iPhone/iPad that is running your application has the Apple's Mail app installed or not as it can be deleted by the user.

It is better to support multiple email clients. Following code handles the email sending in a more graceful way. The flow of the code is:

  • If Mail app is installed, open Mail's composer pre-filled with provided data
  • Otherwise, try opening the Gmail app, then Outlook, then Yahoo mail, then Spark, in this order
  • If none of those clients are installed, fallback to default mailto:.. that prompts the user to install Apple's Mail app.

Code is written in Swift 5:

    import MessageUI
    import UIKit

    class SendEmailViewController: UIViewController, MFMailComposeViewControllerDelegate {
        
        @IBAction func sendEmail(_ sender: UIButton) {
            // Modify following variables with your text / recipient
            let recipientEmail = "[email protected]"
            let subject = "Multi client email support"
            let body = "This code supports sending email via multiple different email apps on iOS! :)"
            
            // Show default mail composer
            if MFMailComposeViewController.canSendMail() {
                let mail = MFMailComposeViewController()
                mail.mailComposeDelegate = self
                mail.setToRecipients([recipientEmail])
                mail.setSubject(subject)
                mail.setMessageBody(body, isHTML: false)
                
                present(mail, animated: true)
            
            // Show third party email composer if default Mail app is not present
            } else if let emailUrl = createEmailUrl(to: recipientEmail, subject: subject, body: body) {
                UIApplication.shared.open(emailUrl)
            }
        }
        
        private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
            let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            
            let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
            let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
            let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")
            
            if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
                return gmailUrl
            } else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
                return outlookUrl
            } else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
                return yahooMail
            } else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
                return sparkUrl
            }
            
            return defaultUrl
        }
        
        func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
            controller.dismiss(animated: true)
        }
    }

Please note that I intentionally missed out the body for the Outlook app, as it is not able to parse it.

You also have to add following code to Info.plist file that whitelists the URl query schemes that are used.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>googlegmail</string>
    <string>ms-outlook</string>
    <string>readdle-spark</string>
    <string>ymail</string>
</array>

Switching to landscape mode in Android Emulator

Just use 9 in numeric keyboard with num-lock off.

Image showing the numpad with 9 highlighted

7 rotates in the opposite direction.

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

Access camera from a browser

Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.

Also, you may try the getUserMedia method (supported by Opera 12)

enter image description here

How to change a <select> value from JavaScript

You can use the selectedIndex property to set it to the first option:

document.getElementById("select").selectedIndex = 0;

Sleep function in Windows, using C

Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.

void sleep(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock())
        ;
}

Note that the name sleep for this function is misleading, since the CPU will not be sleeping at all.

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

how to compare the Java Byte[] array?

Because neither == nor the equals() method of the array compare the contents; both only evaluate object identity (== always does, and equals() is not overwritten, so the version from Object is being used).

For comparing the contents, use Arrays.equals().

Centering a div block without the width

<style type="text/css">
.container_box{
    text-align:center
}
.content{
    padding:10px;
    background:#ff0000;
    color:#ffffff;

}

use span istead of the inner divs

<div class="container_box">
   <span class="content">Hello</span>
</div>