Programs & Examples On #Orchestration

Orchestration refers to a very high level of control, coordination and management of computer systems and services in order to automate processes.

How do I define the name of image built with docker-compose

For docker-compose version 2 file format, you can build and tag an image for one service and then use that same built image for another service.

For my case, I want to set up an elasticsearch cluster with 2 nodes, they both need to use the same image, but configured to run differently. I also want to build my own custom elasticsearch image from my own Dockerfile. So this is what I did (docker-compose.yml):

version: '2'

services:
  es-master:
    build: ./elasticsearch
    image: porter/elasticsearch
    ports:
      - "9200:9200"
    container_name: es_master

  es-node:
    image: porter/elasticsearch
    depends_on:
      - es-master
    ports:
      - "9200"
    command: elasticsearch --discovery.zen.ping.unicast.hosts=es_master

You can see that in the first service definition es-master, I use the build option to build an image from the Dockerfile in ./elasticsearch. I tag the image with the name porter/elasticsearch with the image option.
Then, I reference this built image in the es-node service definition with the image option, and also use a depends_on to make sure the other container es-master is built and run first.

Add a dependency in Maven

I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.

If yes, then this is what you want to read.

And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)

Pure JavaScript: a function like jQuery's isNumeric()

isFinite(String(n)) returns true for n=0 or '0', '1.1' or 1.1,

but false for '1 dog' or '1,2,3,4', +- Infinity and any NaN values.

Trying to embed newline in a variable in bash

sed solution:

echo "a b c" | sed 's/ \+/\n/g'

Result:

a
b
c

How to initialize an array of objects in Java

Player[] players = Stream.iterate(0, x-> x+1 ).limit(PlayerCount).map(i -> new Player(i)).toArray(Player[]::new);

How to automatically generate N "distinct" colors?

Everyone seems to have missed the existence of the very useful YUV color space which was designed to represent perceived color differences in the human visual system. Distances in YUV represent differences in human perception. I needed this functionality for MagicCube4D which implements 4-dimensional Rubik's cubes and an unlimited numbers of other 4D twisty puzzles having arbitrary numbers of faces.

My solution starts by selecting random points in YUV and then iteratively breaking up the closest two points, and only converting to RGB when returning the result. The method is O(n^3) but that doesn't matter for small numbers or ones that can be cached. It can certainly be made more efficient but the results appear to be excellent.

The function allows for optional specification of brightness thresholds so as not to produce colors in which no component is brighter or darker than given amounts. IE you may not want values close to black or white. This is useful when the resulting colors will be used as base colors that are later shaded via lighting, layering, transparency, etc. and must still appear different from their base colors.

import java.awt.Color;
import java.util.Random;

/**
 * Contains a method to generate N visually distinct colors and helper methods.
 * 
 * @author Melinda Green
 */
public class ColorUtils {
    private ColorUtils() {} // To disallow instantiation.
    private final static float
        U_OFF = .436f,
        V_OFF = .615f;
    private static final long RAND_SEED = 0;
    private static Random rand = new Random(RAND_SEED);    

    /*
     * Returns an array of ncolors RGB triplets such that each is as unique from the rest as possible
     * and each color has at least one component greater than minComponent and one less than maxComponent.
     * Use min == 1 and max == 0 to include the full RGB color range.
     * 
     * Warning: O N^2 algorithm blows up fast for more than 100 colors.
     */
    public static Color[] generateVisuallyDistinctColors(int ncolors, float minComponent, float maxComponent) {
        rand.setSeed(RAND_SEED); // So that we get consistent results for each combination of inputs

        float[][] yuv = new float[ncolors][3];

        // initialize array with random colors
        for(int got = 0; got < ncolors;) {
            System.arraycopy(randYUVinRGBRange(minComponent, maxComponent), 0, yuv[got++], 0, 3);
        }
        // continually break up the worst-fit color pair until we get tired of searching
        for(int c = 0; c < ncolors * 1000; c++) {
            float worst = 8888;
            int worstID = 0;
            for(int i = 1; i < yuv.length; i++) {
                for(int j = 0; j < i; j++) {
                    float dist = sqrdist(yuv[i], yuv[j]);
                    if(dist < worst) {
                        worst = dist;
                        worstID = i;
                    }
                }
            }
            float[] best = randYUVBetterThan(worst, minComponent, maxComponent, yuv);
            if(best == null)
                break;
            else
                yuv[worstID] = best;
        }

        Color[] rgbs = new Color[yuv.length];
        for(int i = 0; i < yuv.length; i++) {
            float[] rgb = new float[3];
            yuv2rgb(yuv[i][0], yuv[i][1], yuv[i][2], rgb);
            rgbs[i] = new Color(rgb[0], rgb[1], rgb[2]);
            //System.out.println(rgb[i][0] + "\t" + rgb[i][1] + "\t" + rgb[i][2]);
        }

        return rgbs;
    }

    public static void hsv2rgb(float h, float s, float v, float[] rgb) {
        // H is given on [0->6] or -1. S and V are given on [0->1]. 
        // RGB are each returned on [0->1]. 
        float m, n, f;
        int i;

        float[] hsv = new float[3];

        hsv[0] = h;
        hsv[1] = s;
        hsv[2] = v;
        System.out.println("H: " + h + " S: " + s + " V:" + v);
        if(hsv[0] == -1) {
            rgb[0] = rgb[1] = rgb[2] = hsv[2];
            return;
        }
        i = (int) (Math.floor(hsv[0]));
        f = hsv[0] - i;
        if(i % 2 == 0)
            f = 1 - f; // if i is even 
        m = hsv[2] * (1 - hsv[1]);
        n = hsv[2] * (1 - hsv[1] * f);
        switch(i) {
            case 6:
            case 0:
                rgb[0] = hsv[2];
                rgb[1] = n;
                rgb[2] = m;
                break;
            case 1:
                rgb[0] = n;
                rgb[1] = hsv[2];
                rgb[2] = m;
                break;
            case 2:
                rgb[0] = m;
                rgb[1] = hsv[2];
                rgb[2] = n;
                break;
            case 3:
                rgb[0] = m;
                rgb[1] = n;
                rgb[2] = hsv[2];
                break;
            case 4:
                rgb[0] = n;
                rgb[1] = m;
                rgb[2] = hsv[2];
                break;
            case 5:
                rgb[0] = hsv[2];
                rgb[1] = m;
                rgb[2] = n;
                break;
        }
    }


    // From http://en.wikipedia.org/wiki/YUV#Mathematical_derivations_and_formulas
    public static void yuv2rgb(float y, float u, float v, float[] rgb) {
        rgb[0] = 1 * y + 0 * u + 1.13983f * v;
        rgb[1] = 1 * y + -.39465f * u + -.58060f * v;
        rgb[2] = 1 * y + 2.03211f * u + 0 * v;
    }

    public static void rgb2yuv(float r, float g, float b, float[] yuv) {
        yuv[0] = .299f * r + .587f * g + .114f * b;
        yuv[1] = -.14713f * r + -.28886f * g + .436f * b;
        yuv[2] = .615f * r + -.51499f * g + -.10001f * b;
    }

    private static float[] randYUVinRGBRange(float minComponent, float maxComponent) {
        while(true) {
            float y = rand.nextFloat(); // * YFRAC + 1-YFRAC);
            float u = rand.nextFloat() * 2 * U_OFF - U_OFF;
            float v = rand.nextFloat() * 2 * V_OFF - V_OFF;
            float[] rgb = new float[3];
            yuv2rgb(y, u, v, rgb);
            float r = rgb[0], g = rgb[1], b = rgb[2];
            if(0 <= r && r <= 1 &&
                0 <= g && g <= 1 &&
                0 <= b && b <= 1 &&
                (r > minComponent || g > minComponent || b > minComponent) && // don't want all dark components
                (r < maxComponent || g < maxComponent || b < maxComponent)) // don't want all light components

                return new float[]{y, u, v};
        }
    }

    private static float sqrdist(float[] a, float[] b) {
        float sum = 0;
        for(int i = 0; i < a.length; i++) {
            float diff = a[i] - b[i];
            sum += diff * diff;
        }
        return sum;
    }

    private static double worstFit(Color[] colors) {
        float worst = 8888;
        float[] a = new float[3], b = new float[3];
        for(int i = 1; i < colors.length; i++) {
            colors[i].getColorComponents(a);
            for(int j = 0; j < i; j++) {
                colors[j].getColorComponents(b);
                float dist = sqrdist(a, b);
                if(dist < worst) {
                    worst = dist;
                }
            }
        }
        return Math.sqrt(worst);
    }

    private static float[] randYUVBetterThan(float bestDistSqrd, float minComponent, float maxComponent, float[][] in) {
        for(int attempt = 1; attempt < 100 * in.length; attempt++) {
            float[] candidate = randYUVinRGBRange(minComponent, maxComponent);
            boolean good = true;
            for(int i = 0; i < in.length; i++)
                if(sqrdist(candidate, in[i]) < bestDistSqrd)
                    good = false;
            if(good)
                return candidate;
        }
        return null; // after a bunch of passes, couldn't find a candidate that beat the best.
    }


    /**
     * Simple example program.
     */
    public static void main(String[] args) {
        final int ncolors = 10;
        Color[] colors = generateVisuallyDistinctColors(ncolors, .8f, .3f);
        for(int i = 0; i < colors.length; i++) {
            System.out.println(colors[i].toString());
        }
        System.out.println("Worst fit color = " + worstFit(colors));
    }

}

What is "origin" in Git?

The other answers say that origin is an alias for the URL of a remote repository which is not entirely accurate. It should be noted that an address that starts with http is a URL while one that starts with git@ is a URI or Universal Resource Identifier.

All URLs are URIs, but not all URIs are URLs.

In short, when you type git remote add origin <URI> you are telling your local git that whenever you use the word origin you actually mean the URI that you specified. Think of it like a variable holding a value.

And just like a variable, you can name it whatever you want (eg. github, heroku, destination, etc).

What programming language does facebook use?

Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.

Java switch statement: Constant expression required, but it IS constant

I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?

While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression1. This refers to §4.12.4 Final Variables which defines a "constant variable" as follows:

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as "constant variables". The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.

In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final may be what is needed.

You could change your code to use an enum rather than int constants, but that brings another couple of different restrictions:

  • You must include a default case, even if you have case for every known value of the enum; see Why is default required for a switch on an enum?
  • The case labels must all be explicit enum values, not expressions that evaluate to enum values.

1 - The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and String only, b) allow primaries that are literals (apart from null) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, ++, -- or instanceof, and e) allow type casts to primitive types or String only.

Note that this doesn't include any form of method or lambda calls, new, .class. .length or array subscripting. Furthermore, any use of array values, enum values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).

How to get root directory in yii2

Supposing you have a writable "uploads" folder in your application:

You can define a param like this:

Yii::$app->params['uploadPath'] = realpath(Yii::$app->basePath) . '/uploads/';

Then you can simply use the parameter as:

$path1 = Yii::$app->params['uploadPath'] . $filename;

Just depending on if you are using advanced or simple template the base path will be (following the link provided by phazei):

Simple @app: Your application root directory

Advanced @app: Your application root directory (either frontend or backend or console depending on where you access it from)

This way the application will be more portable than using realpath(dirname(__FILE__).'/../../'));

How to get an input text value in JavaScript

Notice that this line:

lol = document.getElementById('lolz').value;

is before the actual <input> element on your markup:

<input type="text" name="enter" class="enter" value="" id="lolz"/>

Your code is parsed line by line, and the lol = ... line is evaluated before the browser knows about the existance of an input with id lolz. Thus, document.getElementById('lolz') will return null, and document.getElementById('lolz').value should cause an error.

Move that line inside the function, and it should work. This way, that line will only run when the function is called. And use var as others suggested, to avoid making it a global variable:

function kk(){
    var lol = document.getElementById('lolz').value;
    alert(lol);
}

You can also move the script to the end of the page. Moving all script blocks to the end of your HTML <body> is the standard practice today to avoid this kind of reference problem. It also tends to speed up page load, since scripts that take long to load and parse are processed after the HTML has been (mostly) displayed.

Difference between Hashing a Password and Encrypting it

I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.

Leading zeros for Int in Swift

For left padding add a string extension like this:

Swift 2.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
    }
}

Swift 3.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
    }
}

Using this method:

for myInt in 1...3 {
    print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}

Append data frames together in a for loop

x <- c(1:10) 

# empty data frame with variables ----

df <- data.frame(x1=character(),
                     y1=character())

for (i in x) {
  a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
  df <- rbind(df,a1)
}

names(df) <- c("st_column","nd_column")
View(df)

that might be a good way to do so....

CSS Selector for <input type="?"

Sorry, the short answer is no. CSS (2.1) will only mark up the elements of a DOM, not their attributes. You'd have to apply a specific class to each input.

Bummer I know, because that would be incredibly useful.

I know you've said you'd prefer CSS over JavaScript, but you should still consider using jQuery. It provides a very clean and elegant way of adding styles to DOM elements based on attributes.

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

How to import popper.js?

I had the same problem. Tried different approches, but this one worked for me. Read the instruction from http://getbootstrap.com/.

Copy the CDN paths of Javascripts (Popper, jQuery and Bootstrap) in same manner (it is important) as given.

enter image description here

_x000D_
_x000D_
<head>_x000D_
//Path to jQuery_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
_x000D_
////Path to Popper - it is for dropsdowns etc in bootstrap_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>_x000D_
_x000D_
//Path to bootsrap_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

HorizontalScrollView within ScrollView Touch Handling

It wasn't working well for me. I changed it and now it works smoothly. If anyone interested.

public class ScrollViewForNesting extends ScrollView {
    private final int DIRECTION_VERTICAL = 0;
    private final int DIRECTION_HORIZONTAL = 1;
    private final int DIRECTION_NO_VALUE = -1;

    private final int mTouchSlop;
    private int mGestureDirection;

    private float mDistanceX;
    private float mDistanceY;
    private float mLastX;
    private float mLastY;

    public ScrollViewForNesting(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
    }

    public ScrollViewForNesting(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ScrollViewForNesting(Context context) {
        this(context,null);
    }    


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {      
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDistanceY = mDistanceX = 0f;
                mLastX = ev.getX();
                mLastY = ev.getY();
                mGestureDirection = DIRECTION_NO_VALUE;
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                mDistanceX += Math.abs(curX - mLastX);
                mDistanceY += Math.abs(curY - mLastY);
                mLastX = curX;
                mLastY = curY;
                break;
        }

        return super.onInterceptTouchEvent(ev) && shouldIntercept();
    }


    private boolean shouldIntercept(){
        if((mDistanceY > mTouchSlop || mDistanceX > mTouchSlop) && mGestureDirection == DIRECTION_NO_VALUE){
            if(Math.abs(mDistanceY) > Math.abs(mDistanceX)){
                mGestureDirection = DIRECTION_VERTICAL;
            }
            else{
                mGestureDirection = DIRECTION_HORIZONTAL;
            }
        }

        if(mGestureDirection == DIRECTION_VERTICAL){
            return true;
        }
        else{
            return false;
        }
    }
}

How to change root logging level programmatically for logback

I seem to be having success doing

org.jboss.logmanager.Logger logger = org.jboss.logmanager.Logger.getLogger("");
logger.setLevel(java.util.logging.Level.ALL);

Then to get detailed logging from netty, the following has done it

org.slf4j.impl.SimpleLogger.setLevel(org.slf4j.impl.SimpleLogger.TRACE);

How is the AND/OR operator represented as in Regular Expressions?

I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:

((^|, )(part1|part2|part3))+$

Positive matches:

part1
part2, part1
part1, part2, part3

Negative matches:

part1,           //with and without trailing spaces.
part3, part2, 
otherpart1

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

SQL query, if value is null then return 1

try like below...

CASE 
WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate

How to import a single table in to mysql database using command line

you can do it in mysql command instead of linux command.
1.login your mysql.
2.excute this in mysql command:
use DATABASE_NAME;
SET autocommit=0 ; source ABSOLUTE_PATH/TABLE_SQL_FILE.sql ; COMMIT ;

How to post SOAP Request from PHP

In my experience, it's not quite that simple. The built-in PHP SOAP client didn't work with the .NET-based SOAP server we had to use. It complained about an invalid schema definition. Even though .NET client worked with that server just fine. By the way, let me claim that SOAP interoperability is a myth.

The next step was NuSOAP. This worked for quite a while. By the way, for God's sake, don't forget to cache WSDL! But even with WSDL cached users complained the damn thing is slow.

Then, we decided to go bare HTTP, assembling the requests and reading the responses with SimpleXMLElemnt, like this:

$request_info = array();

$full_response = @http_post_data(
    'http://example.com/OTA_WS.asmx',
    $REQUEST_BODY,
    array(
        'headers' => array(
            'Content-Type' => 'text/xml; charset=UTF-8',
            'SOAPAction'   => 'HotelAvail',
        ),
        'timeout' => 60,

    ),
    $request_info
);

$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));

foreach ($response_xml->xpath('//@HotelName') as $HotelName) {
    echo strval($HotelName) . "\n";
}

Note that in PHP 5.2 you'll need pecl_http, as far as (surprise-surpise!) there's no HTTP client built in.

Going to bare HTTP gained us over 30% in SOAP request times. And from then on we redirect all the performance complains to the server guys.

In the end, I'd recommend this latter approach, and not because of the performance. I think that, in general, in a dynamic language like PHP there's no benefit from all that WSDL/type-control. You don't need a fancy library to read and write XML, with all that stubs generation and dynamic proxies. Your language is already dynamic, and SimpleXMLElement works just fine, and is so easy to use. Also, you'll have less code, which is always good.

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

Remove querystring from URL

A simple way is you can do as follows

public static String stripQueryStringAndHashFromPath(String uri) {
 return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}

How to send and retrieve parameters using $state.go toParams and $stateParams?

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

In the state add your params to end of state and define the params:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' });

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

How do I get and set Environment variables in C#?

Use the System.Environment class.

The methods

var value = System.Environment.GetEnvironmentVariable(variable [, Target])

and

System.Environment.SetEnvironmentVariable(variable, value [, Target])

will do the job for you.

The optional parameter Target is an enum of type EnvironmentVariableTarget and it can be one of: Machine, Process, or User. If you omit it, the default target is the current process.

When to use "new" and when not to, in C++?

You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:

void foo()
{
  Point p = Point(0,0);
} // p is now destroyed.

for (...)
{
  Point p = Point(0,0);
} // p is destroyed after each loop

Some people will say that the use of new decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.

In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.

class Foo
{

  Point p;
}; // p will be automatically destroyed when foo is.

Allocating (and freeing) objects with the use of new is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.

A second example of when to allocate via new is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.

E.g.

void foo(int size)
{
   Point* pointArray = new Point[size];
   ...
   delete [] pointArray;
}

(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).

HTML / CSS How to add image icon to input type="button"?

This is the minimal style needed, fitting the image to the default button size:

_x000D_
_x000D_
<input type="button" value=" " style="background-image: url(http://www.geppoz.eu/geppoz.png);background-size:100% 100%;">
_x000D_
_x000D_
_x000D_

the "spaced" value is needed to keep baseline alignment, just in case you need it...

How to make an executable JAR file?

If you use maven, add the following to your pom.xml file:

<plugin>
    <!-- Build an executable JAR -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.path.to.YourMainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

Then you can run mvn package. The jar file will be located under in the target directory.

How to split a string in Ruby and get all items except the first one?

Try this:

first, *rest = ex.split(/, /)

Now first will be the first value, rest will be the rest of the array.

Recursively list all files in a directory including files in symlink directories

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

ls -LR

You can also accomplish this with

find -follow

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

find -L

as -follow has been deprecated.

Retrieving Data from SQL Using pyodbc

you could try using Pandas to retrieve information and get it as dataframe

import pyodbc as cnn
import pandas as pd

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')

# Copy to Clipboard for paste in Excel sheet
def copia (argumento):
    df=pd.DataFrame(argumento)
    df.to_clipboard(index=False,header=True)


tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn) 

# Copy to Clipboard
copia(tableResult)

# Or create a Excel file with the results
df=pd.DataFrame(tableResult)
df.to_excel("FileExample.xlsx",sheet_name='Results')

I hope this helps! Cheers!

Accessing Redux state in an action creator?

I wouldn't access state in the Action Creator. I would use mapStateToProps() and import the entire state object and import a combinedReducer file (or import * from './reducers';) in the component the Action Creator is eventually going to. Then use destructuring in the component to use whatever you need from the state prop. If the Action Creator is passing the state onto a Reducer for the given TYPE, you don't need to mention state because the reducer has access to everything that is currently set in state. Your example is not updating anything. I would only use the Action Creator to pass along state from its parameters.

In the reducer do something like:

const state = this.state;
const apple = this.state.apples;

If you need to perform an action on state for the TYPE you are referencing, please do it in the reducer.

Please correct me if I'm wrong!!!

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

When and why do I need to use cin.ignore() in C++?

Ignore function is used to skip(discard/throw away) characters in the input stream. Ignore file is associated with the file istream. Consider the function below ex: cin.ignore(120,'/n'); the particular function skips the next 120 input character or to skip the characters until a newline character is read.

ADB Shell Input Events

Also, if you want to send embedded spaces with the input command, use %s

adb shell input text 'this%sis%san%sexample'   

will yield

this is an example

being input.

% itself does not need escaping - only the special %s pair is treated specially. This leads of course to the obvious question of how to enter the literal string %s, which you would have to do with two separate commands.

How can I format a decimal to always show 2 decimal places?

You can use the string formatting operator as so:

num = 49
x = "%.2f" % num  # x is now the string "49.00"

I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.

throwing an exception in objective-c/cocoa

A word of caution here. In Objective-C, unlike many similar languages, you generally should try to avoid using exceptions for common error situations that may occur in normal operation.

Apple's documentation for Obj-C 2.0 states the following: "Important: Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors (such as a file not being accessible)"

Apple's conceptual Exception handling documentation explains the same, but with more words: "Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime. [.....] Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications."

The reasons for this is partly to adhere to programming idioms in Objective-C (using return values in simple cases and by-reference parameters (often the NSError class) in more complex cases), partly that throwing and catching exceptions is much more expensive and finally (and perpaps most importantly) that Objective-C exceptions are a thin wrapper around C's setjmp() and longjmp() functions, essentially messing up your careful memory handling, see this explanation.

Arraylist swap elements

for (int i = 0; i < list.size(); i++) {
        if (i < list.size() - 1) {
            if (list.get(i) > list.get(i + 1)) {
                int j = list.get(i);
                list.remove(i);
                list.add(i, list.get(i));
                list.remove(i + 1);
                list.add(j);
                i = -1;
            }
        }
    }

cmd line rename file with date and time

I tried to do the same:

<fileName>.<ext> --> <fileName>_<date>_<time>.<ext> 

I found that :

rename 's/(\w+)(\.\w+)/$1'$(date +"%Y%m%d_%H%M%S)'$2/' *

How to use custom packages

I try so many ways but the best I use go.mod and put

module nameofProject.com

and then i import from same project I use

import("nameofProject.com/folder")

It's very useful to create project in any place

How to search for a part of a word with ElasticSearch

While there are a lot of answers which focuses on solving the issue at hand but don't talk much about the various trade-off which someone needs to make before choosing a particular answer. So let me try to add a few more details on this perspective.

Partial search is now a day a very common and important feature and if not implemented properly can lead to poor user experience and bad performance, so first know your application function and non-function requirement related to this feature which I talked about in my this detailed SO answer.

Now there are various approaches, like query time, index time, completion suggester and search as you type data-types added in recent version of elasticsarch.

Now people who quickly want to just implement a solution can use below end to end working solution.

Index mapping

{
  "settings": {
    "analysis": {
      "filter": {
        "autocomplete_filter": {
          "type": "ngram",
          "min_gram": 1,
          "max_gram": 10
        }
      },
      "analyzer": {
        "autocomplete": { 
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    },
    "index.max_ngram_diff" : 10
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "autocomplete", 
        "search_analyzer": "standard" 
      }
    }
  }
}

Index given sample docs

{
  "title" : "John Doeman"
  
}

{
  "title" : "Jane Doewoman"
  
}

{
  "title" : "Jimmy Jackal"
  
}

And search query

{
    "query": {
        "match": {
            "title": "Doe"
        }
    }
}

which returns expected search results

 "hits": [
            {
                "_index": "6467067",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.76718915,
                "_source": {
                    "title": "John Doeman"
                }
            },
            {
                "_index": "6467067",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.76718915,
                "_source": {
                    "title": "Jane Doewoman"
                }
            }
        ]

How do I reference a local image in React?

const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />

phpMyAdmin allow remote users

Try this

Replace

<Directory /usr/share/phpMyAdmin/>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        <RequireAny>
            Require ip 127.0.0.1
            Require ip ::1
        </RequireAny>
    </IfModule>
    <IfModule !mod_authz_core.c>
        # Apache 2.2
        Order Deny,Allow
        Deny from All
        Allow from 127.0.0.1
        Allow from ::1
    </IfModule>
</Directory>

With this:

<Directory "/usr/share/phpMyAdmin/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny 
    Allow from all
</Directory>

Add the following line for ease of access:

Alias /phpmyadmin /usr/share/phpMyAdmin

What is the difference between MacVim and regular Vim?

The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.

I can finally copy paste between MacVim on my terminal and the rest of my applications.

python NameError: global name '__file__' is not defined

change your codes as follows! it works for me. `

os.path.dirname(os.path.abspath("__file__"))

ng-if, not equal to?

This is now possible as of AngularJS 1.5.10, using ng-switch-when-separator

_x000D_
_x000D_
var app = angular.module("app", []); _x000D_
_x000D_
app.controller("ctrl", function($scope) {_x000D_
    $scope.myDataSet = [{Name: 'Michelle', Gender: 'Female', DOB: '01/12/1986', Payment: [{Status: '0'}]},{Name: 'Steve', Gender: 'Male', DOB: '11/12/1982', Payment: [{Status: '1'}]},{Name: 'Dan', Gender: 'Male', DOB: '03/22/1976', Payment: [{Status: '2'}]},{Name: 'Doug', Gender: 'Male', DOB: '02/02/1980', Payment: [{Status: '3'}]},{Name: 'Mary', Gender: 'Female', DOB: '04/02/1976', Payment: [{Status: '4'}]},{Name: 'Cheyenne', Gender: 'Female', DOB: '07/10/1981', Payment: [{Status: '5'}]},{Name: 'Bob', Gender: 'Male', DOB: '02/16/1990', Payment: [{Status: '6'}]},{Name: 'Bad data', Gender: 'Blank', DOB: '01/01/1970', Payment: [{Status: '7'}]}];_x000D_
});
_x000D_
<script src="https://code.angularjs.org/1.5.10/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="ctrl">_x000D_
    <div ng-repeat="details in myDataSet" ng-switch on="details.Payment[0].Status">_x000D_
_x000D_
        <p>{{ details.Name }}</p>_x000D_
        <p>{{ details.DOB  }}</p>_x000D_
_x000D_
        <div ng-switch-when="0">_x000D_
            <p>No payment</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="1|2" ng-switch-when-separator="|">_x000D_
            <p>Late</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="3|4|5" ng-switch-when-separator="|">_x000D_
            <p>Some payment made</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="6">_x000D_
            <p>Late and further taken out</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-default>_x000D_
            <p>Error</p>_x000D_
        </div>_x000D_
        _x000D_
        <p>{{ details.Gender}}</p>_x000D_
_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why am I getting the error "connection refused" in Python? (Sockets)

in your server.py file make : host ='192.168.1.94' instead of host = socket.gethostname()

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I solved the problem by adding dispatcher in UserControl_Loaded event

 Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
 {
     combobox.SelectedIndex = 0;
 }));

HTML: Changing colors of specific words in a string of text

use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>

How do I select a MySQL database through CLI?

Use the following steps to select the database:

mysql -u username -p

it will prompt for password, Please enter password. Now list all the databases

show databases;

select the database which you want to select using the command:

use databaseName;

select data from any table:

select * from tableName limit 10;

You can select your database using the command use photogallery; Thanks !

EditText underline below text property

Use android:backgroundTint="" in your EditText xml layout.

For api<21 you can use AppCompatEditText from support library thenapp:backgroundTint=""

ReCaptcha API v2 Styling

You can also choose between a dark or light ReCaptcha theme. I used this in one of my Angular 8 Apps

Regular Expression: Any character that is NOT a letter or number

Just for others to see:

someString.replaceAll("([^\\p{L}\\p{N}])", " ");

will remove any non-letter and non-number unicode characters.

Source

Format number as percent in MS SQL Server

And for all SQL Server versions

SELECT CAST(0.973684210526315789 * 100 AS DECIMAL(18, 2))

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

Creating custom function in React component

With React Functional way

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";

const App = () => {
  const saySomething = (something) => {
    console.log(something);
  };
  useEffect(() => {
    saySomething("from useEffect");
  });
  const handleClick = (e) => {
    saySomething("element clicked");
  };
  return (
    <Button variant="contained" color="primary" onClick={handleClick}>
      Hello World
    </Button>
  );
};

ReactDOM.render(<App />, document.querySelector("#app"));

https://codesandbox.io/s/currying-meadow-gm9g0

What's the difference between lists and tuples?

Difference between list and tuple

  1. Literal

    someTuple = (1,2)
    someList  = [1,2] 
    
  2. Size

    a = tuple(range(1000))
    b = list(range(1000))
    
    a.__sizeof__() # 8024
    b.__sizeof__() # 9088
    

    Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements.

  3. Permitted operations

    b    = [1,2]   
    b[0] = 3       # [3, 2]
    
    a    = (1,2)
    a[0] = 3       # Error
    

    That also means that you can't delete an element or sort a tuple. However, you could add a new element to both list and tuple with the only difference that since the tuple is immutable, you are not really adding an element but you are creating a new tuple, so the id of will change

    a     = (1,2)
    b     = [1,2]  
    
    id(a)          # 140230916716520
    id(b)          # 748527696
    
    a   += (3,)    # (1, 2, 3)
    b   += [3]     # [1, 2, 3]
    
    id(a)          # 140230916878160
    id(b)          # 748527696
    
  4. Usage

    As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used.

    a    = (1,2)
    b    = [1,2] 
    
    c = {a: 1}     # OK
    c = {b: 1}     # Error
    

Finding Android SDK on Mac and adding to PATH

1. How to find it

  • Open Android studio, go to Android Studio > Preferences
  • Search for sdk
  • Something similar to this (this is a Windows box as you can see) will show

You can see the location there – most of the time it is:

/Users/<name>/Library/Android/sdk

2. How to install it, if not there

Standalone SDK download page

3. How to add it to the path

Open your Terminal edit your ~/.bash_profile file in nano by typing:

nano ~/.bash_profile

If you use Zsh, edit ~/.zshrc instead.

Go to the end of the file and add the directory path to your $PATH:

export PATH="${HOME}/Library/Android/sdk/tools:${HOME}/Library/Android/sdk/platform-tools:${PATH}"
  • Save it by pressing Ctrl+X
  • Restart the Terminal
  • To see if it is working or not, type in the name of any file or binary which are inside the directories that you've added (e.g. adb) and verify it is opened/executed

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

See the wiki article:

In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https.

WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.

That is:

  • HTTPS is a transport layer (point-to-point) security mechanism
  • WS-Security is an application layer (end-to-end) security mechanism.

Finding modified date of a file/folder

To get the modified date on a single file try:

$lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime

To compare with another:

$dateA= $lastModifiedDate 
$dateB= (Get-Item "C:\other.tmp").LastWriteTime

if ($dateA -ge $dateB) {
  Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
} else {
  Write-Host("C:\foo.tmp was modified before C:\other.tmp")
}

Conditional formatting based on another cell's value

change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.

There is no mention that B5 contains any value so assuming 80% is .8 formatted as percentage without decimals and blank counts as "below":

Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:

=C5>0.8

with green fill and Done.

CF rule example

In SQL Server, what does "SET ANSI_NULLS ON" mean?

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql

When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name.

For e.g

DECLARE @TempVariable VARCHAR(10)
SET @TempVariable = NULL

SET ANSI_NULLS ON
SELECT 'NO ROWS IF SET ANSI_NULLS ON' where    @TempVariable = NULL
-- IF ANSI_NULLS ON , RETURNS ZERO ROWS


SET ANSI_NULLS OFF
SELECT 'THERE WILL BE A ROW IF ANSI_NULLS OFF' where    @TempVariable =NULL
-- IF ANSI_NULLS OFF , THERE WILL BE ROW !

Simple file write function in C++

You need to declare the prototype of your writeFile function, before actually using it:

int writeFile( void );

int main( void )
{
   ...

how to check for null with a ng-if values in a view with angularjs?

See the correct way with your example:

<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>

Regards, Nicholls

Converting PKCS#12 certificate into PEM using OpenSSL

There is a free and open-source GUI tool KeyStore Explorer to work with crypto key containers. Using it you can export a certificate or private key into separate files or convert the container into another format (jks, pem, p12, pkcs12, etc)

enter image description here

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

In my case, just using flex-shrink: 0 didn't work. But adding flex-grow: 1 to it worked.

.item {
    flex-shrink: 0;
    flex-grow: 1;
}

Spring MVC UTF-8 Encoding

In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).

The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.

If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).

What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.

Difference between <? super T> and <? extends T> in Java

extends

The wildcard declaration of List<? extends Number> foo3 means that any of these are legal assignments:

List<? extends Number> foo3 = new ArrayList<Number>();  // Number "extends" Number (in this context)
List<? extends Number> foo3 = new ArrayList<Integer>(); // Integer extends Number
List<? extends Number> foo3 = new ArrayList<Double>();  // Double extends Number
  1. Reading - Given the above possible assignments, what type of object are you guaranteed to read from List foo3:

    • You can read a Number because any of the lists that could be assigned to foo3 contain a Number or a subclass of Number.
    • You can't read an Integer because foo3 could be pointing at a List<Double>.
    • You can't read a Double because foo3 could be pointing at a List<Integer>.
  2. Writing - Given the above possible assignments, what type of object could you add to List foo3 that would be legal for all the above possible ArrayList assignments:

    • You can't add an Integer because foo3 could be pointing at a List<Double>.
    • You can't add a Double because foo3 could be pointing at a List<Integer>.
    • You can't add a Number because foo3 could be pointing at a List<Integer>.

You can't add any object to List<? extends T> because you can't guarantee what kind of List it is really pointing to, so you can't guarantee that the object is allowed in that List. The only "guarantee" is that you can only read from it and you'll get a T or subclass of T.

super

Now consider List <? super T>.

The wildcard declaration of List<? super Integer> foo3 means that any of these are legal assignments:

List<? super Integer> foo3 = new ArrayList<Integer>();  // Integer is a "superclass" of Integer (in this context)
List<? super Integer> foo3 = new ArrayList<Number>();   // Number is a superclass of Integer
List<? super Integer> foo3 = new ArrayList<Object>();   // Object is a superclass of Integer
  1. Reading - Given the above possible assignments, what type of object are you guaranteed to receive when you read from List foo3:

    • You aren't guaranteed an Integer because foo3 could be pointing at a List<Number> or List<Object>.
    • You aren't guaranteed a Number because foo3 could be pointing at a List<Object>.
    • The only guarantee is that you will get an instance of an Object or subclass of Object (but you don't know what subclass).
  2. Writing - Given the above possible assignments, what type of object could you add to List foo3 that would be legal for all the above possible ArrayList assignments:

    • You can add an Integer because an Integer is allowed in any of above lists.
    • You can add an instance of a subclass of Integer because an instance of a subclass of Integer is allowed in any of the above lists.
    • You can't add a Double because foo3 could be pointing at an ArrayList<Integer>.
    • You can't add a Number because foo3 could be pointing at an ArrayList<Integer>.
    • You can't add an Object because foo3 could be pointing at an ArrayList<Integer>.

PECS

Remember PECS: "Producer Extends, Consumer Super".

  • "Producer Extends" - If you need a List to produce T values (you want to read Ts from the list), you need to declare it with ? extends T, e.g. List<? extends Integer>. But you cannot add to this list.

  • "Consumer Super" - If you need a List to consume T values (you want to write Ts into the list), you need to declare it with ? super T, e.g. List<? super Integer>. But there are no guarantees what type of object you may read from this list.

  • If you need to both read from and write to a list, you need to declare it exactly with no wildcards, e.g. List<Integer>.

Example

Note this example from the Java Generics FAQ. Note how the source list src (the producing list) uses extends, and the destination list dest (the consuming list) uses super:

public class Collections { 
  public static <T> void copy(List<? super T> dest, List<? extends T> src) {
      for (int i = 0; i < src.size(); i++) 
        dest.set(i, src.get(i)); 
  } 
}

Also see How can I add to List<? extends Number> data structures?

Extracting date from a string in Python

For extracting the date from a string in Python; the best module available is the datefinder module.

You can use it in your Python project by following the easy steps given below.

Step 1: Install datefinder Package

pip install datefinder

Step 2: Use It In Your Project

import datefinder

input_string = "monkey 2010-07-10 love banana"
# a generator will be returned by the datefinder module. I'm typecasting it to a list. Please read the note of caution provided at the bottom.
matches = list(datefinder.find_dates(input_string))

if len(matches) > 0:
    # date returned will be a datetime.datetime object. here we are only using the first match.
    date = matches[0]
    print date
else:
    print 'No dates found'

note: if you are expecting a large number of matches; then typecasting to list won't be a recommended way as it will be having a big performance overhead.

Jquery resizing image

$(function() {
    $('.story-small img').each(function() {
        var maxWidth = 100; // Max width for the image
        var maxHeight = 100;    // Max height for the image
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
        // Check if the current width is larger than the max
        if(width>height && width>maxWidth)
        {
            ratio = maxWidth / width;   // get ratio for scaling image
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio); // Scale height based on ratio
        }
        else if(height>width && height>maxHeight)
        {
            ratio = maxHeight / height; // get ratio for scaling image
            $(this).css("height", maxHeight);   // Set new height
            $(this).css("width", width * ratio);    // Scale width based on ratio
        }
    });
});

Get line number while using grep

In order to display the results with the line numbers, you might try this

grep -nr "word to search for" /path/to/file/file 

The result should be something like this:

linenumber: other data "word to search for" other data

How to add a button dynamically in Android?

Try this code. It will work fine..

public class DynamicViewsActivity extends Activity {

Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_dynamic_views);
    ScrollView scrl=new ScrollView(this);
    final LinearLayout ll=new LinearLayout(this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(100, 500, 100, 200);
    scrl.addView(ll);
    Button add_btn=new Button(this);
    add_btn.setText("Click Here");

    ll.addView(add_btn, layoutParams);


    final Context context = this;

    add_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(context, App2Activity.class);
            startActivity(intent);
        }
    });
    this.setContentView(scrl);
}
}

NameError: global name is not defined

You need to do:

import sqlitedbx

def main():
    db = sqlitedbx.SqliteDBzz()
    db.connect()

if __name__ == "__main__":
    main()

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

In my case, it was because I was not pointing to the correct package where I kept my feature (cucumber) file(s). This was a case of wrong path specification. See code snippet below:

import org.junit.runner.RunWith;

import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        
    features = "src/test/features",
    glue = "stepDefinitions"
        
        )

Below is the screenshot of the JUnit error: Junit Runner Error

Below is the Stack Trace in the console:

enter image description here

The final solution was I had to change the path to the correct package where my feature files were kept.

See the corrected code snippet below:

package cucumberOptions;

import org.junit.runner.RunWith;

import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        
    features = "src/test/java/features",
    glue = "stepDefinitions"
        
        )

public class TestRunner {

}

How to return a dictionary | Python

def prepare_table_row(row):
    lst = [i.text for i in row if i != u'\n']
    return dict(rank = int(lst[0]),
                grade = str(lst[1]),
                channel=str(lst[2])),
                videos = float(lst[3].replace(",", " ")),
                subscribers = float(lst[4].replace(",", "")),
                views = float(lst[5].replace(",", "")))

Calculate Age in MySQL (InnoDb)

Since the question is being tagged for mysql, I have the following implementation that works for me and I hope similar alternatives would be there for other RDBMS's. Here's the sql:

select YEAR(now()) - YEAR(dob) - ( DAYOFYEAR(now()) < DAYOFYEAR(dob) ) as age 
from table 
where ...

Create table with jQuery - append

this is most better

html

<div id="here_table"> </div>

jQuery

$('#here_table').append( '<table>' );

for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' +  i + '</tr>' );

    for(ii=0;ii<3;ii++)
    {
    $('#here_table').append( '<td>' + 'result' +  i + '</tr>' );
    }
}

$('#here_table').append(  '</table>' );

How to set 'X-Frame-Options' on iframe?

you can do it in tomcat instance level config file (web.xml) need to add the 'filter' and filter-mapping' in web.xml config file. this will add the [X-frame-options = DENY] in all the page as it is a global setting.

<filter>
        <filter-name>httpHeaderSecurity</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>antiClickJackingEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>antiClickJackingOption</param-name>
          <param-value>DENY</param-value>
        </init-param>
    </filter>

  <filter-mapping> 
    <filter-name>httpHeaderSecurity</filter-name> 
    <url-pattern>/*</url-pattern>
</filter-mapping>

How to check for a JSON response using RSpec?

You can also define a helper function inside spec/support/

module ApiHelpers
  def json_body
    JSON.parse(response.body)
  end
end

RSpec.configure do |config| 
  config.include ApiHelpers, type: :request
end

and use json_body whenever you need to access the JSON response.

For example, inside your request spec you can use it directly

context 'when the request contains an authentication header' do
  it 'should return the user info' do
    user  = create(:user)
    get URL, headers: authenticated_header(user)

    expect(response).to have_http_status(:ok)
    expect(response.content_type).to eq('application/vnd.api+json')
    expect(json_body["data"]["attributes"]["email"]).to eq(user.email)
    expect(json_body["data"]["attributes"]["name"]).to eq(user.name)
  end
end

jQuery Ajax PUT with parameters

For others who wind up here like I did, you can use AJAX to do a PUT with parameters, but they are sent as the body, not as query strings.

How to use CSS to surround a number with a circle?

Do something like this in your css

 div {
    width: 10em; height: 10em; 
    -webkit-border-radius: 5em; -moz-border-radius: 5em;
  }
  p {
    text-align: center; margin-top: 4.5em;
  }

Use the paragraph tag to write the text. Hope that helps

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

Excel 2007 - Compare 2 columns, find matching values

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) will solve this issue.

This will search for a value in the first column to the left and return the value in the same row from a specific column.

Item frequency count in Python

The answer below takes some extra cycles, but it is another method

def func(tup):
    return tup[-1]


def print_words(filename):
    f = open("small.txt",'r')
    whole_content = (f.read()).lower()
    print whole_content
    list_content = whole_content.split()
    dict = {}
    for one_word in list_content:
        dict[one_word] = 0
    for one_word in list_content:
        dict[one_word] += 1
    print dict.items()
    print sorted(dict.items(),key=func)

Remove innerHTML from div

jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.

Just do

divToUpdate.html("");

or

divToUpdate.empty();

How should I unit test multithreaded code?

Pete Goodliffe has a series on the unit testing of threaded code.

It's hard. I take the easier way out and try to keep the threading code abstracted from the actual test. Pete does mention that the way I do it is wrong but I've either got the separation right or I've just been lucky.

How to add external JS scripts to VueJS Components

Simplest solution is to add the script in the index.html file of your vue-project

index.html:

 <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>vue-webpack</title>
      </head>
      <body>
        <div id="app"></div>
        <!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
    0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
    for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
    MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
    mixpanel.init("xyz");</script><!-- end Mixpanel -->
        <script src="/dist/build.js"></script>
      </body>
    </html>

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

I tested the following procedure under macOS Mojave 10.14.6 (18G3020).

Launch Automator. Create a document of type “Quick Action”:

quick action template

(In older versions of macOS, use the “Service” template.)

In the new Automator document, add a “Run AppleScript” action. (You can type “run applescript” into the search field at the top of the action list to find it.) Here's the AppleScript to paste into the action:

on run {input, parameters}
    tell application "Terminal"
        if it is running then
            do script ""
        end if
        activate
    end tell
end run

Set the “Workflow receives” popup to “no input”. It should look like this overall:

workflow with applescript

Save the document with the name “New Terminal”. Then go to the Automator menu (or the app menu in any running application) and open the Services submenu. You should now see the “New Terminal” quick action:

New Terminal service menu item

If you click the “New Terminal” menu item, you'll get a dialog box:

permission dialog

Click OK to allow the action to run. You'll see this dialog once in each application that's frontmost when you use the action. In other words, the first time you use the action while Finder is frontmost, you'll see the dialog. And the first time you use the action while Safari is frontmost, you'll see the dialog. And so on.

After you click OK in the dialog, Terminal should open a new window.

To assign a keyboard shortcut to the quick action, choose the “Services Preferences…” item from the Services menu. (Or launch System Preferences, choose the Keyboard pane, then choose the Shortcuts tab, then choose Services from the left-hand list.) Scroll to the bottom of the right-hand list and find the New Terminal service. Click it and you should see an “Add Shortcut” button:

add shortcut button

Click the button and press your preferred keyboard shortcut. Then, scratch your head, because (when I tried it) the Add Shortcut button reappears. But click the button again and you should see your shortcut:

keyboard shortcut set

Now you should be able to press your keyboard shortcut in most circumstances to get a new terminal window.

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

counting number of directories in a specific directory

A pure bash solution:

shopt -s nullglob
dirs=( /path/to/directory/*/ )
echo "There are ${#dirs[@]} (non-hidden) directories"

If you also want to count the hidden directories:

shopt -s nullglob dotglob
dirs=( /path/to/directory/*/ )
echo "There are ${#dirs[@]} directories (including hidden ones)"

Note that this will also count links to directories. If you don't want that, it's a bit more difficult with this method.


Using find:

find /path/to/directory -type d \! -name . -prune -exec printf x \; | wc -c

The trick is to output an x to stdout each time a directory is found, and then use wc to count the number of characters. This will count the number of all directories (including hidden ones), excluding links.


The methods presented here are all safe wrt to funny characters that can appear in file names (spaces, newlines, glob characters, etc.).

Can a Windows batch file determine its own file name?

Using the following script, based on SLaks answer, I determined that the correct answer is:

echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0

And here is my test script:

@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause

What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

Scroll to bottom of div with Vue.js

I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight BUT you have to put this into the updated() hook for the whole solution to work.

data(){
return {
  conversation: [
    {
    }
  ]
 },
mounted(){
 EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
  this.conversation.push(textMsg)
  // Didn't work doing scroll here
 })
},
updated(){              <=== PUT IT HERE !!
  var elem = this.$el
  elem.scrollTop = elem.clientHeight;
},

How to use ADB to send touch events to device using sendevent command?

Consider using Android's uiautomator, with adb shell uiautomator [...] or directly using the .jar that comes with the SDK.

How to store decimal values in SQL Server?

DECIMAL(18,0) will allow 0 digits after the decimal point.

Use something like DECIMAL(18,4) instead that should do just fine!

That gives you a total of 18 digits, 4 of which after the decimal point (and 14 before the decimal point).

Excel: last character/string match in a string

How about creating a custom function and using that in your formula? VBA has a built-in function, InStrRev, that does exactly what you're looking for.

Put this in a new module:

Function RSearch(str As String, find As String)
    RSearch = InStrRev(str, find)
End Function

And your function will look like this (assuming the original string is in B1):

=LEFT(B1,RSearch(B1,"\"))

REST vs JSON-RPC?

If your service works fine with only models and the GET/POST/PUT/DELETE pattern, use pure REST.

I agree that HTTP is originally designed for stateless applications.

But for modern, more complex (!) real-time (web) applications where you will want to use Websockets (which often imply statefulness), why not use both? JSON-RPC over Websockets is very light so you have the following benefits:

  • Instant updates on every client (define your own server-to-client RPC call for updating the models)
  • Easy to add complexity (try to make an Etherpad clone with only REST)
  • If you do it right (add RPC only as an extra for real-time), most is still usable with only REST (except if the main feature is a chat or something)

As you are only designing the server side API, start with defining REST models and later add JSON-RPC support as needed, keeping the number of RPC calls to a minimum.

(and sorry for parentheses overuse)

GenyMotion Unable to start the Genymotion virtual device

I'm running OSX. The solutions suggested didn't work for me. I'm using OSX Yosemite. I restarted my Mac then I uninstalled VirtualBox by launching the uninstall script (which is shown when you launch the dmg of VirtualBox) then reinstalled it. I also uninstalled and reinstalled Genymotion. Now everything is working smooth.

How to check if an email address exists without sending an email?

Not really.....Some server may not check the "rcpt to:"

http://www.freesoft.org/CIE/RFC/1123/92.htm

Doing so is security risk.....

If the server do, you can write a bot to discovery every address on the server....

Where can I read the Console output in Visual Studio 2015

The simple way is using System.Diagnostics.Debug.WriteLine()

Your can then read what you're writing to the output by clicking the menu "DEBUG" -> "Windows" -> "Output".

Adding an onclick event to a div element

Its possible, we can specify onclick event in

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
    document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
    document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>

How do I disable a href link in JavaScript?

So the above solutions make the link not work, but don't make it visible (AFAICT) that the link is no longer valid. I've got a situation where I've got a series of pages and want to disable (and make it obvious that it's disabled) the link that points to the current page.

So:

window.onload = function() {
    var topics = document.getElementsByClassName("topics");
    for (var i = topics.length-1; i > -1; i-- ) {
        for (var j = topics[i].childNodes.length-1; j > -1; j--) {
             if (topics[i].childNodes[j].nodeType == 1) {
                if (topics[i].childNodes[j].firstChild.attributes[0].nodeValue == this.n_root3) {
                    topics[i].childNodes[j].innerHTML = topics[i].childNodes[j].firstChild.innerHTML;
                }
            }
        }
    }
}

This walks through the list of links, finds the one that points to the current page (the n_root3 might be a local thing, but I imagine document must have something similar), and replaces the link with the link text contents.

HTH

"Line contains NULL byte" in CSV reader (Python)

I've solved a similar problem with an easier solution:

import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))

The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the documentation.

CustomErrors mode="Off"

My problem was that i had this defined in my web.config

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <remove statusCode="500" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error/Internal" />
</httpErrors>

How to get a tab character?

Tab is [HT], or character number 9, in the unicode library.

How do I implement charts in Bootstrap?

Later than my previous answer, but may be useful anyway; while gRaphaël Charting may be an outdated alternative, a more recent and nicer option may be http://chartjs.org - still without any Flash, with a MIT license, and a recently updated GitHub.

I've been using it myself since my last answer, so now I have some web apps with one and some with the other.

If you are starting a project anew, try with Chart.js first.

Switching users inside Docker image to a non-root user

In case you need to perform privileged tasks like changing permissions of folders you can perform those tasks as a root user and then create a non-privileged user and switch to it:

From <some-base-image:tag>

# Switch to root user
USER root # <--- Usually you won't be needed it - Depends on base image

# Run privileged command
RUN apt install <packages>
RUN apt <privileged command>

# Set user and group
ARG user=appuser
ARG group=appuser
ARG uid=1000
ARG gid=1000
RUN groupadd -g ${gid} ${group}
RUN useradd -u ${uid} -g ${group} -s /bin/sh -m ${user} # <--- the '-m' create a user home directory

# Switch to user
USER ${uid}:${gid}

# Run non-privileged command
RUN apt <non-privileged command>

How do I rename the android package name?

Lets address the two use cases

**Rename a package name or Trim a package **

com.mycompany.mystupidapplicationname to com.mycompany.brandname

or

com.someothercompany.mystupidapplicationname to com.someothercompany.mystupidapplicationname

or

com.someothercompany.mystupidapplicationname to someothercompany.brandname

  1. Select Package in the drop down in Android Studio

Select package in dropdown

  1. Right click on the package which contains your MainActivity and refractor it

enter image description here

  1. Select Rename Package and everything will work like a charm

But this will only rename the last part of package name

  1. To rename the first or second part of package name . Create a new dummy file in the part of package which you want to rename. the file will be created inside mycompany.com.myapplicationame. Then move the file inside mycompany(right click => move) to make mycompany appear in tree view. This will make that part part of the tree view and will you help you to do a right click and rename that part.

enter image description here

  1. Delete the dummy file

  2. To Trim a package , simply right click and move the package part inside its grand parent

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

What is the difference between CSS and SCSS?

CSS is the styling language that any browser understands to style webpages.

SCSS is a special type of file for SASS, a program written in Ruby that assembles CSS style sheets for a browser, and for information, SASS adds lots of additional functionality to CSS like variables, nesting and more which can make writing CSS easier and faster.
SCSS files are processed by the server running a web app to output a traditional CSS that your browser can understand.

Returning an empty array

I'm pretty sure you should go with bar(); because with foo(); it creates a List (for nothing) since you create a new File[0] in the end anyway, so why not go with directly returning it!

Eclipse CDT: Symbol 'cout' could not be resolved

I am using Ubuntu 12.04 / Eclipse 4.2.1 / CDT 8.1.1 and I used to have the same problem for quite some time: importing a C++ project from SVN would cause these annoying "Unresolved inclusion" errors and I would instead have to create a new project and copy the files in there as a work-around (still partial, since SVN functionality would not be there!).

At last, I have just found a simple, satisfactory solution:

  • Go to Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros etc. -> Providers and check Enable language settings providers for this project.

  • Restart Eclipse.

Hopefully that already does the trick.

Where does the iPhone Simulator store its data?

I have no affiliation with this program, but if you are looking to open any of this in the finder SimPholders makes it incredibly easy.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

In addition to @yogihosting's answer, if you are using DirectAdmin, then follow these steps:

  1. Go to the DirectAdmin's login page. Usually, its port is 2222.
  2. Login as administrator. Its username is admin by default.
  3. From the "Access Level" on the right panel, make sure you are on "Admin Level". If not, change to it.
  4. From the "Extra Features" section, click on "Custom HTTPD Configurations".
  5. Choose the domain you want to change.
  6. Enter the configurations you want to change in the textarea at the top of the page. You should consider the existing configuration file and modify values based on it. For example, if you see that open_basedir is set inside a <Directory>, maybe you should surround your change in the related <Directory> tag:

    <Directory "/path/to/directory">
        php_admin_value open_basedir none
    </Directory>
    
  7. After making necessary changes, click on the "Save" button.

  8. You should now see your changes saved to the configuration file if they were valid.

There is another way of editing the configuration file, however:

Caution: Be careful, and use the following steps at your own risk, as you may run into errors, or it may lead to downtime. The recommended way is the previous one, as it prevents you from modifying configuration file improperly and show you the error.

  1. Login to your server as root.
  2. Go to /usr/local/directadmin/data/users. From the listed users, go to one related to the domain you want to change.
  3. Here, there is an httpd.conf file. Make a backup from it:

    cp httpd.conf httpd.conf.back
    
  4. Now edit the configuration file with your editor of choice. For example, edit existing open_basedir to none. Do not try to remove things, or you may experience downtime. Save the file after editing.

  5. Restart the Apache web server using one of the following ways (use sudo if needed):

    httpd -k graceful
    apachectl -k graceful
    apache2 -k graceful
    
  6. If your encounter any errors, then replace the main configuration file with the backed-up file, and restart the web server.

Again, the first solution is the preferred one, and you should not try the second method at the first time. As it is noted in the caution, the advantage of the first way is that it prevents saving your bad-configured stuff.

Hope it helps!

How to add content to html body using JS?

In most browsers, you can use a javascript variable instead of using document.getElementById. Say your html body content is like this:

<section id="mySection"> Hello </section>

Then you can just refer to mySection as a variable in javascript:

mySection.innerText += ', world'
// same as: document.getElementById('mySection').innerText += ', world'

See this snippet:

_x000D_
_x000D_
mySection.innerText += ', world!'
_x000D_
<section id="mySection"> Hello </section>
_x000D_
_x000D_
_x000D_

Merge (Concat) Multiple JSONObjects in Java

You can create a new JSONObject like this:

JSONObject merged = new JSONObject();
JSONObject[] objs = new JSONObject[] { Obj1, Obj2 };
for (JSONObject obj : objs) {
    Iterator it = obj.keys();
    while (it.hasNext()) {
        String key = (String)it.next();
        merged.put(key, obj.get(key));
    }
}

With this code, if you have any repeated keys between Obj1 and Obj2 the value in Obj2 will remain. If you want the values in Obj1 to be kept you should invert the order of the array in line 2.

How can I check if a background image is loaded?

try this:

$('<img/>').attr('src', 'http://picture.de/image.png').on('load', function() {
   $(this).remove(); // prevent memory leaks as @benweet suggested
   $('body').css('background-image', 'url(http://picture.de/image.png)');
});

this will create new image in memory and use load event to detect when the src is loaded.

Storing JSON in database vs. having a new column for each key

some time joins on the table will be an overhead. lets say for OLAP. if i have two tables one is ORDERS table and other one is ORDER_DETAILS. For getting all the order details we have to join two tables this will make the query slower when no of rows in the tables increase lets say in millions or so.. left/right join is too slower than inner join. I Think if we add JSON string/Object in the respective ORDERS entry JOIN will be avoided. add report generation will be faster...

How can I determine if a variable is 'undefined' or 'null'?

You can check if the value is undefined or null by simply using typeof:

if(typeof value == 'undefined'){

how to make jni.h be found?

Installing the OpenJDK Development Kit (JDK) should fix your problem.

sudo apt-get install openjdk-X-jdk

This should make you able to compile without problems.

Show two digits after decimal point in c++

The easiest way to do this, is using cstdio's printf. Actually, i'm surprised that anyone mentioned printf! anyway, you need to include the library, like this...

#include<cstdio>

int main() {
    double total;
    cin>>total;
    printf("%.2f\n", total);
}

This will print the value of "total" (that's what %, and then ,total does) with 2 floating points (that's what .2f does). And the \n at the end, is just the end of line, and this works with UVa's judge online compiler options, that is:

g++ -lm -lcrypt -O2 -pipe -DONLINE_JUDGE filename.cpp

the code you are trying to run will not run with this compiler options...

How does one reorder columns in a data frame?

A dplyr solution (part of the tidyverse package set) is to use select:

select(table, "Time", "Out", "In", "Files") 

# or

select(table, Time, Out, In, Files)

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.

# Find the source files
$sourceDir="X:\sourceFolder"

# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse |  foreach {

    # Remove the original  root folder
    $split = $_.Fullname  -split '\\'
    $DestFile =  $split[1..($split.Length - 1)] -join '\' 

    # Build the new  destination file path
    $DestFile = $targetDir+$DestFile

    # Move-Item won't  create the folder structure so we have to 
    # create a blank file  and then overwrite it
    $null = New-Item -Path  $DestFile -Type File -Force
    Move-Item -Path  $_.FullName -Destination $DestFile -Force
}

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

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

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

This ends up with a query like :

(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

Android: how to handle button click

Option 1 and 2 involves using inner class that will make the code kind of clutter. Option 2 is sort of messy because there will be one listener for every button. If you have small number of button, this is okay. For option 4 I think this will be harder to debug as you will have to go back and fourth the xml and java code. I personally use option 3 when I have to handle multiple button clicks.

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

How do I deal with certificates using cURL while trying to access an HTTPS url?

Just create the folders, which is missing in your system..

/etc/pki/tls/certs/

and create the file using the following command,

sudo apt-get install ca-certificates

and then copy and paste the certificate to the destination folder, which is showing in your error.. mine was " with message 'error setting certificate verify locations: CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none' in " make sure you paste the file to the exact location mentioned in the error. Use the following command to copy paste..

sudo cp /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt

Fixed.

JavaScript calculate the day of the year (1 - 366)

This is a solution that avoids the troublesome Date object and timezone issues, it requires that your input date be in the format "yyyy-dd-mm". If you want to change the format, then modify date_str_to_parts function:

    function get_day_of_year(str_date){
    var date_parts = date_str_to_parts(str_date);
    var is_leap = (date_parts.year%4)==0;
    var acct_for_leap = (is_leap && date_parts.month>2);
    var day_of_year = 0;

    var ary_months = [
        0,
        31, //jan
        28, //feb(non leap)
        31, //march
        30, //april
        31, //may
        30, //june
        31, //july
        31, //aug
        30, //sep
        31, //oct
        30, //nov   
        31  //dec
        ];


    for(var i=1; i < date_parts.month; i++){
        day_of_year += ary_months[i];
    }

    day_of_year += date_parts.date;

    if( acct_for_leap ) day_of_year+=1;

    return day_of_year;

}

function date_str_to_parts(str_date){
    return {
        "year":parseInt(str_date.substr(0,4),10),
        "month":parseInt(str_date.substr(5,2),10),
        "date":parseInt(str_date.substr(8,2),10)
    }
}

How do I concatenate const/literal strings in C?

You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.

Specifically:

...snip...

destination

Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

...snip...

http://www.cplusplus.com/reference/clibrary/cstring/strcat.html

There's an example here as well.

How can I get this ASP.NET MVC SelectList to work?

If you want to pass some random text to your DropDownList, for example --Select-- you can easy do this using this code:

@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "--Select--", new { @class = "form-control" })

How can I serve static html from spring boot?

As it is written before, some folders (/META-INF/resources/, /resources/, /static/, /public/) serve static content by default, conroller misconfiguration can break this behaviour.

It is a common pitfall that people define the base url of a controller in the @RestController annotation, instead of the @RequestMapping annotation on the top of the controllers.

This is wrong:

@RestController("/api/base")
public class MyController {

    @PostMapping
    public String myPostMethod( ...) {

The above example will prevent you from opening the index.html. The Spring expects a POST method at the root, because the myPostMethod is mapped to the "/" path.

You have to use this instead:

@RestController
@RequestMapping("/api/base")
public class MyController {

    @PostMapping
    public String myPostMethod( ...) {

Sorting arraylist in alphabetical order (case insensitive)

Custom Comparator should help

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }
});

Or if you are using Java 8:

list.sort(String::compareToIgnoreCase);

How to create a MySQL hierarchical recursive query?

The best approach I've come up with is

  1. Use lineage to store\sort\trace trees. That's more than enough, and works thousands times faster for reading than any other approach. It also allows to stay on that pattern even if DB will change(as ANY db will allow that pattern to be used)
  2. Use function that determines lineage for specific ID.
  3. Use it as you wish (in selects, or on CUD operations, or even by jobs).

Lineage approach descr. can be found wherever, for example Here or here. As of function - that is what enspired me.

In the end - got more-or-less simple, relatively fast, and SIMPLE solution.

Function's body

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `get_lineage`(the_id INT) RETURNS text CHARSET utf8
    READS SQL DATA
BEGIN

 DECLARE v_rec INT DEFAULT 0;

 DECLARE done INT DEFAULT FALSE;
 DECLARE v_res text DEFAULT '';
 DECLARE v_papa int;
 DECLARE v_papa_papa int DEFAULT -1;
 DECLARE csr CURSOR FOR 
  select _id,parent_id -- @n:=@n+1 as rownum,T1.* 
  from 
    (SELECT @r AS _id,
        (SELECT @r := table_parent_id FROM table WHERE table_id = _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := the_id, @l := 0,@n:=0) vars,
        table m
    WHERE @r <> 0
    ) T1
    where T1.parent_id is not null
 ORDER BY T1.lvl DESC;
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    open csr;
    read_loop: LOOP
    fetch csr into v_papa,v_papa_papa;
        SET v_rec = v_rec+1;
        IF done THEN
            LEAVE read_loop;
        END IF;
        -- add first
        IF v_rec = 1 THEN
            SET v_res = v_papa_papa;
        END IF;
        SET v_res = CONCAT(v_res,'-',v_papa);
    END LOOP;
    close csr;
    return v_res;
END

And then you just

select get_lineage(the_id)

Hope it helps somebody :)

How to pause for specific amount of time? (Excel/VBA)

this works flawlessly for me. insert any code before or after the "do until" loop. In your case, put the 5 lines (time1= & time2= & "do until" loop) at the end inside your do loop

sub whatever()
Dim time1, time2

time1 = Now
time2 = Now + TimeValue("0:00:01")
    Do Until time1 >= time2
        DoEvents
        time1 = Now()
    Loop

End sub

How to access a property of an object (stdClass Object) member/element of an array?

Try this, working fine -

$array = json_decode(json_encode($array), true);

jQuery load first 3 elements, click "load more" to display next 5 elements

Simple and with little changes. And also hide load more when entire list is loaded.

jsFiddle here.

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#showLess').hide();
    var items =  25;
    var shown =  3;
    $('#loadMore').click(function () {
        $('#showLess').show();
        shown = $('#myList li:visible').size()+5;
        if(shown< items) {$('#myList li:lt('+shown+')').show();}
        else {$('#myList li:lt('+items+')').show();
             $('#loadMore').hide();
             }
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

Created Button Click Event c#

if your button is inside your form class:

buttonOk.Click += new EventHandler(your_click_method);

(might not be exactly EventHandler)

and in your click method:

this.Close();

If you need to show a message box:

MessageBox.Show("test");

Identifier is undefined

From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined. Reasonably, because with the current syntax the next function definition (in this case is ac_search) will be included under the addWord scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

Selecting a row of pandas series/dataframe by integer index

To index-based access to the pandas table, one can also consider numpy.as_array option to convert the table to Numpy array as

np_df = df.as_matrix()

and then

np_df[i] 

would work.

how to convert a string to an array in php

here, Use explode() function to convert string into array, by a string

click here to know more about explode()

$str = "this is string";
$delimiter = ' ';  // use any string / character by which, need to split string into Array
$resultArr = explode($delimiter, $str);  
var_dump($resultArr);

Output :

Array
(
    [0] => "this",
    [1] => "is",
    [2] => "string "
)

it is same as the requirements:

  arr[0]="this";
  arr[1]="is";
  arr[2]="string";

Can we make unsigned byte in Java

There is no unsigned byte in Java, but if you want to display a byte, you can do,

int myInt = 144;

byte myByte = (byte) myInt;

char myChar = (char) (myByte & 0xFF);

System.out.println("myChar :" + Integer.toHexString(myChar));

Output:

myChar : 90

For more information, please check, How to display a hex/byte value in Java.

Finding local IP addresses using Python's stdlib

I had to solve the problem "Figure out if an IP address is local or not", and my first thought was to build a list of IPs that were local and then match against it. This is what led me to this question. However, I later realized there is a more straightfoward way to do it: Try to bind on that IP and see if it works.

_local_ip_cache = []
_nonlocal_ip_cache = []
def ip_islocal(ip):
    if ip in _local_ip_cache:
        return True
    if ip in _nonlocal_ip_cache:
        return False
    s = socket.socket()
    try:
        try:
            s.bind((ip, 0))
        except socket.error, e:
            if e.args[0] == errno.EADDRNOTAVAIL:
                _nonlocal_ip_cache.append(ip)
                return False
            else:
                raise
    finally:
        s.close()
    _local_ip_cache.append(ip)
    return True

I know this doesn't answer the question directly, but this should be helpful to anyone trying to solve the related question and who was following the same train of thought. This has the advantage of being a cross-platform solution (I think).

jQuery Validation plugin: validate check box

There is the easy way

HTML:

<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]"  />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>

JQUERY:

$("#submit").on("click",function(){
    if (($("input[name*='test']:checked").length)<=0) {
        alert("You must check at least 1 box");
    }
    return true;
});

For this you not need any plugin. Enjoy;)

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

Plotting in a non-blocking way with Matplotlib

Iggy's answer was the easiest for me to follow, but I got the following error when doing a subsequent subplot command that was not there when I was just doing show:

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

In order to avoid this error, it helps to close (or clear) the plot after the user hits enter.

Here's the code that worked for me:

def plt_show():
    '''Text-blocking version of plt.show()
    Use this instead of plt.show()'''
    plt.draw()
    plt.pause(0.001)
    input("Press enter to continue...")
    plt.close()

Get current directory name (without full path) in a Bash script

The following commands will result in printing your current working directory in a bash script.

pushd .
CURRENT_DIR="`cd $1; pwd`"
popd
echo $CURRENT_DIR

Append key/value pair to hash with << in Ruby

There is merge!.

h = {}
h.merge!(key: "bar")
# => {:key=>"bar"}

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

Fully custom validation error message with Rails

Here is another way:

If you use this template:

<% if @thing.errors.any? %>
  <ul>
    <% @thing.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
  </ul>
<% end %>

You can write you own custom message like this:

class Thing < ActiveRecord::Base

  validate :custom_validation_method_with_message

  def custom_validation_method_with_message
    if some_model_attribute.blank?
      errors.add(:_, "My custom message")
    end
  end

This way, because of the underscore, the full message becomes " My custom message", but the extra space in the beginning is unnoticeable. If you really don't want that extra space at the beginning just add the .lstrip method.

<% if @thing.errors.any? %>
  <ul>
    <% @thing.errors.full_messages.each do |message| %>
      <li><%= message.lstrip %></li>
    <% end %>
  </ul>
<% end %>

The String.lstrip method will get rid of the extra space created by ':_' and will leave any other error messages unchanged.

Or even better, use the first word of your custom message as the key:

  def custom_validation_method_with_message
    if some_model_attribute.blank?
      errors.add(:my, "custom message")
    end
  end

Now the full message will be "My custom message" with no extra space.

If you want the full message to start with a word capitalized like "URL can't be blank" it cannot be done. Instead try adding some other word as the key:

  def custom_validation_method_with_message
    if some_model_attribute.blank?
      errors.add(:the, "URL can't be blank")
    end
  end

Now the full message will be "The URL can't be blank"

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

Keyboard shortcuts with jQuery

    <script type="text/javascript">
        $(document).ready(function(){
            $("#test").keypress(function(e){
                if (e.which == 103) 
                {
                    alert('g'); 
                };
            });
        });
    </script>

    <input type="text" id="test" />

this site says 71 = g but the jQuery code above thought otherwise

Capital G = 71, lowercase is 103

What's the right way to decode a string that has special HTML entities in it?

If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:

function parseHtmlEntities(str) {
    return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
        var num = parseInt(numStr, 10); // read num as normal number
        return String.fromCharCode(num);
    });
}

[Edit]

Note: this would only work for numeric html-entities, and not stuff like &oring;.

[Edit 2]

Fixed the function (some typos), test here: http://jsfiddle.net/Be2Bd/1/

Can comments be used in JSON?

There are other libraries that are JSON compatible, which support comments.

One notable example is the "Hashcorp Language" (HCL)". It is written by the same people who made Vagrant, packer, consul, and vault.

Twitter bootstrap progress bar animation on page load

While Tats_innit's answer has a nice touch to it, I had to do it a bit differently since I have more than one progress bar on the page.

here's my solution:

JSfiddle: http://jsfiddle.net/vacNJ/

HTML (example):

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="60"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="50"></div>
</div>

<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="40"></div>
</div>

?

JavaScript:

setTimeout(function(){

    $('.progress .bar').each(function() {
        var me = $(this);
        var perc = me.attr("data-percentage");

        var current_perc = 0;

        var progress = setInterval(function() {
            if (current_perc>=perc) {
                clearInterval(progress);
            } else {
                current_perc +=1;
                me.css('width', (current_perc)+'%');
            }

            me.text((current_perc)+'%');

        }, 50);

    });

},300);

@Tats_innit: Using setInterval() to dynamically recalc the progress is a nice solution, thx mate! ;)

EDIT:

A friend of mine wrote a nice jquery plugin for custom twitter bootstrap progress bars. Here's a demo: http://minddust.github.com/bootstrap-progressbar/

Here's the Github repo: https://github.com/minddust/bootstrap-progressbar

Where is debug.keystore in Android Studio

EDIT Step 1) Go to File > Project Structure > select project > go to "signing" and select your default or any keystore you want and fill all the details. In case you are not able to fill the details, hit the green '+' button. I've highlighted in the screenshot.enter image description here

Step 2) VERY IMPORTANT: Goto Build Types> select your build type and select your "Signing Config". In my case, I've to select "config". Check the highlighted region. enter image description here

How to display a gif fullscreen for a webpage background?

This should do what you're looking for.

CSS:

html, body {
    height: 100%;
    margin: 0;
}

.gif-container {
  background: url("image.gif") center;
  background-size: cover;

  height: 100%;
}

HTML:

<div class="gif-container"></div>

Attempted to read or write protected memory

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.

Conditional Formatting using Excel VBA code

This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5 in this case) will be? Then I can try to provide a more complete answer.

Sub setCondFormat()
    Range("B3").Select
    With Range("B3:H63")
        .FormatConditions.Add Type:=xlExpression, Formula1:= _
          "=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
        With .FormatConditions(.FormatConditions.Count)
            .SetFirstPriority
            With .Interior
                .PatternColorIndex = xlAutomatic
                .Color = 5287936
                .TintAndShade = 0
            End With
        End With
    End With
End Sub

Note: this is tested in Excel 2010.

Edit: Updated code based on comments.

Error C1083: Cannot open include file: 'stdafx.h'

You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.

Python find min max and average of a list (array)

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

Normalizing a list of numbers in Python

Use scikit-learn:

from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))

How can I have Github on my own server?

I tried gitosis that is fully command line. And I chose this one.

Being a Java guy, I also looked with interest to Gitblit.

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

First step, you have to set your autofocus attribute on form input.

<input name="full_name" autofocus/>

And then you have to add declaration to set autofocus of your input after your modal is shown.
Try this code :

$(document).on('ready', function(){
    // Set modal form input to autofocus when autofocus attribute is set
    $('.modal').on('shown.bs.modal', function () {
        $(this).find($.attr('autofocus')).focus();
    });
});

Are there bookmarks in Visual Studio Code?

If you are using vscodevim extension, then you can harness the power of vim keyboard moves. When you are on a line that you would like to bookmark, in normal mode, you can type:

m {a-z A-Z} for a possible 52 bookmarks within a file. Small letter alphabets are for bookmarks within a single file. Capital letters preserve their marks across files.

To navigate to a bookmark from within any file, you then need to hit ' {a-z A-Z}. I don't think these bookmarks stay across different VSCode sessions though.

More vim shortcuts here.

Installing PHP Zip Extension

For php 7.3 on ubuntu 16.04

sudo apt-get install php7.3-zip

How to get current value of RxJS Subject or Observable?

I had similar situation where late subscribers subscribe to the Subject after its value arrived.

I found ReplaySubject which is similar to BehaviorSubject works like a charm in this case. And here is a link to better explanation: http://reactivex.io/rxjs/manual/overview.html#replaysubject

Which version of Python do I have installed?

Mostly usage commands:

python -version

Or

python -V

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

Calculating Distance between two Latitude and Longitude GeoCoordinates

You can use System.device.Location:

System.device.Location.GeoCoordinate gc = new System.device.Location.GeoCoordinate(){
Latitude = yourLatitudePt1,
Longitude = yourLongitudePt1
};

System.device.Location.GeoCoordinate gc2 = new System.device.Location.GeoCoordinate(){
Latitude = yourLatitudePt2,
Longitude = yourLongitudePt2
};

Double distance = gc2.getDistanceTo(gc);

good luck

PHP array printing using a loop

Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.

Using two CSS classes on one element

If you only have two items, you can do this:

.social {
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
    border: none;
}

.social:first-child { 
    padding-top:0;
    border-bottom: dotted 1px #6d6d6d;
}

In Python, how to check if a string only contains certain characters?

A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:

input_string = 'abc test'
input_string_test = input_string
allowed_list = ['a', 'b', 'c', 'test', ' ']

for allowed_list_item in allowed_list:
    input_string_test = input_string_test.replace(allowed_list_item, '')

if not input_string_test:
    # test passed

So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string.

adding css class to multiple elements

.button input,
.button a {
    ...
}

Plotting two variables as lines using ggplot2 on the same graph

I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.

I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.

Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).

var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)    

Plotting

ggplot() + geom_line(aes(x=date,y=var0),color='red') + 
           geom_line(aes(x=date,y=var1),color='blue') + 
           ylab('Values')+xlab('date')

enter image description here

However I was not able to add a correct legend using this format. Does anyone know how?

How to Disable landscape mode in Android?

In the <apphome>/platform/android directory created AndroidManifest.xml (copying it from the generated one). Then add android:screenOrientation="portrait" to ALL of the activity elements.

Visual Studio Error: (407: Proxy Authentication Required)

I faced the same error with my Visual Studio Team Services account (formerly Visual Studio Online, Team Foundation Service).

I simply entered the credentials using the VS 2013 "Connect to Team Foundation Server" Window, and then connected it to the Visual Studio Team Services Team Project. It worked this way.

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
    {
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);
    }

Usage:

    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html

How do I update Homebrew?

  • cd /usr/local
  • git status
  • Discard all the changes (unless you actually want to try to commit to Homebrew - you probably don't)
  • git status til it's clean
  • brew update

sed command with -i option failing on Mac, but works on Linux

As the other answers indicate, there is not a way to use sed portably across OS X and Linux without making backup files. So, I instead used this Ruby one-liner to do so:

ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml

In my case, I needed to call it from a rake task (i.e., inside a Ruby script), so I used this additional level of quoting:

sh %q{ruby -pi -e "sub(/ $/, '')" ./config/locales/*.yml}

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Prevent line-break of span element

white-space: nowrap is the correct solution but it will prevent any break in a line. If you only want to prevent line breaks between two elements it gets a bit more complicated:

<p>
    <span class="text">Some text</span>
    <span class="icon"></span>
</p>

To prevent breaks between the spans but to allow breaks between "Some" and "text" can be done by:

p {
    white-space: nowrap;
}

.text {
    white-space: normal;
}

That's good enough for Firefox. In Chrome you additionally need to replace the whitespace between the spans with an &nbsp;. (Removing the whitespace doesn't work.)

What's the difference between using "let" and "var"?

May the following two functions show the difference:

function varTest() {
    var x = 31;
    if (true) {
        var x = 71;  // Same variable!
        console.log(x);  // 71
    }
    console.log(x);  // 71
}

function letTest() {
    let x = 31;
    if (true) {
        let x = 71;  // Different variable
        console.log(x);  // 71
    }
    console.log(x);  // 31
}

WPF - add static items to a combo box

<ComboBox Text="Something">
            <ComboBoxItem Content="Item1"></ComboBoxItem >
            <ComboBoxItem Content="Item2"></ComboBoxItem >
            <ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>

Can I use a min-height for table, tr or td?

if you set style="height:100px;" on a td if the td has content that grows the cell more than that, it will do so no need for min height on a td.

Capture screenshot of active window?

Use the following code :

            // Shot size = screen size
            Size shotSize = Screen.PrimaryScreen.Bounds.Size;

            // the upper left point in the screen to start shot
            // 0,0 to get the shot from upper left point
            Point upperScreenPoint = new Point(0, 0);

            // the upper left point in the image to put the shot
            Point upperDestinationPoint = new Point(0, 0);

            // create image to get the shot in it
            Bitmap shot = new Bitmap(shotSize.Width, shotSize.Height);

            // new Graphics instance 
            Graphics graphics = Graphics.FromImage(shot);

            // get the shot by Graphics class 
            graphics.CopyFromScreen(upperScreenPoint, upperDestinationPoint, shotSize);

            // return the image
            pictureBox1.Image = shot;

How to Join to first row

Tried the cross, works nicely, but takes slightly longer. Adjusted line columns to have max and added group which kept speed and dropped the extra record.

Here's the adjusted query:

SELECT Orders.OrderNumber, max(LineItems.Quantity), max(LineItems.Description)
FROM Orders
    INNER JOIN LineItems 
    ON Orders.OrderID = LineItems.OrderID
Group by Orders.OrderNumber

VHDL - How should I create a clock in a testbench?

If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:

library ieee;
use ieee.std_logic_1164.all;

entity tb is
end entity;

architecture sim of tb is

  -- Procedure for clock generation
  procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
    constant PERIOD    : time := 1 sec / FREQ;        -- Full period
    constant HIGH_TIME : time := PERIOD / 2;          -- High time
    constant LOW_TIME  : time := PERIOD - HIGH_TIME;  -- Low time; always >= HIGH_TIME
  begin
    -- Check the arguments
    assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
    -- Generate a clock cycle
    loop
      clk <= '1';
      wait for HIGH_TIME;
      clk <= '0';
      wait for LOW_TIME;
    end loop;
  end procedure;

  -- Clock frequency and signal
  signal clk_166 : std_logic;
  signal clk_125 : std_logic;

begin

  -- Clock generation with concurrent procedure call
  clk_gen(clk_166, 166.667E6);  -- 166.667 MHz clock
  clk_gen(clk_125, 125.000E6);  -- 125.000 MHz clock

  -- Time resolution show
  assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;

end architecture;

The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.

If the clk_gen procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.

Waveform for clocks are shown in figure below.

Waveforms for clk_166 and clk_125

An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:

-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
  constant HIGH_TIME   : time := 0.5 sec / FREQ;  -- High time as fixed value
  variable low_time_v  : time;                    -- Low time calculated per cycle; always >= HIGH_TIME
  variable cycles_v    : real := 0.0;             -- Number of cycles
  variable freq_time_v : time := 0 fs;            -- Time used for generation of cycles
begin
  -- Check the arguments
  assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
  -- Initial phase shift
  clk <= '0';
  wait for PHASE;
  -- Generate cycles
  loop
    -- Only high pulse if run is '1' or 'H'
    if (run = '1') or (run = 'H') then
      clk <= run;
    end if;
    wait for HIGH_TIME;
    -- Low part of cycle
    clk <= '0';
    low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME;  -- + 1.0 for cycle after current
    wait for low_time_v;
    -- Cycle counter and time passed update
    cycles_v := cycles_v + 1.0;
    freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
  end loop;
end procedure;

Again reuse through a package will be nice.

How to get current user who's accessing an ASP.NET application?

If you're using membership you can do: Membership.GetUser()

Your code is returning the Windows account which is assigned with ASP.NET.

Additional Info Edit: You will want to include System.Web.Security

using System.Web.Security

What's the difference between deadlock and livelock?

Imagine you've thread A and thread B. They are both synchronised on the same object and inside this block there's a global variable they are both updating;

static boolean commonVar = false;
Object lock = new Object;

...

void threadAMethod(){
    ...
    while(commonVar == false){
         synchornized(lock){
              ...
              commonVar = true
         }
    }
}

void threadBMethod(){
    ...
    while(commonVar == true){
         synchornized(lock){
              ...
              commonVar = false
         }
    }
}

So, when thread A enters in the while loop and holds the lock, it does what it has to do and set the commonVar to true. Then thread B comes in, enters in the while loop and since commonVar is true now, it is be able to hold the lock. It does so, executes the synchronised block, and sets commonVar back to false. Now, thread A again gets it's new CPU window, it was about to quit the while loop but thread B has just set it back to false, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.

It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.

Difference between Iterator and Listiterator?

the following is that the difference between iterator and listIterator

iterator :

boolean hasNext();
E next();
void remove();

listIterator:

boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);

Python, creating objects

when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.

class Student:
     def __init__(self):

# creating an object....

   student1=Student()

Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..

class Student:
      def __init__(self,name,age):
            self.name=value
            self.age=value

 # creating an object.......

     student2=Student("smith",25)