Programs & Examples On #Freebsd

FreeBSD is an advanced Unix-like operating system for modern server, desktop, and embedded computer platforms. It is open source and licensed under the 2-clause BSD license.

Check if string is neither empty nor space in shell script

[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty"

Stripping all newlines and spaces from the string will cause a blank one to be reduced to nothing which can be tested and acted upon

Determine the process pid listening on a certain port

Short version which you can pass to kill command:

lsof -i:80 -t

How can I get the behavior of GNU's readlink -f on a Mac?

Better late than never, I suppose. I was motivated to develop this specifically because my Fedora scripts weren't working on the Mac. The problem is dependencies and Bash. Macs don't have them, or if they do, they are often somewhere else (another path). Dependency path manipulation in a cross-platform Bash script is a headache at best and a security risk at worst - so it's best to avoid their use, if possible.

The function get_realpath() below is simple, Bash-centric, and no dependencies are required. I uses only the Bash builtins echo and cd. It is also fairly secure, as everything gets tested at each stage of the way and it returns error conditions.

If you don't want to follow symlinks, then put set -P at the front of the script, but otherwise cd should resolve the symlinks by default. It's been tested with file arguments that are {absolute | relative | symlink | local} and it returns the absolute path to the file. So far we've not had any problems with it.

function get_realpath() {

if [[ -f "$1" ]]
then
    # file *must* exist
    if cd "$(echo "${1%/*}")" &>/dev/null
    then
        # file *may* not be local
        # exception is ./file.ext
        # try 'cd .; cd -;' *works!*
        local tmppwd="$PWD"
        cd - &>/dev/null
    else
        # file *must* be local
        local tmppwd="$PWD"
    fi
else
    # file *cannot* exist
    return 1 # failure
fi

# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success

}

You can combine this with other functions get_dirname, get_filename, get_stemname and validate_path. These can be found at our GitHub repository as realpath-lib (full disclosure - this is our product but we offer it free to the community without any restrictions). It also could serve as a instructional tool - it's well documented.

We've tried our best to apply so-called 'modern Bash' practices, but Bash is a big subject and I'm certain there will always be room for improvement. It requires Bash 4+ but could be made to work with older versions if they are still around.

How to install packages offline?

If you want install python libs and their dependencies offline, finish following these steps on a machine with the same os, network connected, and python installed:

1) Create a requirements.txt file with similar content (Note - these are the libraries you wish to download):

Flask==0.12
requests>=2.7.0
scikit-learn==0.19.1
numpy==1.14.3
pandas==0.22.0

One option for creating the requirements file is to use pip freeze > requirements.txt. This will list all libraries in your environment. Then you can go in to requirements.txt and remove un-needed ones.

2) Execute command mkdir wheelhouse && pip download -r requirements.txt -d wheelhouse to download libs and their dependencies to directory wheelhouse

3) Copy requirements.txt into wheelhouse directory

4) Archive wheelhouse into wheelhouse.tar.gz with tar -zcf wheelhouse.tar.gz wheelhouse

Then upload wheelhouse.tar.gz to your target machine:

1) Execute tar -zxf wheelhouse.tar.gz to extract the files

2) Execute pip install -r wheelhouse/requirements.txt --no-index --find-links wheelhouse to install the libs and their dependencies

Compare two different files line by line in python

Yet another example...

from __future__ import print_function #Only for Python2

with open('file1.txt') as f1, open('file2.txt') as f2, open('outfile.txt', 'w') as outfile:
    for line1, line2 in zip(f1, f2):
        if line1 == line2:
            print(line1, end='', file=outfile)

And if you want to eliminate common blank lines, just change the if statement to:

if line1.strip() and line1 == line2:

.strip() removes all leading and trailing whitespace, so if that's all that's on a line, it will become an empty string "", which is considered false.

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

Using :focus to style outer div?

DIV elements can get focus if set the tabindex attribute. Here is the working example.

_x000D_
_x000D_
#focus-example > .extra {_x000D_
  display: none;_x000D_
}_x000D_
#focus-example:focus > .extra {_x000D_
  display: block;_x000D_
}
_x000D_
<div id="focus-example" tabindex="0">_x000D_
  <div>Focus me!</div>_x000D_
  <div class="extra">Hooray!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

For more information about focus and blur, you can check out this article.

Update: And here is another example using focus to create a menu.

_x000D_
_x000D_
#toggleMenu:focus {_x000D_
  outline: none;_x000D_
}_x000D_
button:focus + .menu {_x000D_
  display: block;_x000D_
}_x000D_
.menu {_x000D_
  display: none;_x000D_
}_x000D_
.menu:focus {_x000D_
  display: none;_x000D_
}
_x000D_
<div id="toggleMenu" tabindex="0">_x000D_
  <button type="button">Menu</button>_x000D_
  <ul class="menu" tabindex="1">_x000D_
    <li>Home</li>_x000D_
    <li>About Me</li>_x000D_
    <li>Contacts</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Overriding a JavaScript function while referencing the original

So my answer ended up being a solution that allows me to use the _this variable pointing to the original object. I create a new instance of a "Square" however I hated the way the "Square" generated it's size. I thought it should follow my specific needs. However in order to do so I needed the square to have an updated "GetSize" function with the internals of that function calling other functions already existing in the square such as this.height, this.GetVolume(). But in order to do so I needed to do this without any crazy hacks. So here is my solution.

Some other Object initializer or helper function.

this.viewer = new Autodesk.Viewing.Private.GuiViewer3D(
  this.viewerContainer)
var viewer = this.viewer;
viewer.updateToolbarButtons =  this.updateToolbarButtons(viewer);

Function in the other object.

updateToolbarButtons = function(viewer) {
  var _viewer = viewer;
  return function(width, height){ 
blah blah black sheep I can refer to this.anything();
}
};

Trying to get property of non-object MySQLi result

The cause of your problem is simple. So many people will run into the same problem, Because I did too and it took me hour to figure out. Just in case, someone else stumbles, The problem is in your query, your select statement is calling $dbname instead of table name. So its not found whereby returning false which is boolean. Good luck.

What are functional interfaces used for in Java 8?

You can use lambda in Java 8

public static void main(String[] args) {
    tentimes(inputPrm - > System.out.println(inputPrm));
    //tentimes(System.out::println);  // You can also replace lambda with static method reference
}

public static void tentimes(Consumer myFunction) {
    for (int i = 0; i < 10; i++)
        myFunction.accept("hello");
}

For further info about Java Lambdas and FunctionalInterfaces

What's the difference between KeyDown and KeyPress in .NET?

Keydown is pressing the key without releasing it, Keypress is a complete press-and-release cycle.

Put another way, KeyDown + KeyUp = Keypress

Accessing certain pixel RGB value in openCV

A piece of code is easier for people who have such problem. I share my code and you can use it directly. Please note that OpenCV store pixels as BGR.

cv::Mat vImage_; 

if(src_)
{
    cv::Vec3f vec_;

    for(int i = 0; i < vHeight_; i++)
        for(int j = 0; j < vWidth_; j++)
        {
            vec_ = cv::Vec3f((*src_)[0]/255.0, (*src_)[1]/255.0, (*src_)[2]/255.0);//Please note that OpenCV store pixels as BGR.

            vImage_.at<cv::Vec3f>(vHeight_-1-i, j) = vec_;

            ++src_;
        }
}

if(! vImage_.data ) // Check for invalid input
    printf("failed to read image by OpenCV.");
else
{
    cv::namedWindow( windowName_, CV_WINDOW_AUTOSIZE);
    cv::imshow( windowName_, vImage_); // Show the image.
}

get string value from HashMap depending on key name

This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:

        Map<Integer, String> testKeyset = new HashMap<Integer, String>();

        testKeyset.put(1, "first");
        testKeyset.put(2, "second");
        testKeyset.put(3, "third");
        testKeyset.put(4, "fourth");

        // Print a single value relevant to a specified Key. (uses keySet())
        for(int mapKey: testKeyset.keySet())
            System.out.println(testKeyset.get(mapKey));

        // Print all values regardless of the key.
        for(String mapVal: testKeyset.values())
            System.out.println(mapVal.trim());

        // Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
        System.out.println(testKeyset.entrySet());

How to detect the swipe left or Right in Android?

This is a cute class I use (in cases I want to catch event on a View, if it is a ViewGroup, I use the second implementation):

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class SwipeDetector implements View.OnTouchListener{

    private int min_distance = 100;
    private float downX, downY, upX, upY;
    private View v;

    private onSwipeEvent swipeEventListener;



    public SwipeDetector(View v){
        this.v=v;
        v.setOnTouchListener(this);
    }

    public void setOnSwipeListener(onSwipeEvent listener)
    {
        try{
            swipeEventListener=listener;
        }
        catch(ClassCastException e)
        {
            Log.e("ClassCastException","please pass SwipeDetector.onSwipeEvent Interface instance",e);
        }
    }


    public void onRightToLeftSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.RIGHT_TO_LEFT);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public void onLeftToRightSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.LEFT_TO_RIGHT);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public void onTopToBottomSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.TOP_TO_BOTTOM);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public void onBottomToTopSwipe(){
        if(swipeEventListener!=null)
            swipeEventListener.SwipeEventDetected(v,SwipeTypeEnum.BOTTOM_TO_TOP);
        else
            Log.e("SwipeDetector error","please pass SwipeDetector.onSwipeEvent Interface instance");
    }

    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN: {
            downX = event.getX();
            downY = event.getY();
            return true;
        }
        case MotionEvent.ACTION_UP: {
            upX = event.getX();
            upY = event.getY();

            float deltaX = downX - upX;
            float deltaY = downY - upY;

            //HORIZONTAL SCROLL
            if(Math.abs(deltaX) > Math.abs(deltaY))
            {
                if(Math.abs(deltaX) > min_distance){
                    // left or right
                    if(deltaX < 0) 
                    {
                        this.onLeftToRightSwipe();
                        return true;
                    }
                    if(deltaX > 0) {
                        this.onRightToLeftSwipe();
                        return true; 
                    }
                }
                else {
                    //not long enough swipe...
                    return false; 
                }
            }
            //VERTICAL SCROLL
            else 
            {
                if(Math.abs(deltaY) > min_distance){
                    // top or down
                    if(deltaY < 0) 
                    { this.onTopToBottomSwipe();
                    return true; 
                    }
                    if(deltaY > 0)
                    { this.onBottomToTopSwipe(); 
                    return true;
                    }
                }
                else {
                    //not long enough swipe...
                    return false;
                }
            }

            return true;
        }
        }
        return false;
    }
    public interface onSwipeEvent
    {
        public void SwipeEventDetected(View v, SwipeTypeEnum SwipeType);
    }

    public SwipeDetector setMinDistanceInPixels(int min_distance)
{
    this.min_distance=min_distance;
    return this;
}

    public enum SwipeTypeEnum
    {
        RIGHT_TO_LEFT,LEFT_TO_RIGHT,TOP_TO_BOTTOM,BOTTOM_TO_TOP
    }

}

and this is a use example:

filters_container=(RelativeLayout)root.findViewById(R.id.filters_container);
    new SwipeDetector(filters_container).setOnSwipeListener(new SwipeDetector.onSwipeEvent() {
        @Override
        public void SwipeEventDetected(View v, SwipeDetector.SwipeTypeEnum swipeType) {
            if(swipeType==SwipeDetector.SwipeTypeEnum.LEFT_TO_RIGHT)
                getActivity().onBackPressed();
        }
    });

In some cases you would like to detect the swipe gestures on a container and pass down the touch Events to the childs so in that case you can create a Custom View group, lets say RelativeLayout and override onInterceptTouchEvent , and there you can detect the swipe event without blocking the pass of Touch Event to your child views,for Example:

    import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;


public class SwipeDetectRelativeLayout extends RelativeLayout {


    private float x1,x2;
    static final int MIN_DISTANCE=150;
    private onSwipeEventDetected mSwipeDetectedListener;


    public SwipeDetectRelativeLayout(Context context) {
        super(context);
    }

    public SwipeDetectRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwipeDetectRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        switch(ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                x2 = ev.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE)
                {
                        //swiping right to left
                        if(deltaX<0)
                        {
                            if(mSwipeDetectedListener!=null)
                                mSwipeDetectedListener.swipeEventDetected();
                        }
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    public interface onSwipeEventDetected
    {
        public void swipeEventDetected();
    }

    public void registerToSwipeEvents(onSwipeEventDetected listener)
    {
        this.mSwipeDetectedListener=listener;
    }
}

How do I get class name in PHP?

This will return pure class name even when using namespace:

echo substr(strrchr(__CLASS__, "\\"), 1);    

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Make a dictionary in Python from input values

record = int(input("Enter the student record need to add :"))

stud_data={}

for i in range(0,record):
    Name = input("Enter the student name :").split()
    Age = input("Enter the {} age :".format(Name))
    Grade = input("Enter the {} grade :".format(Name)).split()
    Nam_key =  Name[0]
    Age_value = Age[0]
    Grade_value = Grade[0]
    stud_data[Nam_key] = {Age_value,Grade_value}

print(stud_data)

Can you display HTML5 <video> as a full screen background?

I might be a bit late to answer this but this will be useful for new people looking for this answer.

The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.

I got into this issue not long ago and I found the solution using media queries.

Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS

I will add the code here as well:

HTML:

<div class="videoBgWrapper">
    <video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
        <source src="videosfolder/video.webm" type="video/webm">
        <source src="videosfolder/video.mp4" type="video/mp4">
        <source src="videosfolder/video.ogv" type="video/ogg">
    </video>
</div>

CSS:

.videoBgWrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.videoBg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .videoBg{
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  .videoBg {
    width: auto;
    height: 100%;
  }
}

I hope you find it useful.

Is there a way to automatically generate getters and setters in Eclipse?

Eclipse > Source > Generate Getters and Setters

Shift elements in a numpy array

For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs.

Benchmark

import numpy as np
import timeit

# enhanced from IronManMark20 version
def shift1(arr, num, fill_value=np.nan):
    arr = np.roll(arr,num)
    if num < 0:
        arr[num:] = fill_value
    elif num > 0:
        arr[:num] = fill_value
    return arr

# use np.roll and np.put by IronManMark20
def shift2(arr,num):
    arr=np.roll(arr,num)
    if num<0:
         np.put(arr,range(len(arr)+num,len(arr)),np.nan)
    elif num > 0:
         np.put(arr,range(num),np.nan)
    return arr

# use np.pad and slice by me.
def shift3(arr, num, fill_value=np.nan):
    l = len(arr)
    if num < 0:
        arr = np.pad(arr, (0, abs(num)), mode='constant', constant_values=(fill_value,))[:-num]
    elif num > 0:
        arr = np.pad(arr, (num, 0), mode='constant', constant_values=(fill_value,))[:-num]

    return arr

# use np.concatenate and np.full by chrisaycock
def shift4(arr, num, fill_value=np.nan):
    if num >= 0:
        return np.concatenate((np.full(num, fill_value), arr[:-num]))
    else:
        return np.concatenate((arr[-num:], np.full(-num, fill_value)))

# preallocate empty array and assign slice by chrisaycock
def shift5(arr, num, fill_value=np.nan):
    result = np.empty_like(arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else:
        result[:] = arr
    return result

arr = np.arange(2000).astype(float)

def benchmark_shift1():
    shift1(arr, 3)

def benchmark_shift2():
    shift2(arr, 3)

def benchmark_shift3():
    shift3(arr, 3)

def benchmark_shift4():
    shift4(arr, 3)

def benchmark_shift5():
    shift5(arr, 3)

benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5']

for x in benchmark_set:
    number = 10000
    t = timeit.timeit('%s()' % x, 'from __main__ import %s' % x, number=number)
    print '%s time: %f' % (x, t)

benchmark result:

benchmark_shift1 time: 0.265238
benchmark_shift2 time: 0.285175
benchmark_shift3 time: 0.473890
benchmark_shift4 time: 0.099049
benchmark_shift5 time: 0.052836

Conclusion

shift5 is winner! It's OP's third solution.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).

.carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
          transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
  z-index: 2;
}

Add a UIView above all, even the navigation bar

[[UIApplication sharedApplication].windows.lastObject addSubview:myView];

Mongoose query where value is not null

I ended up here and my issue was that I was querying for

{$not: {email: /@domain.com/}}

instead of

{email: {$not: /@domain.com/}}

Static variables in C++

Static variable in a header file:

say 'common.h' has

static int zzz;

This variable 'zzz' has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h' has it's own unique object of name 'zzz'.

Static variable in a class:

Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.

$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."

So let's say 'myclass.h' has

struct myclass{
   static int zzz;        // this is only a declaration
};

and myclass.cpp has

#include "myclass.h"

int myclass::zzz = 0           // this is a definition, 
                               // should be done once and only once

and "hisclass.cpp" has

#include "myclass.h"

void f(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

and "ourclass.cpp" has

#include "myclass.h"
void g(){myclass::zzz = 2;}    // myclass::zzz is always the same in any 
                               // translation unit

So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.

Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate

Oracle: How to filter by date and time in a where clause

Obviously '12/01/2012 13:16:32.000' doesn't match 'DD-MON-YYYY hh24:mi' format.

Update:

You need 'MM/DD/YYYY hh24:mi:ss.ff' format and to use TO_TIMESTAMP instead of TO_DATE cause dates don't hold millis in oracle.

Run-time error '1004' - Method 'Range' of object'_Global' failed

When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.

If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.

inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.

The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like

With ThisWorkbook.Worksheets("Template")
    .Range(inputTemplateHeader).Value = NO_ENTRY
    .Range(inputTemplateContent).Value = NO_ENTRY
End With

Adjust the workbook and worksheet references to fit your particular situation.

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

Verilog generate/genvar in an always block

You don't need a generate bock if you want all the bits of temp assigned in the same always block.

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
    for (integer c=0; c<ROWBITS; c=c+1) begin: test
        temp[c] <= 1'b0;
    end
end

Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
        temp <= '0; // fill with 0
    end
end

Open a facebook link by native Facebook app on iOS

I did this in MonoTouch in the following method, I'm sure a pure Obj-C based approach wouldn't be too different. I used this inside a class which had changing URLs at times which is why I just didn't put it in a if/elseif statement.

NSString *myUrls = @"fb://profile/100000369031300|http://www.facebook.com/ytn3rd";
NSArray *urls = [myUrls componentsSeparatedByString:@"|"];
for (NSString *url in urls){
    NSURL *nsurl = [NSURL URLWithString:url];
    if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
        [[UIApplication sharedApplication] openURL:nsurl];
        break;
    }
}

The break is not always called before your app changes to Safari/Facebook. I assume your program will halt there and call it when you come back to it.

How do you set, clear, and toggle a single bit?

The bitfield approach has other advantages in the embedded arena. You can define a struct that maps directly onto the bits in a particular hardware register.

struct HwRegister {
    unsigned int errorFlag:1;  // one-bit flag field
    unsigned int Mode:3;       // three-bit mode field
    unsigned int StatusCode:4;  // four-bit status code
};

struct HwRegister CR3342_AReg;

You need to be aware of the bit packing order - I think it's MSB first, but this may be implementation-dependent. Also, verify how your compiler handlers fields crossing byte boundaries.

You can then read, write, test the individual values as before.

How to access ssis package variables inside script component

Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: screenshot of Script Transformation Editor properties page Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:

// Modify as necessary
public override void PreExecute()
{
    base.PreExecute();
    string thePath = Variables.FilePath;
    // Do something ...
}

public override void PostExecute()
{
    base.PostExecute();
    string theNewValue = "";
    // Do something to figure out the new value...
    Variables.FilePath = theNewValue;
}

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    string thePath = Variables.FilePath;
    // Do whatever needs doing here ...
}

One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.

Regarding the code snippet:

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

varCollection is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.

Error in file(file, "rt") : cannot open the connection

If running on Windows try running R or R Studio as administrator to avoid Windows OS file system constraints.

Fixed header, footer with scrollable content

Approach 1 - flexbox

It works great for both known and unknown height elements. Make sure to set the outer div to height: 100%; and reset the default margin on body. See the browser support tables.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  flex: 1;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 2 - CSS table

For both known and unknown height elements. It also works in legacy browsers including IE8.

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: table;_x000D_
}_x000D_
.header, .content, .footer {_x000D_
  display: table-row;_x000D_
}_x000D_
.header, .footer {_x000D_
  background: silver;_x000D_
}_x000D_
.inner {_x000D_
  display: table-cell;_x000D_
}_x000D_
.content .inner {_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  background: pink;_x000D_
}_x000D_
.scrollable {_x000D_
  position: absolute;_x000D_
  left: 0; right: 0;_x000D_
  top: 0; bottom: 0;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">_x000D_
    <div class="inner">Header</div>_x000D_
  </div>_x000D_
  <div class="content">_x000D_
    <div class="inner">_x000D_
      <div class="scrollable">_x000D_
        <div style="height:1000px;">Content</div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="footer">_x000D_
    <div class="inner">Footer</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 3 - calc()

If header and footer are fixed height, you can use CSS calc().

jsFiddle

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 50px;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: calc(100% - 100px);_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Approach 4 - % for all

If the header and footer are known height, and they are also percentage you can just do the simple math making them together of 100% height.

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  height: 100%;_x000D_
}_x000D_
.header, .footer {_x000D_
  height: 10%;_x000D_
  background: silver;_x000D_
}_x000D_
.content {_x000D_
  height: 80%;_x000D_
  overflow: auto;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="header">Header</div>_x000D_
  <div class="content">_x000D_
    <div style="height:1000px;">Content</div>_x000D_
  </div>_x000D_
  <div class="footer">Footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

npm ERR! Error: EPERM: operation not permitted, rename

In my situation this helped:

Before proceeding to execute these commands close all VS Code instances.

  1. clean cache with

     npm cache clean --force
    
  2. install the latest version of npm globally as admin:

     npm install -g npm@latest --force
    
  3. clean cache with

     npm cache clean --force
    
  4. Try to install your component once again.

I hope this works for others, if not you may also try temporarily disabling antivirus software before trying again.

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

How to upload & Save Files with Desired name

Configure The "php.ini" File

First, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the file_uploads directive, and set it to On:

file_uploads = On 

Create The HTML Form

Next, create an HTML form that allow users to choose the image file they want to upload:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Some rules to follow for the HTML form above: Make sure that the form uses method="post" The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work. Other things to notice: The type="file" attribute of the tag shows the input field as a file-select control, with a "Browse" button next to the input control The form above sends data to a file called "upload.php", which we will create next.

Create The Upload File PHP Script

The "upload.php" file contains the code for uploading a file:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

Driver executable must be set by the webdriver.ie.driver system property

You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe

Then you have write below code in your eclipse main class

   System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
   WebDriver driver = new InternetExplorerDriver();

Slicing a dictionary

set intersection and dict comprehension can be used here

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}

How to pad zeroes to a string?

Another approach would be to use a list comprehension with a condition checking for lengths. Below is a demonstration:

# input list of strings that we want to prepend zeros
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]

# prepend zeros to make each string to length 8, if length of string is less than 8
In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
Out[83]: ['00101010', '10101010', '00011110', '00000000']

Installing Homebrew on OS X

I faced the same problem of brew command not found while installing Homebrew on mac BigSur with M1 processor.

I - Install XCode if it is not installed yet.

II - Select terminal.app in Finder.

III - RMB click on Terminal and select "Get Info"

IV - Select Open using Rosetta checkbox.

V - Close any open Terminal windows.

VI - Open a new Terminal window and install Hobebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

VII - Test Homebrew installation.

IIX - Uncheck Open using Rosetta checkbox.

Rethrowing exceptions in Java without losing the stack trace

catch (WhateverException e) {
    throw e;
}

will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

How do I reference a cell range from one worksheet to another using excel formulas?

The formula that you have is fine. But, after entering it, you need to hit Control + Shift + Enter in order to apply it to the range of values. Specifically:

  1. Select the range of values in the destination sheet.

  2. Enter into the formula panel your desired formula, e.g. =Sheet2!A1:F1

  3. Hit Control + Shift + Enter to apply the formula to the range.

What is the best way to trigger onchange event in react js

Triggering change events on arbitrary elements creates dependencies between components which are hard to reason about. It's better to stick with React's one-way data flow.

There is no simple snippet to trigger React's change event. The logic is implemented in ChangeEventPlugin.js and there are different code branches for different input types and browsers. Moreover, the implementation details vary across versions of React.

I have built react-trigger-change that does the thing, but it is intended to be used for testing, not as a production dependency:

let node;
ReactDOM.render(
  <input
    onChange={() => console.log('changed')}
    ref={(input) => { node = input; }}
  />,
  mountNode
);

reactTriggerChange(node); // 'changed' is logged

CodePen

Scala vs. Groovy vs. Clojure

Scala

Scala evolved out of a pure functional language known as Funnel and represents a clean-room implementation of almost all Java's syntax, differing only where a clear improvement could be made or where it would compromise the functional nature of the language. Such differences include singleton objects instead of static methods, and type inference.

Much of this was based on Martin Odersky's prior work with the Pizza language. The OO/FP integration goes far beyond mere closures and has led to the language being described as post-functional.

Despite this, it's the closest to Java in many ways. Mainly due to a combination of OO support and static typing, but also due to a explicit goal in the language design that it should integrate very tightly with Java.

Groovy

Groovy explicitly tackles two of Java's biggest criticisms by

  • being dynamically typed, which removes a lot of boilerplate and
  • adding closures to the language.

It's perhaps syntactically closest to Java, not offering some of the richer functional constructs that Clojure and Scala provide, but still offering a definite evolutionary improvement - especially for writing script-syle programs.

Groovy has the strongest commercial backing of the three languages, mostly via springsource.

Clojure

Clojure is a functional language in the LISP family, it's also dynamically typed.

Features such as STM support give it some of the best out-of-the-box concurrency support, whereas Scala requires a 3rd-party library such as Akka to duplicate this.

Syntactically, it's also the furthest of the three languages from typical Java code.

I also have to disclose that I'm most acquainted with Scala :)

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

Create a Date with a set timezone without using a string representation

I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.

And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.

Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.

Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.

On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

How to change Label Value using javascript

Based off your code, i created this Fiddle
You need to use

var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];


if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.

Attributes / member variables in interfaces?

You can only do this with an abstract class, not with an interface.

Declare Rectangle as an abstract class instead of an interface and declare the methods that must be implemented by the sub-class as public abstract. Then class Tile extends class Rectangle and must implement the abstract methods from Rectangle.

JQuery Validate input file type

Simply use the .rules('add') method immediately after creating the element...

var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");

    // declare the rule on this newly created input field        
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});
  • You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

  • You'll still need to declare rules for your static elements using .validate(). Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

  • You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

  • You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add'). For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".

Working DEMO: http://jsfiddle.net/8dAU8/5/

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

First time scroll when entering in recycler view first time then use

linearLayoutManager.scrollToPositionWithOffset(messageHashMap.size()-1

put in minus for scroll down for scroll up put in positive value);

if the view is very big in height then scrolltoposition particular offset is used for the top of view then you use

int overallXScroldl =chatMessageBinding.rvChat.computeVerticalScrollOffset();
chatMessageBinding.rvChat.smoothScrollBy(0, Math.abs(overallXScroldl));

Django - Static file not found

  1. You can remove the STATIC_ROOT line
  2. Or you can create another static folder in different directory. For suppose the directory is: project\static Now update:
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'project/static/')
    ]
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Whatever you do the main point is STATICFILES_DIRS and STATIC_ROOT should not contain same directory.

I know it's been a long time but hope the new buddies can get help from it

asp.net: Invalid postback or callback argument

This error can also be caused by nested <form> tag in the master page which is not allowed.

<form id="someid"></form>

This will likely be the cause if you have picked up a template and copying the code from somewhere as it.

Solution

You have to break the nesting of <form> tag. The following should become

<form method="" name="form1">
  <form method="" name="form2>
  </form>
</form>

should become

<form method="" name="form1">    
</form>

<form method="" name="form2>    
</form>

Get yesterday's date in bash on Linux, DST-safe

I think this should work, irrespective of how often and when you run it ...

date -d "yesterday 13:00" '+%Y-%m-%d'

What's the use of ob_start() in php?

this is to further clarify JD Isaaks answer ...

The problem you run into often is that you are using php to output html from many different php sources, and those sources are often, for whatever reason, outputting via different ways.

Sometimes you have literal html content that you want to directly output to the browser; other times the output is being dynamically created (server-side).

The dynamic content is always(?) going to be a string. Now you have to combine this stringified dynamic html with any literal, direct-to-display html ... into one meaningful html node structure.

This usually forces the developer to wrap all that direct-to-display content into a string (as JD Isaak was discussing) so that it can be properly delivered/inserted in conjunction with the dynamic html ... even though you don't really want it wrapped.

But by using ob_## methods you can avoid that string-wrapping mess. The literal content is, instead, output to the buffer. Then in one easy step the entire contents of the buffer (all your literal html), is concatenated into your dynamic-html string.

(My example shows literal html being output to the buffer, which is then added to a html-string ... look also at JD Isaaks example to see string-wrapping-of-html).

<?php // parent.php

//---------------------------------
$lvs_html  = "" ;

$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__without_ob( ) ;
$lvs_html .= "<div>more html</div>" ;

$lvs_html .= "----<br/>" ;

$lvs_html .= "<div>html</div>" ;
$lvs_html .= gf_component_assembler__with_ob( ) ;
$lvs_html .= "<div>more html</div>" ;

echo $lvs_html ;    
//    02 - component contents
//    html
//    01 - component header
//    03 - component footer
//    more html
//    ----
//    html
//    01 - component header
//    02 - component contents
//    03 - component footer
//    more html 

//---------------------------------
function gf_component_assembler__without_ob( ) 
  { 
    $lvs_html  = "<div>01 - component header</div>" ; // <table ><tr>" ;
    include( "component_contents.php" ) ;
    $lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;

    return $lvs_html ;
  } ;

//---------------------------------
function gf_component_assembler__with_ob( ) 
  { 
    $lvs_html  = "<div>01 - component header</div>" ; // <table ><tr>" ;

        ob_start();
        include( "component_contents.php" ) ;
    $lvs_html .= ob_get_clean();

    $lvs_html .= "<div>03 - component footer</div>" ; // </tr></table>" ;

    return $lvs_html ;
  } ;

//---------------------------------
?>

<!-- component_contents.php -->
  <div>
    02 - component contents
  </div>

Best way to verify string is empty or null

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

C# DateTime to UTC Time without changing the time

Use the DateTime.ToUniversalTime method.

momentJS date string add 5 days

The function add() returns the old date, but changes the original date :)

startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);

'too many values to unpack', iterating over a dict. key=>string, value=>list

In Python3 iteritems() is no longer supported

Use .items

for field, possible_values in fields.items():
    print(field, possible_values)

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

If the message is:

The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[15.0.4,15.0.4]], but resolves to 15.0.2. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

Change the version of all the play services libraries you are using to the one you need (15.0.2 in this case) could solve the problem.

In my case, I've changed:

implementation 'com.google.android.gms:play-services-base:+' -> implementation 'com.google.android.gms:play-services-base:15.0.2'
implementation 'com.google.android.gms:play-services-location:+' -> implementation 'com.google.android.gms:play-services-location:15.0.2'
implementation 'com.google.android.gms:play-services-maps:+' -> implementation 'com.google.android.gms:play-services-maps:15.0.2'
implementation 'com.google.android.gms:play-services-auth:+' -> implementation 'com.google.android.gms:play-services-auth:15.0.2'
implementation 'com.google.android.gms:play-services-places:+' -> implementation 'com.google.android.gms:play-services-places:15.0.2'

How do I use spaces in the Command Prompt?

If double quotes do not solve the issue then try e.g.

dir /X ~1 c:\

to get a list of alternative file or directory names. Example output:

11/09/2014 12:54 AM             8,065  DEFAUL~1.XML Default Desktop Policy.xml
06/12/2014  03:49 PM    <DIR>          PROGRA~1     Program Files 
10/12/2014  12:46 AM    <DIR>          PROGRA~2     Program Files (x86)

Now use the short 8 character file or folder name in the 5th column, e.g. PROGRA~1 or DEFAUL~1.XML, in your commands. For instance:

set JAVA_HOME=c:\PROGRA~1\Java\jdk1.6.0_45 

How do the post increment (i++) and pre increment (++i) operators work in Java?

In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it

++a

  1. a = a + 1;
  2. return a;

a++

  1. temp = a;
  2. a = a + 1;
  3. return temp;

How to publish a website made by Node.js to Github Pages?

No, You cannot publish on Github pages. Try Heroku or something like that. You can only deploy static sites on github pages. You can't deploy a server on github pages.

String array initialization in Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

What are Maven goals and phases and what is their difference?

Maven working terminology having phases and goals.

Phase:Maven phase is a set of action which is associated with 2 or 3 goals

exmaple:- if you run mvn clean

this is the phase will execute the goal mvn clean:clean

Goal:Maven goal bounded with the phase

for reference http://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html

Ruby: character to ascii from a string

"a"[0]

or

?a

Both would return their ASCII equivalent.

Difference between $(this) and event.target?

There is a difference between $(this) and event.target, and quite a significant one. While this (or event.currentTarget, see below) always refers to the DOM element the listener was attached to, event.target is the actual DOM element that was clicked. Remember that due to event bubbling, if you have

<div class="outer">
  <div class="inner"></div>
</div>

and attach click listener to the outer div

$('.outer').click( handler );

then the handler will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).

In this example, when you click inside the inner div, then in the handler:

  • this refers to the .outer DOM element (because that's the object to which the handler was attached)
  • event.currentTarget also refers to the .outer element (because that's the current target element handling the event)
  • event.target refers to the .inner element (this gives you the element where the event originated)

The jQuery wrapper $(this) only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target).

Also note that if you rebind the context of this (e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget.

sendUserActionEvent() is null

I also encuntered the same in S4. I've tested the app in Galaxy Grand , HTC , Sony Experia but got only in s4. You can ignore it as its not related to your app.

Forcing Internet Explorer 9 to use standards document mode

I have faced issue like my main page index.jsp contains the below line but eventhough rendering was not proper in IE. Found the issue and I have added the code in all the files which I included in index.jsp. Hurray! it worked.

So You need to add below code in all the files which you include into the page otherwise it wont work.

    <!doctype html>
    <head>
      <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    </head>

Drawing circles with System.Drawing

if you want to draw circle on button then this code might be use full. else if you want to draw a circle on other control just change the name of control and also event. like here event button is called. if you want to draw this circle in group box call the Groupbox event. regards

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.button1.Location = new Point(108, 12);
       // this.Paint += new PaintEventHandler(Form1_Paint);
        this.button1.Paint += new PaintEventHandler(button1_Paint);
    }
    void button1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = this.button1.CreateGraphics();
        Pen pen = new Pen(Color.Red);
        g.DrawEllipse(pen, 10, 10, 20, 20);

    }





}

XmlSerializer: remove unnecessary xsi and xsd namespaces

There is an alternative - you can provide a member of type XmlSerializerNamespaces in the type to be serialized. Decorate it with the XmlNamespaceDeclarations attribute. Add the namespace prefixes and URIs to that member. Then, any serialization that does not explicitly provide an XmlSerializerNamespaces will use the namespace prefix+URI pairs you have put into your type.

Example code, suppose this is your type:

[XmlRoot(Namespace = "urn:mycompany.2009")]
public class Person {
  [XmlAttribute] 
  public bool Known;
  [XmlElement]
  public string Name;
  [XmlNamespaceDeclarations]
  public XmlSerializerNamespaces xmlns;
}

You can do this:

var p = new Person
  { 
      Name = "Charley",
      Known = false, 
      xmlns = new XmlSerializerNamespaces()
  }
p.xmlns.Add("",""); // default namespace is emoty
p.xmlns.Add("c", "urn:mycompany.2009");

And that will mean that any serialization of that instance that does not specify its own set of prefix+URI pairs will use the "p" prefix for the "urn:mycompany.2009" namespace. It will also omit the xsi and xsd namespaces.

The difference here is that you are adding the XmlSerializerNamespaces to the type itself, rather than employing it explicitly on a call to XmlSerializer.Serialize(). This means that if an instance of your type is serialized by code you do not own (for example in a webservices stack), and that code does not explicitly provide a XmlSerializerNamespaces, that serializer will use the namespaces provided in the instance.

JAVA_HOME does not point to the JDK

I know this question is old but the accepted answer does not work anymore and since this is the fist link on google search i'll tell how i solved this problem.

for eclipse using ubuntu:

go to Window->Preferences->Ant->Runtime->Select Ant_Home_Entries and click on add external jars then find in file explorer where your jdk is (default is in /usr/lib/jvm/) and in the lib folder of your jdk you will find the tool.jar. select this one and click apply.

try to build your project and things should work!

note: i hadn't used ant for a long time but needed it for ycsb couchbase workload generator (http://www.couchbase.com/wiki/display/couchbase/Load+Generator+Setup) if anyone is/was stuck on this.

How to check if character is a letter in Javascript?

// to check if the given string contain alphabets    
function isPangram(sentence){
        let lowerCased = sentence.toLowerCase();
        let letters = "abcdefghijklmnopqrstuvwxyz";
        // traditional for loop can also be used
        for (let char of letters){
            if (!lowerCased.includes(char)) return false;
        }
        return true;
    }

How can I merge two commits into one if I already started rebase?

First you should check how many commits you have:

git log

There are two status:

One is that there are only two commits:

For example:

commit A
commit B

(In this case, you can't use git rebase to do) you need to do following.

$ git reset --soft HEAD^1

$ git commit --amend

Another is that there are more than two commits; you want to merge commit C and D.

For example:

commit A
commit B
commit C
commit D

(under this condition, you can use git rebase)

git rebase -i B

And than use "squash" to do. The rest thins is very easy. If you still don't know, please read http://zerodie.github.io/blog/2012/01/19/git-rebase-i/

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

Setting an environment variable before a command in Bash is not working for the second command in a pipe

How about exporting the variable, but only inside the subshell?:

(export FOO=bar && somecommand someargs | somecommand2)

Keith has a point, to unconditionally execute the commands, do this:

(export FOO=bar; somecommand someargs | somecommand2)

Proper use of mutexes in Python

This is the solution I came up with:

import time
from threading import Thread
from threading import Lock

def myfunc(i, mutex):
    mutex.acquire(1)
    time.sleep(1)
    print "Thread: %d" %i
    mutex.release()


mutex = Lock()
for i in range(0,10):
    t = Thread(target=myfunc, args=(i,mutex))
    t.start()
    print "main loop %d" %i

Output:

main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9

Git push requires username and password

Updating your Git configuration file directly (if you do not want to memorize fancy commands):

Open your .git/config file in your favorite text editor. It will be in the folder that you cloned or in the repository that you performed git init in. Go into that repository. .git is a hidden folder, and pressing Ctrl + H should show the hidden folder, (ls -a in terminal).

Below is a sample of the .git/config file. Copy and paste these lines and be sure to update those lines with your Git information.

[user]
        name = Tux
        email = [email protected]
        username = happy_feet

[remote "origin"]
        url = https://github.com/happy_feet/my_code.git
        fetch = +refs/heads/*:refs/remotes/origin/*

Change the URL part with the following format for SSH:

url = [email protected]:happy_feet/my_code.git

(The above formats do not change with various Git remote servers like GitHub or Bitbucket. It's the same if you are using Git for version control):

Note: The SSH way of connecting to a remote Git repository will require you to add your public SSH key to your Git remote server (like GitHub or Bitbucket. Search the settings page for SSH keys).

To know how to generate your SSH keys, refer to: Creating SSH keys

What is the HTML unicode character for a "tall" right chevron?

From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.

In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).

Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family list or to use a downloadable font. See my Guide to using special characters in HTML.

Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

jquery live hover

This code works:

    $(".ui-button-text").live(
        'hover',
        function (ev) {
            if (ev.type == 'mouseover') {
                $(this).addClass("ui-state-hover");
            }

            if (ev.type == 'mouseout') {
                $(this).removeClass("ui-state-hover");
            }
        });

Input from the keyboard in command line application

If you want to read space separated string, and immediately split the string into an array, you can do this:

var arr = readLine()!.characters.split(" ").map(String.init)

eg.

print("What is your full name?")

var arr = readLine()!.characters.split(" ").map(String.init)

var firstName = ""
var middleName = ""
var lastName = ""

if arr.count > 0 {
    firstName = arr[0]
}
if arr.count > 2 {
    middleName = arr[1]
    lastName = arr[2]
} else if arr.count > 1 {
    lastName = arr[1]
}

print("First Name: \(firstName)")
print("Middle Name: \(middleName)")
print("Last Name: \(lastName)")

How best to read a File into List<string>

Why not use a generator instead?

private IEnumerable<string> ReadLogLines(string logPath) {
    using(StreamReader reader = File.OpenText(logPath)) {
        string line = "";
        while((line = reader.ReadLine()) != null) {
            yield return line;
        }
    }
}

Then you can use it like you would use the list:

var logFile = ReadLogLines(LOG_PATH);
foreach(var s in logFile) {
    // Do whatever you need
}

Of course, if you need to have a List<string>, then you will need to keep the entire file contents in memory. There's really no way around that.

What's the purpose of META-INF?

Generally speaking, you should not put anything into META-INF yourself. Instead, you should rely upon whatever you use to package up your JAR. This is one of the areas where I think Ant really excels: specifying JAR file manifest attributes. It's very easy to say something like:

<jar ...>
    <manifest>
        <attribute name="Main-Class" value="MyApplication"/>
    </manifest>
</jar>

At least, I think that's easy... :-)

The point is that META-INF should be considered an internal Java meta directory. Don't mess with it! Any files you want to include with your JAR should be placed in some other sub-directory or at the root of the JAR itself.

Conda environments not showing up in Jupyter Notebook

While @coolscitist's answer worked for me, there is also a way that does not clutter your kernel environment with the complete jupyter package+deps. It is described in the ipython docs and is (I suspect) only necessary if you run the notebook server in a non-base environment.

conda activate name_of_your_kernel_env
conda install ipykernel
python -m ipykernel install --prefix=/home/your_username/.conda/envs/name_of_your_jupyter_server_env --name 'name_of_your_kernel_env'

You can check if it works using

conda activate name_of_your_jupyter_server_env 
jupyter kernelspec list

Search a whole table in mySQL for a string

Identify all the fields that could be related to your search and then use a query like:

SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
   OR field2 LIKE '%Mary%'
   OR field3 LIKE '%Mary%'
   OR field4 LIKE '%Mary%'
   ....
   (do that for each field you want to check)

Using LIKE '%Mary%' instead of = 'Mary' will look for the fields that contains someCaracters + 'Mary' + someCaracters.

Automated Python to Java translation

Yes Jython does this, but it may or may not be what you want

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

How do I split a string by a multi-character delimiter in C#?

string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));

How do you add an in-app purchase to an iOS application?

I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.

In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.

To summarize:

1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.

These SKProducts should be used to populate your store UI which the user can use to buy a specific product.

2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.

3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:

SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction

4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:

paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError

Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.

Here is another one I created to explain certain things that only text could describe in better manner.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

How to read/write arbitrary bits in C/C++

If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:

struct bitfield{
    unsigned int bit : 1
}
struct bitfield *bitstream;

then later on load it like this (replacing char with int or whatever data you are loading):

long int i;
int j, k;
unsigned char c, d;

bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
for (i=0; i<charstreamlength; i++){
    c=charstream[i];
    for(j=0; j < sizeof(char)*8; j++){
        d=c;
        d=d>>(sizeof(char)*8-j-1);
        d=d<<(sizeof(char)*8-1);
        k=d;
        if(k==0){
            bitstream[sizeof(char)*8*i + j].bit=0;
        }else{
            bitstream[sizeof(char)*8*i + j].bit=1;
        }
    }
}

Then access elements:

bitstream[bitpointer].bit=...

or

...=bitstream[bitpointer].bit

All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.

Use Ant for running program with command line arguments

Can you be a bit more specific about what you're trying to do and how you're trying to do it?

If you're attempting to invoke the program using the <exec> task you might do the following:

<exec executable="name-of-executable">
  <arg value="arg0"/>
  <arg value="arg1"/>
</exec>

How to check if click event is already bound - JQuery

JQuery has solution:

$( "#foo" ).one( "click", function() {
  alert( "This will be displayed only once." );
}); 

equivalent:

$( "#foo" ).on( "click", function( event ) {
  alert( "This will be displayed only once." );
  $( this ).off( event );
});

dplyr mutate with conditional values

Try this:

myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

or this:

myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

Note

Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

Above used this input:

myfile <- 
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

Update 2 dplyr now has case_when which provides another solution:

myfile %>% 
       mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                             V2 == 4 & V3 != 1 ~ 2,
                             TRUE ~ 0))

Meaning of *& and **& in C++

First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.

void foo(int*& x, int**& y) {
    // modifying x or y here will modify a or b in main
}

int main() {
    int val = 42;
    int *a  = &val;
    int **b = &a;

    foo(a, b);
    return 0;
}

Sorting A ListView By Column

i used this trick

private void lv_TavComEmpty_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ListView lv = (ListView)sender;

            //propriety SortOrder make me some problem on graphic layout
            //i use this tag to set last order
            if (lv.Tag == null || (int)lv.Tag > 0)
            //if (lv.Sorting == SortOrder.Ascending)
            {
                ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderBy(t => t.SubItems[e.Column].Text).ToArray();
                lv.Items.Clear();
                lv.Items.AddRange(tmp);

                lv.Tag = -1;
                //lv.Sorting = SortOrder.Descending;
            }
            else
            {
                ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderByDescending(t => t.SubItems[e.Column].Text).ToArray();
                lv.Items.Clear();
                lv.Items.AddRange(tmp);

                lv.Tag = +1;
                //lv.Sorting = SortOrder.Ascending;
            }
        }

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

Content-Disposition:What are the differences between "inline" and "attachment"?

If it is inline, the browser should attempt to render it within the browser window. If it cannot, it will resort to an external program, prompting the user.

With attachment, it will immediately go to the user, and not try to load it in the browser, whether it can or not.

CSS: Hover one element, effect for multiple elements?

I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:

<html>
<head>
<style>
  div.both:hover .image { border: 1px solid blue }
  div.both:hover .layer { border: 1px solid blue }
</style>
</head>

<body>
<div class="section">

<div class="both">
  <div class="image"><img src="myImage.jpg" /></div>
  <div class="layer">Lorem Ipsum</div>
</div>

</div>
</body>
</html>

Create a basic matrix in C (input by user !)

You need to dynamically allocate your matrix. For instance:

int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));

This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.

EnterKey to press button in VBA Userform

Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default property of the button to True (you can set this in the properties window, open by hitting F4)

That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel property of a button to True would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)


Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896

Unable to open project... cannot be opened because the project file cannot be parsed

It sounds like you're going to have to create a new project in Xcode, go into the old directory, and drag all your source files, nibs, and resources into the Xcode files sidebar in the new project. It shouldn't take more than a few minutes, unless you really did a lot of work with custom build settings or targets. Either that, or revert to the last check-in in your source control and manually add any code files which changed between now and then.

Insert HTML with React Variable Statements (JSX)

Try Fragment, if you don't want any of above.

In your case, we can write

import React, {useState, Fragment} from 'react'

const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')

render: function() {
    return (
        <div className="content">{thisIsMyCopy}</div>
    );
}

If you using hook want to set it in a state somewhere with any condition

const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

recyclerview No adapter attached; skipping layout

i have this problem , a few time problem is recycleView put in ScrollView object

After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to minimum height (as per implementation) which is apparently zero.

You have couple of options for fixing this:

  1. Set a certain height to RecyclerView
  2. Set ScrollView.fillViewport to true
  3. Or keep RecyclerView outside of ScrollView. In my opinion, this is the best option by far. If RecyclerView height is not limited - which is the case when it's put into ScrollView - then all Adapter's views have enough place vertically and get created all at once. There is no view recycling anymore which kinda breaks the purpose of RecyclerView .

(Can be followed for android.support.v4.widget.NestedScrollView as well)

Limiting the number of characters in a string, and chopping off the rest

You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So

System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");

will produce

'abc' '  a'

(you can remove quotes, obviously).

Convert string to variable name in JavaScript

var myString = "echoHello";

window[myString] = function() {
    alert("Hello!");
}

echoHello();

Say no to the evil eval. Example here: https://jsfiddle.net/Shaz/WmA8t/

How to find if a native DLL file is compiled as x64 or x86?

Open the dll with a hex editor, like HxD

If the there is a "dt" on the 9th line it is 64bit.

If there is an "L." on the 9th line it is 32bit.

Why would we call cin.clear() and cin.ignore() after reading input?

Why do we use:

1) cin.ignore

2) cin.clear

?

Simply:

1) To ignore (extract and discard) values that we don't want on the stream

2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.

Long version:

If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)

Look at the example:

string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6

What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?

Run the program to see for yourself.

You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".

And "Wlodarczyk" is not shown. It seems like if it was gone (?)*

What happened? ;-)

Because there is a space between "Arkadiusz" and "Wlodarczyk".

"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.

The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.

So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;

Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).

It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...


All right all right. But how to fix it?!

Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)

I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)

After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"

You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.

Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?

Yes!

internal state of cin set to 4 is like an alarm that is howling and making noise.

cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".

All right let's do so! Let's use cin.clear().

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl; 
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl;  //new line is here :-)

We can surely see after executing above code that the state is equal to goodbit.

Great so the problem is solved?

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;; 
cin.clear(); 
cout << cin.rdstate() << endl; 
cin >> age;//new line is here :-)

Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.

WHY?!

Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.

You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)

So it's time for another tool:

cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.

So could we use it even before making the alarm goes off?

Yes:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;

The "Wlodarczyk" is gonna be removed before making the noise in line 7.

What is 10000 and '\n'?

It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.


So the main cause of problem is gone before noise was made...

Why do we need 'clear' then?

What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?

Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.

So we must use clear in case like that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

But should you clear the state 'just in case'?

Of course not.

If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.

So we can use conditional statement to check if the user put wrong type on the stream

int age;
if (cin >> age) //it's gonna return false if types doesn't match
    cout << "You put integer";
else
    cout << "You bad boy! it was supposed to be int";

All right so we can fix our initial problem like for example that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

int age;
cout << "Give me your age:" << endl;
if (cin >> age)
  cout << "Your age is equal to:" << endl;
else
{
 cin.clear();
 cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
 cout << "Give me your age name as string I dare you";
 cin >> age;
}

Of course this can be improved by for example doing what you did in question using loop while.

BONUS:

You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?

Sure, you can do it two ways:

1)

string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;

cout << "Hello, " << name << " " << surname << endl;

2) or by using getline function.

getline(cin, nameOfStringVariable);

and that's how to do it:

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

The second option might backfire you in case you use it after you use 'cin' before the getline.

Let's check it out:

a)

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

If you put "20" as age you won't be asked for nameAndSurname.

But if you do it that way:

b)

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll

everything is fine.

WHAT?!

Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.

b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.

a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.

So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.

So the proper code would be:

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n') 
cout << "Your age is" << age << endl;


string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

I hope streams are more clear to you know.

Hah silence me please! :-)

Table Height 100% inside Div element

This is how you can do it-

HTML-

<div style="overflow:hidden; height:100%">
     <div style="float:left">a<br>b</div>
     <table cellpadding="0" cellspacing="0" style="height:100%;">     
          <tr><td>This is the content of a table that takes 100% height</td></tr>  
      </table>
 </div>

CSS-

html,body
{
    height:100%;
    background-color:grey;
}
table
{
    background-color:yellow;
}

See the DEMO

Update: Well, if you are not looking for applying 100% height to your parent containers, then here is a jQuery solution that should help you-

Demo-using jQuery

Script-

 $(document).ready(function(){
    var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
    $("#tab").css("height",b);
});

"The system cannot find the file specified"

start the sql server agent, that should fix your problem

How can I check if a MySQL table exists with PHP?

It was already posted but here it is with PDO (same query)...

$connection = new PDO ( "mysql:host=host_db; dbname=name_db", user_db, pass_db );

if ($connection->query ("DESCRIBE table_name"  )) {
    echo "exist";
} else {
    echo "doesn't exist";
}

Works like a charm for me....

And here's another approach (i think it is slower)...

if ($connection->query ( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' AND table_name ='tbl_name'" )->fetch ()) {
    echo "exist";
} else {
    echo "doesn't exist";
}

You can also play with this query:

SHOW TABLE STATUS FROM db_name LIKE 'tbl_name'

I think this was suggested to use in the mysql page.

WordPress asking for my FTP credentials to install plugins

I was facing the same problem! I've added the code below in wp-config.php file (in any line) and it's working now!

define('FS_METHOD', 'direct');

How to set the env variable for PHP?

For windows: Go to your "system properties" please.then follow as bellow.

Advanced system settings(from left sidebar)->Environment variables(very last option)->path(from lower box/system variables called as I know)->edit

then concatenate the "php" location you have in your pc (usually it is where your xampp is installed say c:/xampp/php)

N.B : Please never forget to set semicolon (;) between your recent concatenated path and the existed path in your "Path"

Something like C:\Program Files\Git\usr\bin;C:\xampp\php

Hope this will help.Happy coding. :) :)

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

How do I remove diacritics (accents) from a string in .NET?

This works fine in java.

It basically converts all accented characters into their deAccented counterparts followed by their combining diacritics. Now you can use a regex to strip off the diacritics.

import java.text.Normalizer;
import java.util.regex.Pattern;

public String deAccent(String str) {
    String nfdNormalizedString = Normalizer.normalize(str, Normalizer.Form.NFD); 
    Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
    return pattern.matcher(nfdNormalizedString).replaceAll("");
}

How can I select all elements without a given class in jQuery?

You can use the .not() method or :not() selector

Code based on your example:

$("ul#list li").not(".active") // not method
$("ul#list li:not(.active)")   // not selector

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Case-insensitive search in Rails model

Several comments refer to Arel, without providing an example.

Here is an Arel example of a case-insensitive search:

Product.where(Product.arel_table[:name].matches('Blue Jeans'))

The advantage of this type of solution is that it is database-agnostic - it will use the correct SQL commands for your current adapter (matches will use ILIKE for Postgres, and LIKE for everything else).

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

How to get a Color from hexadecimal Color String

Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.

jQueryUI modal dialog does not show close button (x)

Pure CSS Workaround:

I was using both bootstrap and jQuery UI and changing the order of adding the scripts broke some other objects. I ended up using pure CSS workaround:

.ui-dialog-titlebar-close {
  background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_888888_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
  border: medium none;
}
.ui-dialog-titlebar-close:hover {
  background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_222222_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
}

Apache SSL Configuration Error (SSL Connection Error)

A common cause I wanted to suggest for this situation:

Sometimes a customer is running Skype, which is using port 443 without their realizing it. When they go to start Tomcat or Apache, it appears to start but cannot bind with port 443. This is the exact message that the user would receive in the browser. The fix is to stop what was running on port 443 and re-start the webserver so it can bind with port 443.

The customer can re-start Skype after starting the webserver, and Skype will detect that port 443 is in use and choose a different port to use.

nvarchar(max) still being truncated

The problem is with implicit conversion.

If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to nVarChar(4000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter!

When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so:

SET @Query = CAST('' as nVarChar(MAX))--Force implicit conversion to nVarChar(MAX)
           + 'SELECT...'-- some of the query gets set here
           + '...'-- more query gets added on, etc.

What a pain and scary to think this is just how SQL Server works. :(

I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above.

For those who hit an 8000 character max, it was probably because you had no Unicode so it was implicitly converted to VarChar(8000).

Explanation:
What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). After it is done figuring out the value (and after truncating it for you) it then converts it to (MAX) when assigning it to your variable, but by then it is too late.

@viewChild not working - cannot read property nativeElement of undefined

What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:

 window.onload = function(){
     this.keywordsInput.nativeElement.focus();
 }

Struct like objects in Java

As with most things, there's the general rule and then there are specific circumstances. If you are doing a closed, captured application so that you know how a given object is going to be used, then you can exercise more freedom to favor visibility and/or efficiency. If you're developing a class which is going to be used publicly by others beyond your control, then lean towards the getter/setter model. As with all things, just use common sense. It's often ok to do an initial round with publics and then change them to getter/setters later.

What is the difference between Release and Debug modes in Visual Studio?

Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.

As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Primitive type 'short' - casting in Java

In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.

What is the Java equivalent for LINQ?

Java LINQ to SQL implementation. Provides full language integration and larger feature set compared to .NET LINQ.

Change fill color on vector asset in Android Studio

Don't edit the vector assets directly. If you're using a vector drawable in an ImageButton, just choose your color in android:tint.

<ImageButton
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:id="@+id/button"
        android:src="@drawable/ic_more_vert_24dp"
        android:tint="@color/primary" />

How to include files outside of Docker's build context?

Using docker-compose, I accomplished this by creating a service that mounts the volumes that I need and committing the image of the container. Then, in the subsequent service, I rely on the previously committed image, which has all of the data stored at mounted locations. You will then have have to copy these files to their ultimate destination, as host mounted directories do not get committed when running a docker commit command

You don't have to use docker-compose to accomplish this, but it makes life a bit easier

# docker-compose.yml

version: '3'
  services:
    stage:
      image: alpine
      volumes:
        - /host/machine/path:/tmp/container/path
      command: bash -c "cp -r /tmp/container/path /final/container/path"
    setup:
      image: stage
# setup.sh

# Start "stage" service
docker-compose up stage

# Commit changes to an image named "stage"
docker commit $(docker-compose ps -q stage) stage

# Start setup service off of stage image
docker-compose up setup

Fast way to concatenate strings in nodeJS/JavaScript

The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.

Tested with the following code:

function a(){
    var s = "hello";
    var p = "world";
    s = s + p;
    return s;
}

function b(){
    var s = new Buffer("hello");
    var p = new Buffer("world");
    s = Buffer.concat([s,p]);
    return s;
}

var times = 100000;

var t1 = new Date();
for( var i = 0; i < times; i++){
    a();
}

var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
    b();
}

var t3 = new Date();

console.log("Buffer took: " + (t3-t2) + " ms.");

Output:

Normal took: 4 ms.
Buffer took: 458 ms.

Getting 400 bad request error in Jquery Ajax POST

You need to build query from "data" object using the following function

function buildQuery(obj) {
        var Result= '';
        if(typeof(obj)== 'object') {
            jQuery.each(obj, function(key, value) {
                Result+= (Result) ? '&' : '';
                if(typeof(value)== 'object' && value.length) {
                    for(var i=0; i<value.length; i++) {
                        Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
                    }
                } else {
                    Result+= [key, encodeURIComponent(value)].join('=');
                }
            });
        }
        return Result;
    }

and then proceed with

var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});

How to loop through all the properties of a class?

Note that if the object you are talking about has a custom property model (such as DataRowView etc for DataTable), then you need to use TypeDescriptor; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}

This also provides easy access to things like TypeConverter for formatting:

    string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));

Converting String to Int with Swift

swift 4.0

let stringNumber = "123"
let number = Int(stringNumber) //here number is of type "Int?"


//using Forced Unwrapping

if number != nil {         
 //string is converted to Int
}

you could also use Optional Binding other than forced binding.

eg:

  if let number = Int(stringNumber) { 
   // number is of type Int 
  }

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

HTTP Status 404 - The requested resource (/) is not available

Please check in your server specification again, if you have changed your port number to something else. And change the port number in your link whatever new port number it is.

Also check whether your server is running properly before you try accessing your localhost.

Force IE9 to emulate IE8. Possible?

The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.

C++ Boost: undefined reference to boost::system::generic_category()

Depending on the boost version libboost-system comes with the -mt suffix which should indicate the libraries multithreading capability.

So if -lboost_system cannot be found by the linker try -lboost_system-mt.

Maven skip tests

There is a difference between each parameter.

  • The -DskipTests skip running tests phase, it means at the end of this process you will have your tests compiled.

  • The -Dmaven.test.skip=true skip compiling and running tests phase.

As the parameter -Dmaven.test.skip=true skip compiling you don't have the tests artifact.

For more information just read the surfire documentation: http://maven.apache.org/plugins-archives/maven-surefire-plugin-2.12.4/examples/skipping-test.html

How do I install Python OpenCV through Conda?

To install OpenCV in Anaconda, start up the Anaconda command prompt and install OpenCV with

conda install -c https://conda.anaconda.org/menpo opencv3

Test that it works in your Anaconda Spyder or IPython console with

import cv2

You can also check the installed version using:

cv2.__version__

How can I get current date in Android?

  public static String getDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

Can't find file executable in your configured search path for gnc gcc compiler

Here's an easy way for Windows users.

  1. Uninstall the existing codeblocks from your system.
  2. Restart system.
  3. Go to http://www.codeblocks.org/downloads/26
  4. Download the codeblocks-16.01mingw-setup.exe file. It includes the GCC/G++ compiler and GDB debugger from TDM-GCC (version 4.9.2, 32 bit, SJLJ).

How to get the indexpath.row when an element is activated?

// CustomCell.swift

protocol CustomCellDelegate {
    func tapDeleteButton(at cell: CustomCell)
}

class CustomCell: UICollectionViewCell {
    
    var delegate: CustomCellDelegate?
    
    fileprivate let deleteButton: UIButton = {
        let button = UIButton(frame: .zero)
        button.setImage(UIImage(named: "delete"), for: .normal)
        button.addTarget(self, action: #selector(deleteButtonTapped(_:)), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    @objc fileprivate func deleteButtonTapped(_sender: UIButton) {
        delegate?.tapDeleteButton(at: self)
    }
    
}

//  ViewController.swift

extension ViewController: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as? CustomCell else {
            fatalError("Unexpected cell instead of CustomCell")
        }
        cell.delegate = self
        return cell
    }

}

extension ViewController: CustomCellDelegate {

    func tapDeleteButton(at cell: CustomCell) {
        // Here we get the indexPath of the cell what we tapped on.
        let indexPath = collectionView.indexPath(for: cell)
    }

}

How to use zIndex in react-native

You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.

The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.

Set background color in PHP?

You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.

What does "&" at the end of a linux command mean?

I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C). Now a program can use SIG_IGN to ignore all signals or SIG_DFL to restore the default action.

Now if you do $ command & then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

Rxjs 5.5 “ Property ‘map’ does not exist on type Observable.

The problem was related to the fact that you need to add pipe around all operators.

Change this,

this.myObservable().map(data => {})

to this

this.myObservable().pipe(map(data => {}))

And

Import map like this,

import { map } from 'rxjs/operators';

It will solve your issues.

PHP - If variable is not empty, echo some html code

if(!empty($web))
{
   echo 'Something';
}

How to detect if CMD is running as Administrator/has elevated privileges?

The easiest way to do this on Vista, Win 7 and above is enumerating token groups and looking for the current integrity level (or the administrators sid, if only group memberhip is important):

Check if we are running elevated:

whoami /groups | find "S-1-16-12288" && Echo I am running elevated, so I must be an admin anyway ;-)

Check if we belong to local administrators:

whoami /groups | find "S-1-5-32-544" && Echo I am a local admin

Check if we belong to domain admins:

whoami /groups | find "-512 " && Echo I am a domain admin

The following article lists the integrity level SIDs windows uses: http://msdn.microsoft.com/en-us/library/bb625963.aspx

The maximum value for an int type in Go

One way to solve this problem is to get the starting points from the values themselves:

var minLen, maxLen uint
if len(sliceOfThings) > 0 {
  minLen = sliceOfThings[0].minLen
  maxLen = sliceOfThings[0].maxLen
  for _, thing := range sliceOfThings[1:] {
    if minLen > thing.minLen { minLen = thing.minLen }
    if maxLen < thing.maxLen { maxLen = thing.maxLen }
  }
}

Cannot use special principal dbo: Error 15405

Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405

When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)

Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

php artisan serve 

this command get the env contents for the first time and if you update .env file need to restart it.

in my case my username and dbname is valid and php artisan migrate worked

but need to cntrl+c , to cancel php artisan serve , and run it again

php artisan serve

How to import Swagger APIs into Postman?

You can do that: Postman -> Import -> Link -> {root_url}/v2/api-docs

Facebook Graph API, how to get users email?

Make sure to fully specify the version number of the API as something like "v2.11" and not "2.11"

I'm not sure what it defaults to if this is incorrect, but I got some odd errors trying to just retrieve the email when I missed the v.

Spring boot: Unable to start embedded Tomcat servlet container

If you are running on a linux environment, basically your app does not have rights for the default port.

Try 8181 by giving the following option on VM.

-Dserver.port=8181

How to add a primary key to a MySQL table?

For me, none of suggestions worked giving me the errors of syntax, so I just gave a try using phpmyadmin(version 4.9.2), (10.4.10-MariaDB) and added id column with auto-increment primary key. Id column was nicely added from the first element.

Query output was:

ALTER TABLE table_name ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id);

Disable button in angular with two conditions?

Declare a variable in component.ts and initialize it to some value

 buttonDisabled: boolean;

  ngOnInit() {
    this.buttonDisabled = false;
  }

Now in .html or in the template, you can put following code:

<button disabled="{{buttonDisabled}}"> Click Me </button>

Now you can enable/disable button by changing value of buttonDisabled variable.

How can I use Oracle SQL developer to run stored procedures?

I am not sure how to see the actual rows/records that come back.

Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.

In SQL Developer, you can execute a procedure that returns a ref cursor as follows

var rc refcursor
exec proc_name(:rc)

After that, if you execute the following, it will show the results from the cursor:

print rc

Plotting a list of (x, y) coordinates in python matplotlib

As per this example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

enter image description here

To unpack your data from pairs into lists use zip:

x, y = zip(*li)

So, the one-liner:

plt.scatter(*zip(*li))

String date to xmlgregoriancalendar conversion

For me the most elegant solution is this one:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");

Using Java 8.

Extended example:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());

This prints out:

7
1
2014

How to get current local date and time in Kotlin

My utils method for get current date time using Calendar when our minSdkVersion < 26.

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

fun getCurrentDateTime(): Date {
    return Calendar.getInstance().time
}

Using

import ...getCurrentDateTime
import ...toString
...
...
val date = getCurrentDateTime()
val dateInString = date.toString("yyyy/MM/dd HH:mm:ss")

How to iterate through LinkedHashMap with lists as values

for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.

Disable and enable buttons in C#

Update 2019

This is now IsEnabled

 takePicturebutton.IsEnabled = false; // true

Java enum - why use toString instead of name

Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

Use toString() when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

From the javadoc (emphasis mine) :

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

regular expression for finding 'href' value of a <a> link

Using regex to parse html is not recommended

regex is used for regularly occurring patterns.html is not regular with it's format(except xhtml).For example html files are valid even if you don't have a closing tag!This could break your code.

Use an html parser like htmlagilitypack

You can use this code to retrieve all href's in anchor tag using HtmlAgilityPack

HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);

var hrefList = doc.DocumentNode.SelectNodes("//a")
                  .Select(p => p.GetAttributeValue("href", "not found"))
                  .ToList();

hrefList contains all href`s

Binding a Button's visibility to a bool value in ViewModel

In View:

<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>

In view Model:

public _advancedFormat = Visibility.visible (whatever you start with)

public Visibility AdvancedFormat
{
 get{return _advancedFormat;}
 set{
   _advancedFormat = value;
   //raise property changed here
}

You will need to have a property changed event

 protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
        PropertyChanged.Raise(this, e); 
    } 

    protected void OnPropertyChanged(string propertyName) 
    { 
        OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); 
    } 

This is how they use Model-view-viewmodel

But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.

Is there a "do ... while" loop in Ruby?

CAUTION:

The begin <code> end while <condition> is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop, e.g.

loop do 
  # some code here
  break if <condition>
end 

Here's an email exchange in 23 Nov 2005 where Matz states:

|> Don't use it please.  I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised.  What do you regret about it?

Because it's hard for users to tell

  begin <code> end while <cond>

works differently from

  <code> while <cond>

RosettaCode wiki has a similar story:

During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.

What does 'super' do in Python?

some great answers here, but they do not tackle how to use super() in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__

to answer that part and to be able to effectively use super() i'd suggest reading my answer super() and changing the signature of cooperative methods.

here's just the solution to this scenario:

  1. the top-level classes in your hierarchy must inherit from a custom class like SuperObject:
  2. if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept **kwargs.
class SuperObject:        
    def __init__(self, **kwargs):
        print('SuperObject')
        mro = type(self).__mro__
        assert mro[-1] is object
        if mro[-2] is not SuperObject:
            raise TypeError(
                'all top-level classes in this hierarchy must inherit from SuperObject',
                'the last class in the MRO should be SuperObject',
                f'mro={[cls.__name__ for cls in mro]}'
            )

        # super().__init__ is guaranteed to be object.__init__        
        init = super().__init__
        init()

example usage:

class A(SuperObject):
    def __init__(self, **kwargs):
        print("A")
        super(A, self).__init__(**kwargs)

class B(SuperObject):
    def __init__(self, **kwargs):
        print("B")
        super(B, self).__init__(**kwargs)

class C(A):
    def __init__(self, age, **kwargs):
        print("C",f"age={age}")
        super(C, self).__init__(age=age, **kwargs)

class D(B):
    def __init__(self, name, **kwargs):
        print("D", f"name={name}")
        super(D, self).__init__(name=name, **kwargs)

class E(C,D):
    def __init__(self, name, age, *args, **kwargs):
        print( "E", f"name={name}", f"age={age}")
        super(E, self).__init__(name=name, age=age, *args, **kwargs)

E(name='python', age=28)

output:

E name=python age=28
C age=28
A
D name=python
B
SuperObject

Compare given date with today

If you do things with time and dates Carbon is you best friend;

Install the package then:

$theDay = Carbon::make("2010-01-21 00:00:00.0");

$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))

lt = less than, gt = greater than

As in the question:

$theDay->gt(Carbon::today()) ? true : false;

and much more;

"Parameter not valid" exception loading System.Drawing.Image

My guess is that byteArrayIn doesn't contain valid image data.

Please give more information though:

  • Which line of code is throwing an exception?
  • What's the message?
  • Where did you get byteArrayIn from, and are you sure it should contain a valid image?

ReactJS and images in public folder

You don't need any webpack configuration for this..

In your component just give image path. By default react will know its in public directory.

<img src="/image.jpg" alt="image" />

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Just create the database using createdb CLI tool:

PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB

If the database exists, it will return an error:

createdb: database creation failed: ERROR:  database "mydb" already exists

Why my $.ajax showing "preflight is invalid redirect error"?

The error indicates that the preflight is getting a redirect response. This can happen for a number of reasons. Find out where you are getting redirected to for clues to why it is happening. Check the network tab in Developer Tools.

One reason, as @Peter T mentioned, is that the API likely requires HTTPS connections rather than HTTP and all requests over HTTP get redirected. The Location header returned by the 302 response would say the same url with http changed to https in this case.

Another reason might be that your authentication token is not getting sent, or is not correct. Most servers are set up to redirect all requests that don't include an authentication token to the login page. Again, check your Location header to see if this is where you're getting sent and also take a look to make sure the browser sent your auth token with the request.

Oftentimes, a server will be configured to always redirect requests that don't have auth tokens to the login page - including your preflight/OPTIONS requests. This is a problem. Change the server configuration to permit OPTIONS requests from non-authenticated users.

How to save a plot as image on the disk?

To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:

R < myscript.R --no-save

This could be converted to jpg/png as necessary

Use FontAwesome or Glyphicons with css :before

Re: using icon in :before – recent Font Awesome builds include the .fa-icon() mixin for SASS and LESS. This will automatically include the font-family as well as some rendering tweaks (e.g. -webkit-font-smoothing). Thus you can do, e.g.:

// Add "?" icon to header.
h1:before {
    .fa-icon();
    content: "\f059";
}

Android SDK Manager Not Installing Components

In my case I was using Windows 7 with the 64-bit OS. We installed the 64-bit Java SE and 64-bit ADT Bundle. With that set up, we couldn't get the SDK manager to work correctly (specifically, no downloads allowed and it didn't show all the API download options). After trying all of the above answers and from other posts, we decided to look into the Java set up and realized it might the 64-bit configuration that's giving the ADT bundle grief (I vaguely recall seeing/reading this issue before).

So we uninstalled Java 64-bit and reinstalled the 32-bit, and then used the 32-bit ADT bundle, and it worked correctly. The system user was already an admin, so we didn't need to "Run as Administrator"

Maven Jacoco Configuration - Exclude classes/packages from report not working

Your XML is slightly wrong, you need to add any class exclusions within an excludes parent field, so your above configuration should look like the following as per the Jacoco docs

<configuration>
    <excludes>
        <exclude>**/*Config.*</exclude>
        <exclude>**/*Dev.*</exclude>
    </excludes>
</configuration>

The values of the exclude fields should be class paths (not package names) of the compiled classes relative to the directory target/classes/ using the standard wildcard syntax

*   Match zero or more characters
**  Match zero or more directories
?   Match a single character

You may also exclude a package and all of its children/subpackages this way:

<exclude>some/package/**/*</exclude>

This will exclude every class in some.package, as well as any children. For example, some.package.child wouldn't be included in the reports either.

I have tested and my report goal reports on a reduced number of classes using the above.

If you are then pushing this report into Sonar, you will then need to tell Sonar to exclude these classes in the display which can be done in the Sonar settings

Settings > General Settings > Exclusions > Code Coverage

Sonar Docs explains it a bit more

Running your command above

mvn clean verify

Will show the classes have been excluded

No exclusions

[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 37 classes

With exclusions

[INFO] --- jacoco-maven-plugin:0.7.4.201502262128:report (post-test) @ ** ---
[INFO] Analyzed bundle '**' with 34 classes

Hope this helps

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

SnappySnippet

I finally found some time to create this tool. You can install SnappySnippet from Github. It allows easy HTML+CSS extraction from the specified (last inspected) DOM node. Additionally, you can send your code straight to CodePen or JSFiddle. Enjoy!

SnappySnippet Chrome extension

Other features

  • cleans up HTML (removing unnecessary attributes, fixing indentation)
  • optimizes CSS to make it readable
  • fully configurable (all filters can be turned off)
  • works with ::before and ::after pseudo-elements
  • nice UI thanks to Bootstrap & Flat-UI projects

Code

SnappySnippet is open source, and you can find the code on GitHub.

Implementation

Since I've learned quite a lot while making this, I've decided to share some of the problems I've experienced and my solutions to them, maybe someone will find it interesting.

First attempt - getMatchedCSSRules()

At first I've tried retrieving the original CSS rules (coming from CSS files on the website). Quite amazingly, this is very simple thanks to window.getMatchedCSSRules(), however, it didn't work out well. The problem was that we were taking only a part of the HTML and CSS selectors that were matching in the context of the whole document, which were not matching anymore in the context of an HTML snippet. Since parsing and modifying selectors didn't seem like a good idea, I gave up on this attempt.

Second attempt - getComputedStyle()

Then, I've started from something that @CollectiveCognition suggested - getComputedStyle(). However, I really wanted to separate CSS form HTML instead of inlining all styles.

Problem 1 - separating CSS from HTML

The solution here wasn't very beautiful but quite straightforward. I've assigned IDs to all nodes in the selected subtree and used that ID to create appropriate CSS rules.

Problem 2 - removing properties with default values

Assigning IDs to the nodes worked out nicely, however I found out that each of my CSS rules has ~300 properties making the whole CSS unreadable.
Turns out that getComputedStyle() returns all possible CSS properties and values calculated for the given element. Some of them where empty, some had browser default values. To remove default values I had to get them from the browser first (and each tag has different default values). The solution was to compare the styles of the element coming from the website with the same element inserted into an empty <iframe>. The logic here was that there are no style sheets in an empty <iframe>, so each element I've appended there had only default browser styles. This way I was able to get rid of most of the properties that were insignificant.

Problem 3 - keeping only shorthand properties

Next thing I have spotted was that properties having shorthand equivalent were unnecessarily printed out (e.g. there was border: solid black 1px and then border-color: black;, border-width: 1px itd.).
To solve this I've simply created a list of properties that have shorthand equivalents and filtered them out from the results.

Problem 4 - removing prefixed properties

The number of properties in each rule was significantly lower after the previous operation, but I've found that I sill had a lot of -webkit- prefixed properties that I've never hear of (-webkit-app-region? -webkit-text-emphasis-position?).
I was wondering if I should keep any of these properties because some of them seemed useful (-webkit-transform-origin, -webkit-perspective-origin etc.). I haven't figured out how to verify this, though, and since I knew that most of the time these properties are just garbage, I decided to remove them all.

Problem 5 - combining same CSS rules

The next problem I have spotted was that the same CSS rules are repeated over and over (e.g. for each <li> with the exact same styles there was the same rule in the CSS output created).
This was just a matter of comparing rules with each other and combining these that had exactly the same set of properties and values. As a result, instead of #LI_1{...}, #LI_2{...} I got #LI_1, #LI_2 {...}.

Problem 6 - cleaning up and fixing indentation of HTML

Since I was happy with the result, I moved to HTML. It looked like a mess, mostly because the outerHTML property keeps it formatted exactly as it was returned from the server.
The only thing HTML code taken from outerHTML needed was a simple code reformatting. Since it's something available in every IDE, I was sure that there is a JavaScript library that does exactly that. And it turns out that I was right (jquery-clean). What's more, I've got unnecessary attributes removal extra (style, data-ng-repeat etc.).

Problem 7 - filters breaking CSS

Since there is a chance that in some circumstances filters mentioned above may break CSS in the snippet, I've made all of them optional. You can disable them from the Settings menu.

Read file data without saving it in Flask

in function

def handleUpload():
    if 'photo' in request.files:
        photo = request.files['photo']
        if photo.filename != '':      
            image = request.files['photo']  
            image_string = base64.b64encode(image.read())
            image_string = image_string.decode('utf-8')
            #use this to remove b'...' to get raw string
            return render_template('handleUpload.html',filestring = image_string)
    return render_template('upload.html')

in html file

<html>
<head>
    <title>Simple file upload using Python Flask</title>
</head>
<body>
    {% if filestring %}
      <h1>Raw image:</h1>
      <h1>{{filestring}}</h1>
      <img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
    {% else %}
      <h1></h1>
    {% endif %}
</body>

Reading file from Workspace in Jenkins with Groovy script

As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:

import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*    

try{
//get Jenkins instance
    def jenkins = Jenkins.instance
//get job Item
    def item = jenkins.getItemByFullName("The_JOB_NAME")
    println item
// get workspacePath for the job Item
    def workspacePath = jenkins.getWorkspaceFor (item)
    println workspacePath

    def file = new File(workspacePath.toString()+"\\pom.xml")
    def pomFile = new XmlSlurper().parse(file)
    def pomModules = pomFile.modules.children().join(",")
    return pomModules
} catch (Exception ex){
    println ex.message
}

CSS :not(:last-child):after selector

Remove the : before last-child and the :after and used

 ul li:not(last-child){
 content:' |';
}

Hopefully,it should work

OS X Terminal UTF-8 issues

In my case, simply using the uxterm command instead of xterm solved the problem. It's available in /opt/X11/bin/uxterm by installing the XQuartz package provided by Apple.

How to Convert unsigned char* to std::string in C++?

You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;

However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;

How can we programmatically detect which iOS version is device running on?

[[[UIDevice currentDevice] systemVersion] floatValue]

What is the bower (and npm) version syntax?

Based on semver, you can use

  • Hyphen Ranges X.Y.Z - A.B.C 1.2.3-2.3.4 Indicates >=1.2.3 <=2.3.4

  • X-Ranges 1.2.x 1.X 1.2.*

  • Tilde Ranges ~1.2.3 ~1.2 Indicates allowing patch-level changes or minor version changes.

  • Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

    Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple

    • ^1.2.x (means >=1.2.0 <2.0.0)
    • ^0.0.x (means >=0.0.0 <0.1.0)
    • ^0.0 (means >=0.0.0 <0.1.0)

Hibernate, @SequenceGenerator and allocationSize

To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.

However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.

How to pass the button value into my onclick event function?

You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

function dosomething(element) {
  console.log(element.value);
}

Arduino Tools > Serial Port greyed out

So I did with sudo usermod -a -G dialout <my-username>.

You need to log out after you add yourself to a group so those changes are applied. Just log out and log in again and the menu should be available.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

I use:

public synchronized int generateViewId() {
    Random rand = new Random();
    int id;
    while (findViewById(id = rand.nextInt(Integer.MAX_VALUE) + 1) != null);
    return id;
}

By using a random number I always have a huge chance of getting the unique id in first attempt.

Bootstrap: add margin/padding space between columns

Super easy with flexbox. Leave room for some space by changing the columns to col-md-5

<div class="row widgets">
    <div class="text-center col-md-5">
        Widget 1
    </div>
    <div class="text-center col-md-5">
        Widget 2
    </div>
</div>

CSS

.widgets {
    display: flex;
    justify-content: space-around;
}

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use

$(window).on('load', function() {
    // your code here
});

Which will wait until the page is loaded. $(document).ready() waits until the DOM is loaded.

In plain JS:

window.addEventListener('load', function() {
    // your code here
})

Initializing a member array in constructor initializer

  1. No, unfortunately.
  2. You just can't in the way you want, as it's not allowed by the grammar (more below). You can only use ctor-like initialization, and, as you know, that's not available for initializing each item in arrays.
  3. I believe so, as they generalize initialization across the board in many useful ways. But I'm not sure on the details.

In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.

T var = {...};

Finding longest string in array

function findLongestWord(str) {
  str = str.split(" ");
  var sorted = str.sort(function(prev,current){
    return prev.length - current.length;   
  });
  var index = sorted.length;
  str = sorted[index-1];
  return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm