Programs & Examples On #Greenhills

Green Hills Software is a company which makes tools and operating systems for embedded platforms.

Make file echo displaying "$PATH" string

In the manual for GNU make, they talk about this specific example when describing the value function:

The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.

The syntax of the value function is:

 $(value variable)

Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)

The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:

 FOO = $PATH

 all:
         @echo $(FOO)
         @echo $(value FOO)

The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.

How to get MAC address of your machine using a C program?

Much nicer than all this socket or shell madness is simply using sysfs for this:

the file /sys/class/net/eth0/address carries your mac adress as simple string you can read with fopen()/fscanf()/fclose(). Nothing easier than that.

And if you want to support other network interfaces than eth0 (and you probably want), then simply use opendir()/readdir()/closedir() on /sys/class/net/.

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Regular Expression for alphanumeric and underscores

Um...question: Does it need to have at least one character or no? Can it be an empty string?

^[A-Za-z0-9_]+$

Will do at least one upper or lower case alphanumeric or underscore. If it can be zero length, then just substitute the + for *

^[A-Za-z0-9_]*$

Edit:

If diacritics need to be included (such as cedilla - ç) then you would need to use the word character which does the same as the above, but includes the diacritic characters:

^\w+$

Or

^\w*$

What is the difference between `sorted(list)` vs `list.sort()`?

Here are a few simple examples to see the difference in action:

See the list of numbers here:

nums = [1, 9, -3, 4, 8, 5, 7, 14]

When calling sorted on this list, sorted will make a copy of the list. (Meaning your original list will remain unchanged.)

Let's see.

sorted(nums)

returns

[-3, 1, 4, 5, 7, 8, 9, 14]

Looking at the nums again

nums

We see the original list (unaltered and NOT sorted.). sorted did not change the original list

[1, 2, -3, 4, 8, 5, 7, 14]

Taking the same nums list and applying the sort function on it, will change the actual list.

Let's see.

Starting with our nums list to make sure, the content is still the same.

nums

[-3, 1, 4, 5, 7, 8, 9, 14]

nums.sort()

Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.

nums
[-3, 1, 2, 4, 5, 7, 8, 14]

Add / remove input field dynamically with jQuery

In your click function, you can write:

function addMoreRows(frm) {
   rowCount ++;
   var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%"  maxlength="120" /></td><td><input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
   jQuery('#addedRows').append(recRow);
}

Or follow this link: http://www.discussdesk.com/add-remove-more-rows-dynamically-using-jquery.htm

What's the fastest way to loop through an array in JavaScript?

Another jsperf.com test: http://jsperf.com/while-reverse-vs-for-cached-length

The reverse while loop seems to be the fastest. Only problem is that while (--i) will stop at 0. How can I access array[0] in my loop then?

How do I check whether a checkbox is checked in jQuery?

I am using this and this is working absolutely fine:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

Note: If the checkbox is checked it will return true otherwise undefined, so better check for the "TRUE" value.

How to change the foreign key referential action? (behavior)

You can simply use one query to rule them all: ALTER TABLE products DROP FOREIGN KEY oldConstraintName, ADD FOREIGN KEY (product_id, category_id) REFERENCES externalTableName (foreign_key_name, another_one_makes_composite_key) ON DELETE CASCADE ON UPDATE CASCADE

Cannot add a project to a Tomcat server in Eclipse

For me:

It was Eclipse v4.5 (Mars) which did not support Java SE 7, so I added Java SE 8. It worked.

On localhost, how do I pick a free port number?

In my experience, just pick a relatively high number (between 1024-65535) that you think is unlikely to be used by anything else. For example, port # 8080 and # 5555 are ones that I routinely use. Just pick a port number like this as opposed to just making the code randomly select it and then having to find the port number later is much easier for me.

For example, in my current ChatBot project:

port = 8080

What is the difference between getText() and getAttribute() in Selenium WebDriver?

  <input attr1='a' attr2='b' attr3='c'>foo</input>

getAttribute(attr1) you get 'a'

getAttribute(attr2) you get 'b'

getAttribute(attr3) you get 'c'

getText() with no parameter you can only get 'foo'

SQL LIKE condition to check for integer?

Which one of those is indexable?

This one is definitely btree-indexable:

WHERE title >= '0' AND title < ':'

Note that ':' comes after '9' in ASCII.

Usage of $broadcast(), $emit() And $on() in AngularJS

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

Demonstrates the method calls:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

Read entire file in Scala?

as a few people mentioned scala.io.Source is best to be avoided due to connection leaks.

Probably scalax and pure java libs like commons-io are the best options until the new incubator project (ie scala-io) gets merged.

java.net.SocketException: Connection reset

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

How do I access nested HashMaps in Java?

If you plan on constructing HashMaps with variable depth, use a recursive data structure.

Below is an implementation providing a sample interface:

class NestedMap<K, V> {

    private final HashMap<K, NestedMap> child;
    private V value;

    public NestedMap() {
        child = new HashMap<>();
        value = null;
    }

    public boolean hasChild(K k) {
        return this.child.containsKey(k);
    }

    public NestedMap<K, V> getChild(K k) {
        return this.child.get(k);
    }

    public void makeChild(K k) {
        this.child.put(k, new NestedMap());
    }

    public V getValue() {
        return value;
    }

    public void setValue(V v) {
        value = v;
    }
}

and example usage:

class NestedMapIllustration {
    public static void main(String[] args) {

        NestedMap<Character, String> m = new NestedMap<>();

        m.makeChild('f');
        m.getChild('f').makeChild('o');
        m.getChild('f').getChild('o').makeChild('o');
        m.getChild('f').getChild('o').getChild('o').setValue("bar");

        System.out.println(
            "nested element at 'f' -> 'o' -> 'o' is " +
            m.getChild('f').getChild('o').getChild('o').getValue());
    }
}

Inserting image into IPython notebook markdown

If you want to display the image in a Markdown cell then use:

<img src="files/image.png" width="800" height="400">

If you want to display the image in a Code cell then use:

from IPython.display import Image
Image(filename='output1.png',width=800, height=400)

How to write multiple conditions of if-statement in Robot Framework

Just make sure put single space before and after "and" Keyword..

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

jquery change class name

You can do This : $("#td_id").removeClass('Old_class'); $("#td_id").addClass('New_class'); Or You can do This

$("#td_id").removeClass('Old_class').addClass('New_class');

Can I set background image and opacity in the same property?

I saw this and in CSS3 you can now place code in like this. Lets say I want it to cover the whole background I would do something like this. Then with hsla(0,0%,100%,0.70) or rgba you use a white background with whatever percentage saturation or opacity to get the look you desire.

.body{
    background-attachment: fixed;
    background-image: url(../images/Store1.jpeg);
    display: block;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 1;
    background-color: hsla(0,0%,100%,0.70);
    background-blend-mode: overlay;
    background-repeat: no-repeat;
}

How do I add button on each row in datatable?

my recipe:

datatable declaration:

defaultContent: "<button type='button'....

events:

$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }

Best way to concatenate List of String objects?

Assuming it's faster to just move a pointer / set a byte to null (or however Java implements StringBuilder#setLength), rather than check a condition each time through the loop to see when to append the delimiter, you could use this method:

public static String Intersperse (Collection<?> collection, String delimiter)
{
    StringBuilder sb = new StringBuilder ();
    for (Object item : collection)
    {
        if (item == null) continue;
        sb.append (item).append (delimiter);
    }
    sb.setLength (sb.length () - delimiter.length ());
    return sb.toString ();
}

Swipe ListView item From right to left show delete button

I just got his working using the ViewSwitcher in a ListItem.

list_item.xml:

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

<ViewSwitcher
    android:id="@+id/list_switcher"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:inAnimation="@android:anim/slide_in_left"
    android:outAnimation="@android:anim/slide_out_right"
    android:measureAllChildren="false" >
    <TextView
        android:id="@+id/tv_item_name"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:maxHeight="50dp"
        android:paddingLeft="10dp" />

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:clickable="false"
        android:gravity="center"
        >

    <Button
        android:id="@+id/b_edit_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"

         />
    <Button
        android:id="@+id/b_delete_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:background="@android:color/holo_red_dark"
        />
    </LinearLayout>
</ViewSwitcher>

In the ListAdapter: Implement OnclickListeners for the Edit and Delete button in the getView() method. The catch here is to get the position of the ListItem clicked inside the onClick methods. setTag() and getTag() methods are used for this.

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.list_item, null);
        viewHolder.viewSwitcher=(ViewSwitcher)convertView.findViewById(R.id.list_switcher);
        viewHolder.itemName = (TextView) convertView
                .findViewById(R.id.tv_item_name);
        viewHolder.deleteitem=(Button)convertView.findViewById(R.id.b_delete_in_list);
        viewHolder.deleteItem.setTag(position);
        viewHolder.editItem=(Button)convertView.findViewById(R.id.b_edit_in_list);
        viewHolder.editItem.setTag(position);
        viewHolder.deleteItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.deleteItemList((Integer)v.getTag());
            }
        });

        viewHolder.editItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.editItemList(position);
            }
        });
        convertView.setTag(viewHolder);
} else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.itemName.setText(itemlist[position]);
return convertView;  
}

In the Fragment, Add a Gesture Listener to detect the Fling Gesture:

public class MyGestureListener extends SimpleOnGestureListener {
    private ListView list;

    public MyGestureListener(ListView list) {
        this.list = list;
    }

    // CONDITIONS ARE TYPICALLY VELOCITY OR DISTANCE

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        // if (INSERT_CONDITIONS_HERE)

        ltor=(e2.getX()-e1.getX()>DELTA_X);
        if (showDeleteButton(e1))
        {
            return true;
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
        // TODO Auto-generated method stub
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    private boolean showDeleteButton(MotionEvent e1) {
        int pos = list.pointToPosition((int) e1.getX(), (int) e1.getY());
        return showDeleteButton(pos);
    }

    private boolean showDeleteButton(int pos) {

        View child = list.getChildAt(pos);
        if (child != null) {
            Button delete = (Button) child
                    .findViewById(R.id.b_edit_in_list);
            ViewSwitcher viewSwitcher = (ViewSwitcher) child
                    .findViewById(R.id.host_list_switcher);
            TextView hostName = (TextView) child
                    .findViewById(R.id.tv_host_name);
            if (delete != null) {
                    viewSwitcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_left));
                    viewSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_right));
                }

                viewSwitcher.showNext();
                // frameLayout.setVisibility(View.VISIBLE);
            }
            return true;
        }
        return false;
    }
}

In the onCreateView method of the Fragment,

GestureDetector gestureDetector = new GestureDetector(getActivity(),
            new MyGestureListener(hostList));
    hostList.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }

        }
    });

This worked for me. Should refine it more.

Twitter Bootstrap: Print content of modal window

_x000D_
_x000D_
@media print{_x000D_
 body{_x000D_
  visibility: hidden; /* no print*/_x000D_
 }_x000D_
 .print{_x000D_
  _x000D_
  visibility:visible; /*print*/_x000D_
 }_x000D_
}
_x000D_
<body>_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="print">   <!---print--->_x000D_
  <div class="print">   <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to Check if value exists in a MySQL database

This works for me :


$db = mysqli_connect('localhost', 'UserName', 'Password', 'DB_Name') or die('Not Connected');
mysqli_set_charset($db, 'utf8');

$sql = mysqli_query($db,"SELECT * FROM `mytable` WHERE city='c7'");
$sql = mysqli_fetch_assoc($sql);
$Checker = $sql['city'];

if  ($Checker != null) {
    
    echo 'Already exists';
    
} else {

    echo 'Not found';
}

Can I append an array to 'formdata' in javascript?

var formData = new FormData;
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
    formData.append('listOfAlphabet', alphaArray [i]);
}

And In your request you will get array of alphabets.

JQuery DatePicker ReadOnly

I set the following beforeShow event handler (in the options parameter) to achieve this functionality.

beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }

getting the ng-object selected with ng-change

<select ng-model="item.size.code">
<option ng-repeat="size in sizes" ng-attr-value="size.code">{{size.name}}          </option>
</select>

What's the difference between event.stopPropagation and event.preventDefault?

return false;


return false; does 3 separate things when you call it:

  1. event.preventDefault() – It stops the browsers default behaviour.
  2. event.stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
  3. Stops callback execution and returns immediately when called.

Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

preventDefault();


preventDefault(); does one thing: It stops the browsers default behaviour.

When to use them?


We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault(); if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault().

Examples:


Let’s try to understand with examples:

We will see pure JAVASCRIPT example

Example 1:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked and immediately you will be redirected to stackoverflow.com.

Example 2:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.preventDefault();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click action to be triggered.

Example 3:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.stopPropagation();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

This time if you click on Link the function executeParent() will not be called and you will not get the javascript alert div Clicked this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to stackoverflow.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.

Example 4:

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.

Example 5:

For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.

cases:

  1. Returning false from an inline event handler prevents the browser from navigating to the link address, but it doesn't stop the event from propagating through the DOM.
  2. Returning false from a jQuery event handler prevents the browser from navigating to the link address and it stops the event from propagating through the DOM.
  3. Returning false from a regular DOM event handler does absolutely nothing.

Will see all three example.

  1. Inline return false.

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  var link = document.querySelector('a');_x000D_
_x000D_
  link.addEventListener('click', function() {_x000D_
    event.currentTarget.innerHTML = 'Click event prevented using inline html'_x000D_
    alert('Link Clicked');_x000D_
  });_x000D_
_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

  1. Returning false from a jQuery event handler.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
  <a href='https://stackoverflow.com'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  $('a').click(function(event) {_x000D_
    alert('Link Clicked');_x000D_
    $('a').text('Click event prevented using return FALSE');_x000D_
    $('a').contents().unwrap();_x000D_
    return false;_x000D_
  });_x000D_
  $('div').click(function(event) {_x000D_
    alert('Div clicked');_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

  1. Returning false from a regular DOM event handler.

_x000D_
_x000D_
<div onclick='executeParent()'>_x000D_
  <a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
  function executeChild() {_x000D_
    event.currentTarget.innerHTML = 'Click event prevented'_x000D_
    alert('Link Clicked');_x000D_
    return false_x000D_
  }_x000D_
_x000D_
  function executeParent() {_x000D_
    alert('Div Clicked');_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

Hope these examples are clear. Try executing all these examples in a html file to see how they work.

How to open the Chrome Developer Tools in a new window?

As of Chrome 52, the UI has changed. When the Developer Tools dialog is open, you select the vertical ellipsis and can then choose the docking position:

enter image description here

Select the icon on the left to open the Chrome Developer Tools in a new window: multiple windows icon


Previously

Click and hold the button next to the close button of the Developer Tool in order to reveal the "Undock into separate window" option.

enter image description here

Note: A "press" is not enough in that state.

How to display Toast in Android?

If you want to write a simple toast in your activity: Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

1.Showing TextView in Toast:---

TextView tv = new TextView(this); tv.setText("Hello!"); tv.setTextSize(30); tv.setTextColor(Color.RED); tv.setBackgroundColor(Color.YELLOW);

2.Showing Image as Toast:--

ImageView iv = new ImageView(this); iv.setImageResource(R.drawable.blonde); Toast t = new Toast(this); t.setView(iv); t.setDuration(Toast.LENGTH_LONG); t.show();

3.showing Layout as Toast:--

LayoutInflater li = getLayoutInflater(); View view = li.inflate(R.layout.my_toast_layout,null,false); Toast t = new Toast(this); t.setView(view); t.setDuration(Toast.LENGTH_LONG); t.show();

** If you want to write the toast in your Async then: private Activity activity; private android.content.Context context; this.activity = activity; this.context = context; Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
..
..
handleClose = () => {
}

return (
    <SnackBar
        open={open}
        handleClose={() => handleClose}
        variant={variant}
        message={message}
        />
    <SignInForm/>
)

}

Sql query to insert datetime in SQL Server

No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:

select * from table1 where somedate between '2000/01/01' and '2099/12/31'

The separator needs to be a / and it needs to be surrounded by single ' quotes.

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Two ways to do it...

GROUP BY

SELECT RES.[CUSTOMER ID], RES,NAME, SUM(INV.AMOUNT) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]
GROUP BY RES.[CUSTOMER ID], RES,NAME

OVER

SELECT RES.[CUSTOMER ID], RES,NAME, 
       SUM(INV.AMOUNT) OVER (PARTITION RES.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA RES
JOIN INV_DATA INV ON RES.[CUSTOMER ID] INV.[CUSTOMER ID]

How to create a bash script to check the SSH connection?

ssh -q -o "BatchMode=yes" -i /home/sicmapp/.ssh/id_rsa <ID>@<Servername>.<domain> "echo 2>&1" && echo $host SSH_OK || echo $host SSH_NOK

'Incomplete final line' warning when trying to read a .csv file into R

I have solved this problem with changing encoding in read.table argument from fileEncoding = "UTF-16" to fileEncoding = "UTF-8".

'ssh-keygen' is not recognized as an internal or external command

Search your git directory if you already install git

Use git bash should be on your C:\Program Files\Git\bin depend on your installation location

If you already add the path just run sh on your cmd or open sh.exe

type ssh-keygen

Then just insert name and passphrase (You can just type empty string).

Using iText to convert HTML to PDF

I think this is exactly what you were looking for

http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

http://code.google.com/p/flying-saucer

Flying Saucer's primary purpose is to render spec-compliant XHTML and CSS 2.1 to the screen as a Swing component. Though it was originally intended for embedding markup into desktop applications (things like the iTunes Music Store), Flying Saucer has been extended work with iText as well. This makes it very easy to render XHTML to PDFs, as well as to images and to the screen. Flying Saucer requires Java 1.4 or higher.

How can you detect the version of a browser?

Here is the java version for somemone who whould like to do it on server side using the String returned by HttpServletRequest.getHeader("User-Agent");

It is working on the 70 different browser configuration I used for testing.

public static String decodeBrowser(String userAgent) {
    userAgent= userAgent.toLowerCase();
    String name = "unknown";
    String version = "0.0";
    Matcher userAgentMatcher = USER_AGENT_MATCHING_PATTERN.matcher(userAgent);
    if (userAgentMatcher.find()) {
      name = userAgentMatcher.group(1);
      version = userAgentMatcher.group(2);
      if ("trident".equals(name)) {
        name = "msie";
        Matcher tridentVersionMatcher = TRIDENT_MATCHING_PATTERN.matcher(userAgent);
        if (tridentVersionMatcher.find()) {
          version = tridentVersionMatcher.group(1);
        }
      }
    }
    return name + " " + version;
  }

  private static final Pattern USER_AGENT_MATCHING_PATTERN=Pattern.compile("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*([\\d\\.]+)");
  private static final Pattern TRIDENT_MATCHING_PATTERN=Pattern.compile("\\brv[ :]+(\\d+(\\.\\d+)?)");

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

Adding http://minifiedjs.com/ to the list of answers :)

Code is similar to underscore and others:

var l123 = _.range(1, 4);      // same as _(1, 2, 3)
var l0123 = _.range(3);        // same as _(0, 1, 2)
var neg123 = _.range(-3, 0);   // same as _(-3, -2, -1)
var empty = _.range(2,1);      // same as _()

Docs here: http://minifiedjs.com/api/range.html

I use minified.js because it solves all my problems with low footprint and easy to understand syntax. For me, it is a replacement for jQuery, MustacheJS and Underscore/SugarJS in one framework.

Of course, it is not that popular as underscore. This might be a concern for some.

Minified was made available by Tim Jansen using the CC-0 (public domain) license.

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

SQL Server Management Studio missing

Try restarting your computer if you just installed SQL Server and there's no choice in the SQL Server Installation Center to install SQL Server Management Studio.

This choice (see image below) only appeared for me after I installed SQL Server, then restarted my computer:

enter image description here

How do I check if file exists in Makefile so I can delete it?

test ! -f README.md || echo 'Support OpenSource!' >> README.md

"If README.md does not exist, do nothing (and exit successfully). Otherwise, append text to the end."

If you use && instead of || then you generate an error when the file doesn't exist:

Makefile:42: recipe for target 'dostuff' failed
make: *** [dostuff] Error 1

Best way to get hostname with php

What about gethostname()?

Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

How to print bytes in hexadecimal using System.out.println?

byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;

for (byte theByte : test)
{
  System.out.println(Integer.toHexString(theByte));
}

NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.

you might be able to do...

test[1] = (byte) 0xFF;

I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)

How to print a query string with parameter values when using Hibernate

Using Hibernate 4 and slf4j/log4j2 , I tried adding the following in my log4j2.xml configuration :

<Logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace" additivity="false"> 
    <AppenderRef ref="Console"/> 
</Logger> 
<Logger name="org.hibernate.type.EnumType" level="trace" additivity="false"> 
    <AppenderRef ref="Console"/>
</Logger>

But without success.

I found out through this thread that the jboss-logging framework used by hibernate needed to be configured in order to log through slf4j. I added the following argument to the VM arguments of the application:

-Dorg.jboss.logging.provider=slf4j

And it worked like a charm.

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How to set socket timeout in C when making multiple connections?

am not sure if I fully understand the issue, but guess it's related to the one I had, am using Qt with TCP socket communication, all non-blocking, both Windows and Linux..

wanted to get a quick notification when an already connected client failed or completely disappeared, and not waiting the default 900+ seconds until the disconnect signal got raised. The trick to get this working was to set the TCP_USER_TIMEOUT socket option of the SOL_TCP layer to the required value, given in milliseconds.

this is a comparably new option, pls see http://tools.ietf.org/html/rfc5482, but apparently it's working fine, tried it with WinXP, Win7/x64 and Kubuntu 12.04/x64, my choice of 10 s turned out to be a bit longer, but much better than anything else I've tried before ;-)

the only issue I came across was to find the proper includes, as apparently this isn't added to the standard socket includes (yet..), so finally I defined them myself as follows:

#ifdef WIN32
    #include <winsock2.h>
#else
    #include <sys/socket.h>
#endif

#ifndef SOL_TCP
    #define SOL_TCP 6  // socket options TCP level
#endif
#ifndef TCP_USER_TIMEOUT
    #define TCP_USER_TIMEOUT 18  // how long for loss retry before timeout [ms]
#endif

setting this socket option only works when the client is already connected, the lines of code look like:

int timeout = 10000;  // user timeout in milliseconds [ms]
setsockopt (fd, SOL_TCP, TCP_USER_TIMEOUT, (char*) &timeout, sizeof (timeout));

and the failure of an initial connect is caught by a timer started when calling connect(), as there will be no signal of Qt for this, the connect signal will no be raised, as there will be no connection, and the disconnect signal will also not be raised, as there hasn't been a connection yet..

how to get login option for phpmyadmin in xampp

If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").

fail to change placeholder color with Bootstrap 3

You should check out this answer : Change an HTML5 input's placeholder color with CSS

Work on most browser, the solution in this thread is not working on FF 30+ for example

Generating random whole numbers in JavaScript in a specific range?

Crypto-Strong

To get crypto-strong random integer number in ragne [x,y] try

_x000D_
_x000D_
let cs= (x,y)=>x+(y-x+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0_x000D_
_x000D_
console.log(cs(4,8))
_x000D_
_x000D_
_x000D_

Determine if Android app is being used for the first time

for kotlin

    fun checkFirstRun() {

    var prefs_name = "MyPrefsFile"
    var pref_version_code_key = "version_code"
    var doesnt_exist: Int = -1;

    // Get current version code
    var currentVersionCode = BuildConfig.VERSION_CODE

    // Get saved version code
    var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
    var savedVersionCode: Int = prefs.getInt(pref_version_code_key, doesnt_exist)

    // Check for first run or upgrade
    if (currentVersionCode == savedVersionCode) {

        // This is just a normal run
        return;

    } else if (savedVersionCode == doesnt_exist) {

        // TODO This is a new install (or the user cleared the shared preferences)


    } else if (currentVersionCode > savedVersionCode) {

        // TODO This is an upgrade
    }

    // Update the shared preferences with the current version code
    prefs.edit().putInt(pref_version_code_key, currentVersionCode).apply();

}

Change status bar text color to light in iOS 9 with Objective-C

iOS Status bar has only 2 options (black and white). You can try this in AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
}

Find the item with maximum occurrences in a list

I obtained the best results with groupby from itertools module with this function using Python 3.5.2:

from itertools import groupby

a = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]

def occurrence():
    occurrence, num_times = 0, 0
    for key, values in groupby(a, lambda x : x):
        val = len(list(values))
        if val >= occurrence:
            occurrence, num_times =  key, val
    return occurrence, num_times

occurrence, num_times = occurrence()
print("%d occurred %d times which is the highest number of times" % (occurrence, num_times))

Output:

4 occurred 6 times which is the highest number of times

Test with timeit from timeit module.

I used this script for my test with number= 20000:

from itertools import groupby

def occurrence():
    a = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
    occurrence, num_times = 0, 0
    for key, values in groupby(a, lambda x : x):
        val = len(list(values))
        if val >= occurrence:
            occurrence, num_times =  key, val
    return occurrence, num_times

if __name__ == '__main__':
    from timeit import timeit
    print(timeit("occurrence()", setup = "from __main__ import occurrence",  number = 20000))

Output (The best one):

0.1893607140000313

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("http://www.website.com");
    }

Reference - https://blogs.msdn.microsoft.com/rickandy/2012/03/01/response-redirect-and-asp-net-mvc-do-not-mix/

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Only for .NET Core Web API project, add following changes:

  1. Add the following code after the services.AddMvc() line in the ConfigureServices() method of the Startup.cs file:
services.AddCors(allowsites=>{allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
  1. Add the following code after app.UseMvc() line in the Configure() method of the Startup.cs file:
app.UseCors(options => options.AllowAnyOrigin());
  1. Open the controller which you want to access outside the domain and add this following attribute at the controller level:
[EnableCors("AllowOrigin")]

What are all the escape characters?

Java Escape Sequences:

\u{0000-FFFF}  /* Unicode [Basic Multilingual Plane only, see below] hex value 
                  does not handle unicode values higher than 0xFFFF (65535),
                  the high surrogate has to be separate: \uD852\uDF62
                  Four hex characters only (no variable width) */
\b             /* \u0008: backspace (BS) */
\t             /* \u0009: horizontal tab (HT) */
\n             /* \u000a: linefeed (LF) */
\f             /* \u000c: form feed (FF) */
\r             /* \u000d: carriage return (CR) */
\"             /* \u0022: double quote (") */
\'             /* \u0027: single quote (') */
\\             /* \u005c: backslash (\) */
\{0-377}       /* \u0000 to \u00ff: from octal value 
                  1 to 3 octal digits (variable width) */

The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F / &#77887; and would have to be broken into "\uD80C\uDC3F" (UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F".

Remove a parameter to the URL with JavaScript

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

The var alteredURL will be the output you desire.

Hope it helps!

Fit website background image to screen size

Although there are answers to this your questions but because I was once a victim of this problem and after few search online i was unable to solve it but my fellow hub mate helped me and i feel i should share. Examples explained below.

Folders: web-projects/project1/imgs-journey.png

background-image:url(../imgs/journey.png);
background-repeat:no-repeat;
background-size:cover;

My major points is the dots there if you noticed my journey.png is located inside an imgs folder of another folder so you're to add the dot according to the numbers folders where your image is stored. In my case my journey.png image is saved in two folders that's why two dot is used, so i think this may be the problem of background images not showing sometimes in our codes. Thanks.

EventListener Enter Key

Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

How to uninstall mini conda? python

To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.

Encoding URL query parameters in Java

EDIT: URIUtil is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.


URIUtil of Apache httpclient is really useful, although there are some alternatives

URIUtil.encodeQuery(url);

For example, it encodes space as "+" instead of "%20"

Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.

What is the difference between the kernel space and the user space?

Memory get's divided into two distinct areas:

  • The user space, which is a set of locations where normal user processes run (i.e everything other than the kernel). The role of the kernel is to manage applications running in this space from messing with each other, and the machine.
  • The kernel space, which is the location where the code of the kernel is stored, and executes under.

Processes running under the user space have access only to a limited part of memory, whereas the kernel has access to all of the memory. Processes running in user space also don't have access to the kernel space. User space processes can only access a small part of the kernel via an interface exposed by the kernel - the system calls.If a process performs a system call, a software interrupt is sent to the kernel, which then dispatches the appropriate interrupt handler and continues its work after the handler has finished.

I'm trying to use python in powershell

To be able to use Python immediately without restarting the shell window you need to change the path for the machine, the process and the user.

Function Get-EnvVariableNameList {
    [cmdletbinding()]
    $allEnvVars = Get-ChildItem Env:
    $allEnvNamesArray = $allEnvVars.Name
    $pathEnvNamesList = New-Object System.Collections.ArrayList
    $pathEnvNamesList.AddRange($allEnvNamesArray)
    return ,$pathEnvNamesList
}

Function Add-EnvVarIfNotPresent {
Param (
[string]$variableNameToAdd,
[string]$variableValueToAdd
   ) 
    $nameList = Get-EnvVariableNameList
    $alreadyPresentCount = ($nameList | Where{$_ -like $variableNameToAdd}).Count
    #$message = ''
    if ($alreadyPresentCount -eq 0)
    {
    [System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::Machine)
    [System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::Process)
    [System.Environment]::SetEnvironmentVariable($variableNameToAdd, $variableValueToAdd, [System.EnvironmentVariableTarget]::User)
        $message = "Enviromental variable added to machine, process and user to include $variableNameToAdd"
    }
    else
    {
        $message = 'Environmental variable already exists. Consider using a different function to modify it'
    }
    Write-Information $message
}


Function Get-EnvExtensionList {
    $pathExtArray =  ($env:PATHEXT).Split("{;}")
    $pathExtList = New-Object System.Collections.ArrayList
    $pathExtList.AddRange($pathExtArray)
    return ,$pathExtList
}


Function Add-EnvExtension {
Param (
[string]$pathExtToAdd
   ) 
    $pathList = Get-EnvExtensionList
    $alreadyPresentCount = ($pathList | Where{$_ -like $pathToAdd}).Count
    if ($alreadyPresentCount -eq 0)
    {
        $pathList.Add($pathExtToAdd)
        $returnPath = $pathList -join ";"
        [System.Environment]::SetEnvironmentVariable('pathext', $returnPath, [System.EnvironmentVariableTarget]::Machine)
        [System.Environment]::SetEnvironmentVariable('pathext', $returnPath, [System.EnvironmentVariableTarget]::Process)
        [System.Environment]::SetEnvironmentVariable('pathext', $returnPath, [System.EnvironmentVariableTarget]::User)
        $message = "Path extension added to machine, process and user paths to include $pathExtToAdd"
    }
    else
    {
        $message = 'Path extension already exists'
    }
    Write-Information $message
}

Function Get-EnvPathList {
    [cmdletbinding()]
    $pathArray =  ($env:PATH).Split("{;}")
    $pathList = New-Object System.Collections.ArrayList
    $pathList.AddRange($pathArray)
    return ,$pathList
}

Function Add-EnvPath {
Param (
[string]$pathToAdd
   ) 
    $pathList = Get-EnvPathList
    $alreadyPresentCount = ($pathList | Where{$_ -like $pathToAdd}).Count
    if ($alreadyPresentCount -eq 0)
    {
        $pathList.Add($pathToAdd)
        $returnPath = $pathList -join ";"
        [System.Environment]::SetEnvironmentVariable('path', $returnPath, [System.EnvironmentVariableTarget]::Machine)
        [System.Environment]::SetEnvironmentVariable('path', $returnPath, [System.EnvironmentVariableTarget]::Process)
        [System.Environment]::SetEnvironmentVariable('path', $returnPath, [System.EnvironmentVariableTarget]::User)
        $message = "Path added to machine, process and user paths to include $pathToAdd"
    }
    else
    {
        $message = 'Path already exists'
    }
    Write-Information $message
}

Add-EnvExtension '.PY'
Add-EnvExtension '.PYW'
Add-EnvPath 'C:\Python27\'

Bash write to file without echo?

I had the problem not being able to send ">" and ended up with echo!

echo "Hello world" | dd of=test.txt

How can I echo a newline in a batch file?

Like the answer of Ken, but with the use of the delayed expansion.

setlocal EnableDelayedExpansion
(set \n=^
%=Do not remove this line=%
)

echo Line1!\n!Line2
echo Works also with quotes "!\n!line2"

First a single linefeed character is created and assigned to the \n-variable.
This works as the caret at the line end tries to escape the next character, but if this is a Linefeed it is ignored and the next character is read and escaped (even if this is also a linefeed).
Then you need a third linefeed to end the current instruction, else the third line would be appended to the LF-variable.
Even batch files have line endings with CR/LF only the LF are important, as the CR's are removed in this phase of the parser.

The advantage of using the delayed expansion is, that there is no special character handling at all.
echo Line1%LF%Line2 would fail, as the parser stops parsing at single linefeeds.

More explanations are at
SO:Long commands split over multiple lines in Vista/DOS batch (.bat) file
SO:How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Edit: Avoid echo.

This doesn't answer the question, as the question was about single echo that can output multiple lines.

But despite the other answers who suggests the use of echo. to create a new line, it should be noted that echo. is the worst, as it's very slow and it can completly fail, as cmd.exe searches for a file named ECHO and try to start it.

For printing just an empty line, you could use one of

echo,
echo;
echo(
echo/
echo+
echo=

But the use of echo., echo\ or echo: should be avoided, as they can be really slow, depending of the location where the script will be executed, like a network drive.

How do I parse a string to a float or int?

Localization and commas

You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.

Example 1 -- United States number conventions

In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

Example 2 -- European number conventions

In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

The method locale.atoi is also available, but the argument should be an integer.

How to execute only one test spec with angular-cli

Configure test.ts file inside src folder:

const context = require.context('./', true, /\.spec\.ts$/);

Replace /\.spec\.ts$/ with the file name you want to test. For example: /app.component\.spec\.ts$/

This will run test only for app.component.spec.ts.

html "data-" attribute as javascript parameter

If you are using jQuery you can easily fetch the data attributes by

$(this).data("id") or $(event.target).data("id")

How can I escape a single quote?

Probably the easiest way:

<input type='text' id='abc' value="hel'lo">

Spring,Request method 'POST' not supported

You are missimg @ModelAttribute annotation for UserProfessionalForm professionalForm parameter in forgotPassword method.

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String forgotPassword(@ModelAttribute UserProfessionalForm professionalForm,
        BindingResult result, Model model) {

    UserProfileVO userProfileVO = new UserProfileVO();
    userProfileVO.setUser(sessionData.getUser());
    userService.saveUserProfile(userProfileVO);
    model.addAttribute("professional", professionalForm);
    return "Your Professional Details Updated";
}

HTML select dropdown list

Try this:

_x000D_
_x000D_
<select>_x000D_
    <option value="" disabled="disabled" selected="selected">Please select a name</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

When the page loads, this option will be selected by default. However, as soon as the drop-down is clicked, the user won't be able to re-select this option.

Hope this helps.

How to get the difference (only additions) between two files in linux

A similar approach to https://stackoverflow.com/a/15385080/337172 but hopefully more understandable and easy to tweak:

diff \
  --new-line-format="%L" \
  --old-line-format="" \
  --unchanged-line-format="" \
  A1 A2

Can we create an instance of an interface in Java?

Yes it is correct. you can do it with an inner class.

How to check if a MySQL query using the legacy API was successful?

if using MySQLi bind_param try to put this line above the query

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

How to use router.navigateByUrl and router.navigate in Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

/**
 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 *
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 *
 * ### Usage
 *
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 *
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 *
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.
 */

The Router Guide has more details on programmatic navigation.

Django template how to look up a dictionary value with a variable

env: django 2.1.7

view:

dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})

template:

{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

Babel 6 regeneratorRuntime is not defined

I had this problem in Chrome. Similar to RienNeVaPlu?s’s answer, this solved it for me:

npm install --save-dev regenerator-runtime

Then in my code:

import 'regenerator-runtime/runtime';

Happy to avoid the extra 200 kB from babel-polyfill.

How to create a new database after initally installing oracle database 11g Express Edition?

When you installed XE.... it automatically created a database called "XE". You can use your login "system" and password that you set to login.

Key info

server: (you defined)
port: 1521
database: XE
username: system
password: (you defined)

Also Oracle is being difficult and not telling you easily create another database. You have to use SQL or another tool to create more database besides "XE".

Using jq to parse and display multiple fields in a json serially

This will produce an array of names

> jq '[ .users[] | (.first + " " + .last) ]' ~/test.json

[
  "Stevie Wonder",
  "Michael Jackson"
]

Staging Deleted files

Since Git 2.0.0, git add will also stage file deletions.

Git 2.0.0 Docs - git-add

< pathspec >…

Files to add content from. Fileglobs (e.g. *.c) can be given to add all matching files. Also a leading directory name (e.g. dir to add dir/file1 and dir/file2) can be given to update the index to match the current state of the directory as a whole (e.g. specifying dir will record not just a file dir/file1 modified in the working tree, a file dir/file2 added to the working tree, but also a file dir/file3 removed from the working tree. Note that older versions of Git used to ignore removed files; use --no-all option if you want to add modified or new files but ignore removed ones.

Formatting PowerShell Get-Date inside string

You can use the -f operator

$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)

Spécificator    Type                                Example (with [datetime]::now)
d   Short date                                        26/09/2002
D   Long date                                       jeudi 26 septembre 2002
t   Short Hour                                      16:49
T   Long Hour                                       16:49:31
f   Date and hour                                   jeudi 26 septembre 2002 16:50
F   Long Date and hour                              jeudi 26 septembre 2002 16:50:51
g   Default Date                                    26/09/2002 16:52
G   Long default Date and hour                      26/09/2009 16:52:12
M   Month Symbol                                    26 septembre
r   Date string RFC1123                             Sat, 26 Sep 2009 16:54:50 GMT
s   Sortable string date                            2009-09-26T16:55:58
u   Sortable string date universal local hour       2009-09-26 16:56:49Z
U   Sortable string date universal GMT hour         samedi 26 septembre 2009 14:57:22 (oups)
Y   Year symbol                                     septembre 2002

Spécificator    Type                       Example      Output Example
dd              Jour                       {0:dd}       10
ddd             Name of the day            {0:ddd}      Jeu.
dddd            Complet name of the day    {0:dddd}     Jeudi
f, ff, …        Fractions of seconds       {0:fff}      932
gg, …           position                   {0:gg}       ap. J.-C.
hh              Hour two digits            {0:hh}       10
HH              Hour two digits (24 hours) {0:HH}       22
mm              Minuts 00-59               {0:mm}       38
MM              Month 01-12                {0:MM}       12
MMM             Month shortcut             {0:MMM}      Sep.
MMMM            complet name of the month  {0:MMMM}     Septembre
ss              Seconds 00-59              {0:ss}       46
tt              AM or PM                   {0:tt}       ““
yy              Years, 2 digits            {0:yy}       02
yyyy            Years                      {0:yyyy}     2002
zz              Time zone, 2 digits        {0:zz}       +02
zzz             Complete Time zone         {0:zzz}      +02:00
:               Separator                  {0:hh:mm:ss}     10:43:20
/               Separator                  {0:dd/MM/yyyy}   10/12/2002

Excel CSV - Number cell format

You can simply format your range as Text.

Also here is a nice article on the number formats and how you can program them.

PHP is_numeric or preg_match 0-9 validation

is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

[EDIT]

As per your comment, a better regular expression might look like this:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

You're not worried about negatives, so that's not an issue.

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

Hope that helps.

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

Thank you, user374559 and reneD -- that code and description is very helpful.

My stab at some Python to parse and print out the information in a Unix ls-l like format:

#!/usr/bin/env python
import sys

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
    return mbdb

def process_mbdx_file(filename):
    mbdx = {} # Map offset of info in the MBDB file => fileID string
    data = open(filename).read()
    if data[0:4] != "mbdx": raise Exception("This does not look like an MBDX file")
    offset = 4
    offset = offset + 2 # value 0x02 0x00, not sure what this is
    filecount, offset = getint(data, offset, 4) # 4-byte count of records 
    while offset < len(data):
        # 26 byte record, made up of ...
        fileID = data[offset:offset+20] # 20 bytes of fileID
        fileID_string = ''.join(['%02x' % ord(b) for b in fileID])
        offset = offset + 20
        mbdb_offset, offset = getint(data, offset, 4) # 4-byte offset field
        mbdb_offset = mbdb_offset + 6 # Add 6 to get past prolog
        mode, offset = getint(data, offset, 2) # 2-byte mode field
        mbdx[mbdb_offset] = fileID_string
    return mbdx

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

Map over object preserving keys

With Underscore

Underscore provides a function _.mapObject to map the values and preserve the keys.

_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO


With Lodash

Lodash provides a function _.mapValues to map the values and preserve the keys.

_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

JavaScript - Getting HTML form values

HTML:

<input type="text" name="name" id="uniqueID" value="value" />

JS:

var nameValue = document.getElementById("uniqueID").value;

Easy way to use variables of enum types as string in C?

If you are using gcc, it's possible to use:

const char * enum_to_string_map[]={ [enum1]='string1', [enum2]='string2'};

Then just call for instance

enum_to_string_map[enum1]

How to call codeigniter controller function from view

views cannot call controller functions.

MongoDB via Mongoose JS - What is findByID?

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

Initialising an array of fixed size in python

You can use:

>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]

jQuery - Redirect with post data

I included the jquery.redirect.min.js plugin in the head section together with this json solution to submit with data

<script type="text/javascript">     
    $(function () {
     $('form').on('submit', function(e) {
       $.ajax({
        type: 'post',
        url: 'your_POST_URL',
        data: $('form').serialize(),
        success: function () {
         // now redirect
         $().redirect('your_POST_URL', {
          'input1': $("value1").val(), 
          'input2': $("value2").val(),
      'input3': $("value3").val()
       });
      }
   });
   e.preventDefault();
 });
 });
 </script>

Then immediately after the form I added

 $(function(){
     $( '#your_form_Id' ).submit();
    });

webpack: Module not found: Error: Can't resolve (with relative path)

Had the same issue with module not found. Turns out I had a component import Picture from './Picture/Picture'; at the very bottom of all the imports. When I moved it below import React, { Component } from 'react';, it worked.

Running a command as Administrator using PowerShell?

The most reliable way I've found is to wrap it in a self-elevating .bat file:

@echo off
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
CD %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
EXIT

:ADMINTASKS

powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"

EXIT

The .bat checks if you're already admin and relaunches the script as Administrator if needed. It also prevents extraneous "cmd" windows from opening with the 4th parameter of ShellExecute() set to 0.

Git - Ignore node_modules folder everywhere

Use the universal one-liner in terminal in the project directory:

touch .gitignore && echo "node_modules/" >> .gitignore && git rm -r --cached node_modules ; git status

It works no matter if you've created a .gitignore or not, no matter if you've added node_modules to git tracking or not.

Then commit and push the .gitignore changes.

Explanation

touch will generate the .gitignore file if it doesn't already exist.

echo and >> will append node_modules/ at the end of .gitignore, causing the node_modules folder and all subfolders to be ignored.

git rm -r --cached removes the node_modules folder from git control if it was added before. Otherwise, this will show a warning pathspec 'node_modules' did not match any files, which has no side effects and you can safely ignore. The flags cause the removal to be recursive and include the cache.

git status displays the new changes. A change to .gitignore will appear, while node_modules will not appear as it is no longer being tracked by git.

Referencing system.management.automation.dll in Visual Studio

I couldn't get the SDK to install properly (some of the files seemed unsigned, something like that). I found another solution here and that seems to work okay for me. It doesn't require installation of new files at all. Basically, what you do is:

Edit the .csproj file in a text editor, and add:

<Reference Include="System.Management.Automation" />

to the relevant section.

Hope this helps.

.NET code to send ZPL to Zebra printers

Take a look at this thread: Print ZPL codes to ZEBRA printer using PrintDocument class.

Specifically the OP pick this function from the answers to the thread:

[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);

private void Print()
{
    // Command to be sent to the printer
    string command = "^XA^FO10,10,^AO,30,20^FDFDTesting^FS^FO10,30^BY3^BCN,100,Y,N,N^FDTesting^FS^XZ";

    // Create a buffer with the command
    Byte[] buffer = new byte[command.Length];
    buffer = System.Text.Encoding.ASCII.GetBytes(command);
    // Use the CreateFile external func to connect to the LPT1 port
    SafeFileHandle printer = CreateFile("LPT1:", FileAccess.ReadWrite, 0, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
    // Aqui verifico se a impressora é válida
    if (printer.IsInvalid == true)
    {
        return;
    }

    // Open the filestream to the lpt1 port and send the command
    FileStream lpt1 = new FileStream(printer, FileAccess.ReadWrite);
    lpt1.Write(buffer, 0, buffer.Length);
    // Close the FileStream connection
    lpt1.Close();

}

jQuery - What are differences between $(document).ready and $(window).load?

The Difference between $(document).ready() and $(window).load() functions is that the code included inside $(window).load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

There are not difference between the above 3 codes.

They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

Regular expression for excluding special characters

Even in 2009, it seems too many had a very limited idea of what designing for the WORLDWIDE web involved. In 2015, unless designing for a specific country, a blacklist is the only way to accommodate the vast number of characters that may be valid.

The characters to blacklist then need to be chosen according what is illegal for the purpose for which the data is required.

However, sometimes it pays to break down the requirements, and handle each separately. Here look-ahead is your friend. These are sections bounded by (?=) for positive, and (?!) for negative, and effectively become AND blocks, because when the block is processed, if not failed, the regex processor will begin at the start of the text with the next block. Effectively, each look-ahead block will be preceded by the ^, and if its pattern is greedy, include up to the $. Even the ancient VB6/VBA (Office) 5.5 regex engine supports look-ahead.

So, to build up a full regular expression, start with the look-ahead blocks, then add the blacklisted character block before the final $.

For example, to limit the total numbers of characters, say between 3 and 15 inclusive, start with the positive look-ahead block (?=^.{3,15}$). Note that this needed its own ^ and $ to ensure that it covered all the text.

Now, while you might want to allow _ and -, you may not want to start or end with them, so add the two negative look-ahead blocks, (?!^[_-].+) for starts, and (?!.+[_-]$) for ends.

If you don't want multiple _ and -, add a negative look-ahead block of (?!.*[_-]{2,}). This will also exclude _- and -_ sequences.

If there are no more look-ahead blocks, then add the blacklist block before the $, such as [^<>[\]{\}|\\\/^~%# :;,$%?\0-\cZ]+, where the \0-\cZ excludes null and control characters, including NL (\n) and CR (\r). The final + ensures that all the text is greedily included.

Within the Unicode domain, there may well be other code-points or blocks that need to be excluded as well, but certainly a lot less than all the blocks that would have to be included in a whitelist.

The whole regex of all of the above would then be

(?=^.{3,15}$)(?!^[_-].+)(?!.+[_-]$)(?!.*[_-]{2,})[^<>[\]{}|\\\/^~%# :;,$%?\0-\cZ]+$

which you can check out live on https://regex101.com/, for pcre (php), javascript and python regex engines. I don't know where the java regex fits in those, but you may need to modify the regex to cater for its idiosyncrasies.

If you want to include spaces, but not _, just swap them every where in the regex.

The most useful application for this technique is for the pattern attribute for HTML input fields, where a single expression is required, returning a false for failure, thus making the field invalid, allowing input:invalid css to highlight it, and stopping the form being submitted.

How to return the current timestamp with Moment.js?

I would like to add that you can have the whole data information in an object with:

const today = moment().toObject();

You should obtain an object with this properties:

today: {
    date: 15,
    hours: 1,
    milliseconds: 927,
    minutes: 59,
    months: 4,
    seconds: 43,
    years: 2019
    }

It is very useful when you have to calculate dates.

Convert/cast an stdClass object to another class

Yet another approach.

The following is now possible thanks to the recent PHP 7 version.

$theStdClass = (object) [
  'a' => 'Alpha',
  'b' => 'Bravo',
  'c' => 'Charlie',
  'd' => 'Delta',
];

$foo = new class($theStdClass)  {
  public function __construct($data) {
    if (!is_array($data)) {
      $data = (array) $data;
    }

    foreach ($data as $prop => $value) {
      $this->{$prop} = $value;
    }
  }
  public function word4Letter($letter) {
    return $this->{$letter};
  }
};

print $foo->word4Letter('a') . PHP_EOL; // Alpha
print $foo->word4Letter('b') . PHP_EOL; // Bravo
print $foo->word4Letter('c') . PHP_EOL; // Charlie
print $foo->word4Letter('d') . PHP_EOL; // Delta
print $foo->word4Letter('e') . PHP_EOL; // PHP Notice:  Undefined property

In this example, $foo is being initialized as an anonymous class that takes one array or stdClass as only parameter for the constructor.

Eventually, we loop through the each items contained in the passed object and dynamically assign then to an object's property.

To make this approch event more generic, you can write an interface or a Trait that you will implement in any class where you want to be able to cast an stdClass.

Git keeps prompting me for a password

Microsoft Stack solution (Windows and Azure DevOps)

First open the .git/config file to make sure the address looks like:

protocol://something@url

E.g. .git/config for Azure DevOps:

[remote "origin"]
    url = https://[email protected]/mystore/myproject/
    fetch = +refs/heads/*:refs/remotes/origin/*

If the problem still persists, open Windows Credential Manager, click on the safebox named Windows Credentials and remove all the git related credentials.

Now the next time you log into git, it won't go away anymore.

What are the aspect ratios for all Android phone and tablet devices?

I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

  • 4:3
  • 3:2
  • 8:5
  • 5:3
  • 16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)


More complete answer here: stackoverflow community spreadsheet of Android device resolutions and DPIs

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

How to get access to HTTP header information in Spring MVC REST controller?

When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:

@RequestHeader("Accept")

to get the Accept header.

So from the documentation:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

The Accept-Encoding and Keep-Alive header values are provided in the encoding and keepAlive parameters respectively.

And no worries. We are all noobs with something.

Check if a string is a valid date using DateTime.TryParse

Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

When I was in a similar situation, here is what I did:

  1. Gather all the formats my system is expected to support.
  2. Looked at what is common or can be generalize.
  3. Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
  4. I created REGEX to cover as many format as possible.
  5. For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
  6. With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.

This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.

My 2 cents if it helps....

How to Add Incremental Numbers to a New Column Using Pandas

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

What are all the possible values for HTTP "Content-Type" header?

I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.

@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here.

How to determine MIME type of file in android?

File file = new File(path, name);

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    int index = file.getName().lastIndexOf('.')+1;
    String ext = file.getName().substring(index).toLowerCase();
    String type = mime.getMimeTypeFromExtension(ext);

    intent.setDataAndType(Uri.fromFile(file), type);
    try
    {
      context.startActivity(intent);
    }
    catch(ActivityNotFoundException ex)
    {
        ex.printStackTrace();

    }

http://localhost/phpMyAdmin/ unable to connect

Your web server isn't running! You need to find the XAMPP control panel and start the web server up.

Of course, you might find other problems after that, but this is the first step.

Truncate all tables in a MySQL database in one command?

No. There is no single command to truncate all mysql tables at once. You will have to create a small script to truncate the tables one by one.

ref: http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html

Python string prints as [u'String']

Do you really mean u'String'?

In any event, can't you just do str(string) to get a string rather than a unicode-string? (This should be different for Python 3, for which all strings are unicode.)

std::vector versus std::array in C++

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.

How to include a class in PHP

I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

How to change background color in the Notepad++ text editor?

There seems to have been an update some time in the past 3 years which changes the location of where to place themes in order to get them working.

Previosuly, themes were located in the Notepad++ installation folder. Now they are located in AppData:

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

My answer is an update to @Amit-IO's answer about manually copying the themes.

  1. In Explorer, browse to: %AppData%\Notepad++.
  2. If a folder called themes does not exist, create it.
  3. Download your favourite theme from wherever (see Amit-IO's answer for a good list) and save it to %AppData%\Notepad++\themes.
  4. Restart Notepad++ and then use Settings -> Style Configurator. The new theme(s) will appear in the list.

How can I convert a .jar to an .exe?

Despite this being against the general SO policy on these matters, this seems to be what the OP genuinely wants:

http://www.google.com/search?btnG=1&pws=0&q=java+executable+wrapper

If you'd like, you could also try creating the appropriate batch or script file containing the single line:

java -jar MyJar.jar

Or in many cases on windows just double clicking the executable jar.

Javascript setInterval not working

That's because you should pass a function, not a string:

function funcName() {
    alert("test");
}

setInterval(funcName, 10000);

Your code has two problems:

  • var func = funcName(); calls the function immediately and assigns the return value.
  • Just "func" is invalid even if you use the bad and deprecated eval-like syntax of setInterval. It would be setInterval("func()", 10000) to call the function eval-like.

How can I find out which server hosts LDAP on my windows domain?

AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.

Just try this on the command-line:

C:\> nslookup 
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>>  SRV service location:
      priority       = 0
      weight         = 100
      port           = 389
      svr hostname   = <<ldap.hostname>>.<<your.AD.domain>>

(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)

Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.

How to duplicate sys.stdout to a log file?

I wrote a tee() implementation in Python that should work for most cases, and it works on Windows also.

https://github.com/pycontribs/tendo

Also, you can use it in combination with logging module from Python if you want.

How to get the anchor from the URL using jQuery?

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

How to prevent page scrolling when scrolling a DIV element?

Pure javascript version of Vidas's answer, el$ is the DOM node of the plane you are scrolling.

function onlyScrollElement(event, el$) {
    var delta = event.wheelDelta || -event.detail;
    el$.scrollTop += (delta < 0 ? 1 : -1) * 10;
    event.preventDefault();
}

Make sure you dont attach the even multiple times! Here is an example,

var ul$ = document.getElementById('yo-list');
// IE9, Chrome, Safari, Opera
ul$.removeEventListener('mousewheel', onlyScrollElement);
ul$.addEventListener('mousewheel', onlyScrollElement);
// Firefox
ul$.removeEventListener('DOMMouseScroll', onlyScrollElement);
ul$.addEventListener('DOMMouseScroll', onlyScrollElement);

Word of caution, the function there needs to be a constant, if you reinitialize the function each time before attaching it, ie. var func = function (...) the removeEventListener will not work.

How to get the day name from a selected date?

DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();

Session 'app' error while installing APK

terminal:

  • deleting "build and gradle" folders under project/android

  • cd android && ./gradlew clean && cd .. && react-native run-android

  • cd android && ./gradlew clean &&

Open Excel file for reading with VBA without display

Even though you've got your answer, for those that find this question, it is also possible to open an Excel spreadsheet as a JET data store. Borrowing the connection string from a project I've used it on, it will look kinda like this:

strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & objFile.Path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
strSQL = "SELECT * FROM [RegistrationList$] ORDER BY DateToRegister DESC"

Note that "RegistrationList" is the name of the tab in the workbook. There are a few tutorials floating around on the web with the particulars of what you can and can't do accessing a sheet this way.

Just thought I'd add. :)

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

What is the size of a boolean variable in Java?

Size of the boolean in java is virtual machine dependent. but Any Java object is aligned to an 8 bytes granularity. A Boolean has 8 bytes of header, plus 1 byte of payload, for a total of 9 bytes of information. The JVM then rounds it up to the next multiple of 8. so the one instance of java.lang.Boolean takes up 16 bytes of memory.

Difference between Spring MVC and Struts MVC

Spring MVC is deeply integreated in Spring, Struts MVC is not.

how to align all my li on one line?

Other than white-space:nowrap; also add the following CSS

ul li{
  display: inline;
}

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

How do you get the Git repository's name in some Git repository?

In general, you cannot do this. Git does not care how your git repository is named. For example, you can rename directory containing your repository (one with .git subdirectory), and git will not even notice it - everything will continue to work.

However, if you cloned it, you can use command:

git remote show origin

to display a lot of information about original remote that you cloned your repository from, and it will contain original clone URL.

If, however, you removed link to original remote using git remote rm origin, or if you created that repository using git init, such information is simply impossible to obtain - it does not exist anywhere.

How to remove underline from a link in HTML?

The other answers all mention text-decoration. Sometimes you use a Wordpress theme or someone else's CSS where links are underlined by other methods, so that text-decoration: none won't turn off the underlining.

Border and box-shadow are two other methods I'm aware of for underlining links. To turn these off:

border: none;

and

box-shadow: none;

Count the items from a IEnumerable<T> without iterating?

You can use System.Linq.

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    private IEnumerable<string> Tables
    {
        get {
             yield return "Foo";
             yield return "Bar";
         }
    }

    static void Main()
    {
        var x = new Test();
        Console.WriteLine(x.Tables.Count());
    }
}

You'll get the result '2'.

How to keep Docker container running after starting services?

How about using the supervise form of service if available?

service YOUR_SERVICE supervise

Once supervise is successfully running, it will not exit unless it is killed or specifically asked to exit.

Saves having to create a supervisord.conf

How can I avoid ResultSet is closed exception in Java?

Check whether you have declared the method where this code is executing as static. If it is static there may be some other thread resetting the ResultSet.

Format date in a specific timezone

Use moment-timezone

moment(date).tz('Europe/Berlin').format(format)

Before being able to access a particular timezone, you will need to load it like so (or using alternative methods described here)

moment.tz.add('Europe/Berlin|CET CEST CEMT|-10 -20 -30')

how to make a whole row in a table clickable as a link?

A linked table row is possible, but not with the standard <table> elements. You can do it using the display: table style properties. Here and here are some fiddles to demonstrate.

This code should do the trick:

_x000D_
_x000D_
.table {_x000D_
  display: table;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
  display: table-cell;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.row:hover {_x000D_
  background-color: #cccccc;_x000D_
}_x000D_
_x000D_
.cell:hover {_x000D_
  background-color: #e5e5e5;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
<div role="grid" class="table">_x000D_
  <div role="row" class="row">_x000D_
    <div role="gridcell" class="cell">_x000D_
      1.1_x000D_
    </div>_x000D_
    <div role="gridcell" class="cell">_x000D_
      1.2_x000D_
    </div>_x000D_
    <div role="gridcell" class="cell">_x000D_
      1.3_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <a role="row" class="row" href="#">_x000D_
    <div role="gridcell" class="cell">_x000D_
      2.1_x000D_
    </div>_x000D_
    <div role="gridcell" class="cell">_x000D_
      2.2_x000D_
    </div>_x000D_
    <div role="gridcell" class="cell">_x000D_
      2.3_x000D_
    </div>_x000D_
  </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that ARIA roles are needed to ensure proper accessibility since the standard <table> elements are not used. You may need to add additional roles like role="columnheader" if applicable. Find out more at the guide here.

Replacing a fragment with another fragment inside activity group

Please see this Question

You can only replace a "dynamically added fragment".

So, if you want to add a dynamic fragment, see this example.

How to add a TextView to a LinearLayout dynamically in Android?

Here is a more general answer for future viewers of this question. The layout we will make is below:

enter image description here

Method 1: Add TextView to existing LinearLayout

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

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);

    // Add textview 1
    TextView textView1 = new TextView(this);
    textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    textView1.setText("programmatically created TextView1");
    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
    linearLayout.addView(textView1);

    // Add textview 2
    TextView textView2 = new TextView(this);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.RIGHT;
    layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
    textView2.setLayoutParams(layoutParams);
    textView2.setText("programmatically created TextView2");
    textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
    linearLayout.addView(textView2);
}

Note that for LayoutParams you must specify the kind of layout for the import, as in

import android.widget.LinearLayout.LayoutParams;

Otherwise you need to use LinearLayout.LayoutParams in the code.

Here is the xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff99ccff"
    android:orientation="vertical" >

</LinearLayout>

Method 2: Create both LinearLayout and TextView programmatically

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // NOTE: setContentView is below, not here

    // Create new LinearLayout
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setBackgroundColor(0xff99ccff);

    // Add textviews
    TextView textView1 = new TextView(this);
    textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    textView1.setText("programmatically created TextView1");
    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom)
    linearLayout.addView(textView1);

    TextView textView2 = new TextView(this);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.RIGHT;
    layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
    textView2.setLayoutParams(layoutParams);
    textView2.setText("programmatically created TextView2");
    textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
    linearLayout.addView(textView2);

    // Set context view
    setContentView(linearLayout);
}

Method 3: Programmatically add one xml layout to another xml layout

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

    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
            Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null);
    FrameLayout container = (FrameLayout) findViewById(R.id.flContainer);
    container.addView(view);
}

Here is dynamic_linearlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>

And here is the dynamic_linearlayout_item.xml to add:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff66ff66"
        android:padding="20px"
        android:text="programmatically created TextView1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffdbdb"
        android:layout_gravity="right"
        android:layout_margin="10px"
        android:textSize="18sp"
        android:text="programmatically created TextView2" />

</LinearLayout>

How to set the text/value/content of an `Entry` widget using a button in tkinter

Your problem is that when you do this:

a = Button(win, text="plant", command=setText("plant"))

it tries to evaluate what to set for the command. So when instantiating the Button object, it actually calls setText("plant"). This is wrong, because you don't want to call the setText method yet. Then it takes the return value of this call (which is None), and sets that to the command of the button. That's why clicking the button does nothing, because there is no command set for it.

If you do as Milan Skála suggested and use a lambda expression instead, then your code will work (assuming you fix the indentation and the parentheses).

Instead of command=setText("plant"), which actually calls the function, you can set command=lambda:setText("plant") which specifies something which will call the function later, when you want to call it.

If you don't like lambdas, another (slightly more cumbersome) way would be to define a pair of functions to do what you want:

def set_to_plant():
    set_text("plant")
def set_to_animal():
    set_text("animal")

and then you can use command=set_to_plant and command=set_to_animal - these will evaluate to the corresponding functions, but are definitely not the same as command=set_to_plant() which would of course evaluate to None again.

Select a random sample of results from a query result

Suppose you are trying to select exactly 1,000 random rows from a table called my_table. This is one way to do it:

select
    *
from
    (
        select
            row_number() over(order by dbms_random.value) as random_id,
            x.*
        from
            my_table x
    )
where
    random_id <= 1000
;

This is a slight deviation from the answer posted by @Quassnoi. They both have the same costs and execution times. The only difference is that you can select the random number used to fetch the sample.

HTTP 1.0 vs 1.1

For trivial applications (e.g. sporadically retrieving a temperature value from a web-enabled thermometer) HTTP 1.0 is fine for both a client and a server. You can write a bare-bones socket-based HTTP 1.0 client or server in about 20 lines of code.

For more complicated scenarios HTTP 1.1 is the way to go. Expect a 3 to 5-fold increase in code size for dealing with the intricacies of the more complex HTTP 1.1 protocol. The complexity mainly comes, because in HTTP 1.1 you will need to create, parse, and respond to various headers. You can shield your application from this complexity by having a client use an HTTP library, or server use a web application server.

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

As a follow up to Shubham's great answer I like to suggest using enum values instead of strings. Please take a look at the documentation of the TestLogging class.

import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent

tasks.withType(Test) {
    testLogging {
        events TestLogEvent.FAILED,
               TestLogEvent.PASSED,
               TestLogEvent.SKIPPED,
               TestLogEvent.STANDARD_ERROR,
               TestLogEvent.STANDARD_OUT
        exceptionFormat TestExceptionFormat.FULL
        showCauses true
        showExceptions true
        showStackTraces true
    }
}

Jersey client: How to add a list as query parameter

If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {
        super();
    }

    @GET
    @Path("/withlist")
    @Produces(MediaType.TEXT_PLAIN)
    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();
    }
}

Your client would send a request corresponding to:

GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye

Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'

Communication between multiple docker-compose projects

For using another docker-compose network you just do these(to share networks between docker-compose):

  1. Run the first docker-compose project by up -d
  2. Find the network name of the first docker-compose by: docker network ls(It contains the name of the root directory project)
  3. Then use that name by this structure at below in the second docker-compose file.

second docker-compose.yml

version: '3'
services:
  service-on-second-compose:  # Define any names that you want.
    .
    .
    .
    networks:
      - <put it here(the network name that comes from "docker network ls")>

networks:
  - <put it here(the network name that comes from "docker network ls")>:
    external: true

Is quitting an application frowned upon?

Blog post When to Include an Exit Button in Android Apps (Hint: Never) explains it far, far better than I can. I wish every Android developer has read it already.

Excerpts:

In my experience what [the users] really want is: An unambiguous way to guarantee that an app will stop consuming resources (battery, CPU cycles, data transfer, etc.).

Many users perceive that an exit button implements this requirement and ask for it to be added. Developers, looking to please their users, obligingly add one. Shortly thereafter they both fail.

  • In most cases the exit button simply calls Activity.finish(). This is exactly equivalent to hitting the back button. Exactly. Services keep running and polling keeps happening. Users may think they've killed the app but they haven't, and soon they'll be even more annoyed.
  • Exit behavior is now ambiguous. Should your exit button just close the Activity, or should it also stop all associated Services, Receivers, and Alarms? What should Back do? What happens if they hit Home instead? What happens if your app has a widget? Should the exit button stop that from updating too?

The solution is to make the back button behave as you'd expect the exit button to. Better yet, simply stop consuming resources whenever the app isn't visible.

Go ahead and read the complete article.

Fatal Error :1:1: Content is not allowed in prolog

There are certainly some weird characters (e.g. BOM) or some whitespace before the XML preamble (<?xml ...?>)?

How to Import 1GB .sql file to WAMP/phpmyadmin

Step 1: Find the config.inc.php file located in the phpmyadmin directory. In my case it is located here:

C:\wamp\apps\phpmyadmin3.4.5\config.inc.php 

Note: phymyadmin3.4.5 folder name is different in different version of wamp

Step 2: Find the line with $cfg['UploadDir'] on it and update it to:

$cfg['UploadDir'] = 'upload';

Step 3: Create a directory called ‘upload’ within the phpmyadmin directory.

C:\wamp\apps\phpmyadmin3.2.0.1\upload\

Step 4: Copy and paste the large sql file into upload directory which you want importing to phymyadmin

Step 5: Select sql file from drop down list from phymyadmin to import.

Conditional Logic on Pandas DataFrame

Just compare the column with that value:

In [9]: df = pandas.DataFrame([1,2,3,4], columns=["data"])

In [10]: df
Out[10]: 
   data
0     1
1     2
2     3
3     4

In [11]: df["desired"] = df["data"] > 2.5
In [11]: df
Out[12]: 
   data desired
0     1   False
1     2   False
2     3    True
3     4    True

Angular ui-grid dynamically calculate height of the grid

following @tony's approach, changed the getTableHeight() function to

<div id="grid1" ui-grid="$ctrl.gridOptions" class="grid" ui-grid-auto-resize style="{{$ctrl.getTableHeight()}}"></div>

getTableHeight() {
    var offsetValue = 365;
    return "height: " + parseInt(window.innerHeight - offsetValue ) + "px!important";
}

the grid would have a dynamic height with regards to window height as well.

Practical uses of git reset --soft?

SourceTree is a git GUI which has a pretty convenient interface for staging just the bits you want. It does not have anything remotely similar for amending a proper revision.

So git reset --soft HEAD~1 is much more useful than commit --amend in this scenario. I can undo the commit, get all the changes back into the staging area, and resume tweaking the staged bits using SourceTree.

Really, it seems to me that commit --amend is the more redundant command of the two, but git is git and does not shy away from similar commands that do slightly different things.

UITextField text change event

Swift 4

func addNotificationObservers() {

    NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChangeAction(_:)), name: .UITextFieldTextDidChange, object: nil)

}

@objc func textFieldDidChangeAction(_ notification: NSNotification) {

    let textField = notification.object as! UITextField
    print(textField.text!)

}

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Time calculation in php (add 10 hours)?

$date = date('h:i:s A', strtotime($today . ' + 10 hours'));

(untested)

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

.trim() in JavaScript not working in IE

This issue can be caused by IE using compatibility mode on intranet sites. There are two ways to resolve this, you can either update IE to not use compatibility mode on your local machine (in IE11: Tools-> Compatibility View Settings -> Uncheck Display intranet sites in Compatibility View)

Better yet you can update the meta tags in your webpage. Add in:

...
<head>
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
...

What does this mean? It is telling IE to use the latest compatibility mode. More information is available in MSDN: Specifying legacy document modes

How to tell which row number is clicked in a table?

A better approach would be to delegate the event, which means catching it as it bubbles to the parent node.

delegation - overview

This solution is both more robust and efficient.

It allows the event to be handled even if more rows are dynamically added to the table later, and also results in attaching a single event handler to the parent node (table element), instead of one for each child node (tr element).

Assuming that the OP's example is a simplified one, the table's structure can be more complex, for example:

<table id="indexedTable">
    ...
    <tr>
        <td><p>1</p></td>
        <td>2</td>
        <td><p>3</p></td>
    </tr>
</table>

Therefore, a simplistic approach such as getting e.target.parentElement will not work, as clicking the internal <p> and clicking the center <td> will produce different results.

Using delegation normalizes the event handling, only assuming that there are no nested tables.

implementation

Both of the following snippets are equivalent:

$("#indexedTable").delegate("tr", "click", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

$("#indexedTable").on("click", "tr", function(e) {
    console.log($(e.currentTarget).index() + 1);
});

They attach a listener to table element and handle any event that bubbles from the table rows. The current API is the on method and the delegate method is legacy API (and actually calls on behind the scenes).

Note that the order of parameters to both functions is different.

example

A comparison between direct handler attachment and delegation is available below or on jsFiddle:

_x000D_
_x000D_
$("#table-delegate").on("click", "tr", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#delegation-idx").text(idx);  _x000D_
  console.log('delegated', idx);_x000D_
});_x000D_
_x000D_
$("#table-direct tr").on("click", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#direct-idx").text(idx);_x000D_
  console.log('direct', idx);_x000D_
});_x000D_
_x000D_
$('[data-action=add-row]').click(function(e) {_x000D_
  var id = e.target.dataset.table;_x000D_
  $('#' + id + ' tbody')_x000D_
    .append($('<tr><td>extra</td><td>extra</td><td>extra</td></tr>')[0])_x000D_
});
_x000D_
tr:hover{_x000D_
    background:#ddd;_x000D_
}_x000D_
_x000D_
button.add-row {_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<h1>Event handling test</h1>_x000D_
<p>Add rows to both tables and see the difference in handling.</p>_x000D_
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>_x000D_
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>_x000D_
<h2>Delegation</h2>_x000D_
<p><span>row index: </span><span id="delegation-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-delegate">Add row to delegation</button>_x000D_
<table id="table-delegate" class="table">_x000D_
    <tbody>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
_x000D_
</table>_x000D_
_x000D_
<h2>Direct attachment</h2>_x000D_
<p><span>row index: </span><span id="direct-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-direct">Add row to direct</button>_x000D_
<table id="table-direct" class="table">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>normal</td>_x000D_
        <td>normal</td>_x000D_
        <td><p>nested</p></td>_x000D_
    </tr>_x000D_
    _x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the demo on jsFiddle.

P.S:

If you do have nested tables (or, in the general case, wish to delegate to elements with specific depth), you can use this suggestion from the jQuery bug report.

How do I correct the character encoding of a file?

When you see character sequences like ç and é, it's usually an indication that a UTF-8 file has been opened by a program that reads it in as ANSI (or similar). Unicode characters such as these:

U+00C2 Latin capital letter A with circumflex
U+00C3 Latin capital letter A with tilde
U+0082 Break permitted here
U+0083 No break here

tend to show up in ANSI text because of the variable-byte strategy that UTF-8 uses. This strategy is explained very well here.

The advantage for you is that the appearance of these odd characters makes it relatively easy to find, and thus replace, instances of incorrect conversion.

I believe that, since ANSI always uses 1 byte per character, you can handle this situation with a simple search-and-replace operation. Or more conveniently, with a program that includes a table mapping between the offending sequences and the desired characters, like these:

“ -> “ # should be an opening double curly quote
â€? -> ” # should be a closing double curly quote

Any given text, assuming it's in English, will have a relatively small number of different types of substitutions.

Hope that helps.

What does the exclamation mark do before the function?

The function:

function () {}

returns nothing (or undefined).

Sometimes we want to call a function right as we create it. You might be tempted to try this:

function () {}()

but it results in a SyntaxError.

Using the ! operator before the function causes it to be treated as an expression, so we can call it:

!function () {}()

This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. If you want the actual return value to be the result of the call, then try doing it this way:

(function () {})()

How to open mail app from Swift

For those of us still lagging behind on Swift 2.3 here is Gordon's answer in our syntax:

let email = "[email protected]"
if let url = NSURL(string: "mailto:\(email)") {
   UIApplication.sharedApplication().openURL(url)
}

WHERE Clause to find all records in a specific month

Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.

I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.

You can then use

SELECT ... FROM ...
WHERE DateColumn >= @StartDate 
AND DateColumn < DATEADD(month, 1, @StartDate)

If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.

create function Date(@Year int, @Month int, @Day int)
returns datetime
as
    begin
    return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
    end
go

The query then becomes:

SELECT ... FROM ...
WHERE DateColumn >= Date(@Year,@Month,1)
AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))

Call Stored Procedure within Create Trigger in SQL Server

The following should do the trick - Only SqlServer


Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update
AS
BEGIN

SET NOCOUNT ON;

Declare @id int
DECLARE @cDate as DateTime
    set @cDate =(select Getdate())

select @id=deleted.Catagory_id from deleted
print @cDate

execute dbo.psp_Update_Category @id

END

Alter PROCEDURE dbo.psp_Update_Category
@id int
AS
BEGIN

DECLARE @cDate as DateTime
    set @cDate =(select Getdate())
    --Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id   --@UserID
    Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')
END 

How to find third or n?? maximum salary from salary table?

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

SQL - Update multiple records in one query

INSERT INTO tablename
    (name, salary)
    VALUES 
        ('Bob', 1125),
        ('Jane', 1200),
        ('Frank', 1100),
        ('Susan', 1175),
        ('John', 1150)
        ON DUPLICATE KEY UPDATE salary = VALUES(salary);

Find a class somewhere inside dozens of JAR files?

To search all jar files in a given directory for a particular class, you can do this:

ls *.jar | xargs grep -F MyClass

or, even simpler,

grep -F MyClass *.jar

Output looks like this:

Binary file foo.jar matches

It's very fast because the -F option means search for Fixed string, so it doesn't load the the regex engine for each grep invocation. If you need to, you can always omit the -F option and use regexes.

Exclude subpackages from Spring autowiring?

One thing that seems to work for me is this:

@ComponentScan(basePackageClasses = {SomeTypeInYourPackage.class}, resourcePattern = "*.class")

Or in XML:

<context:component-scan base-package="com.example" resource-pattern="*.class"/>

This overrides the default resourcePattern which is "**/*.class".

This would seem like the most type-safe way to ONLY include your base package since that resourcePattern would always be the same and relative to your base package.

What does %s and %d mean in printf in the C language?

%s%d%s%d\n is a format string. It is used to specify how the information is formatted on an output. here the format string is supposed to print string followed by a digit followed by a string and then again a digit. The last symbol \n represents carriage return which marks the end of a line. In C, strings cannot be concatenated by + or , although you can combine different outputs on a single line by using the appropriate format strings (the use of format strings is to format output info.).

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

Using if elif fi in shell scripts

Use double brackets...

if [[ expression ]]

Generating random numbers in Objective-C

As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.

You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.

At the simplest level, you can generate a random number from the system's built-in random source like this:

NSInteger rand = [[GKRandomSource sharedRandom] nextInt];

That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:

NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];

GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:

GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];

Plus you can shape the random distribution by using things like GKShuffledDistribution.

How can I list all foreign keys referencing a given table in SQL Server?

Determine primary keys and unique keys for all tables in a database...

This should list all the constraints and at the end you can put your filters

/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) 
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME='' 

FROM sys.key_constraints as PKnUKEY
    INNER JOIN sys.tables as PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns as PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns as PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,     
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) 
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id 
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

select * from   ALL_KEYS_IN_TABLE
where   
    PARENT_TABLE_NAME  in ('YOUR_TABLE_NAME') 
    or REFERENCE_TABLE_NAME  in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;

For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx

What's the difference between emulation and simulation?

I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.

For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

Tomcat manager/html is not available?

I couldn't log in to the manager app, even though my tomcat-users.xml file was set up correctly. The problem was that tomcat was configured to get users from a database. An employee who knew how this all worked left the company so I had to track this all down.

If you have a web application with something like this in the projects web.xml:

<security-role>
    <role-name>manager</role-name>
</security-role>

You should be aware that this is using the same system for log ins as tomcat! So where ever your manager role user(s) are defined, that is where you should define your manager-gui role and user. In server.xml I found this:

 <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/<DBName>?user=<DBUser>&amp;password=<DBPassword>"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />

That tells me there is a database storing all the users and roles. This overrides the tomcat-users.xml file. Nothing in that file works unless this Realm is commented out. The solution is to add your tomcat user to the users table and your manager-gui role to the user_roles table:

insert into users (user_name, user_pass) values ('tomcat', '<changeMe>');
insert into user_roles (user_name, role_name) values ('tomcat', 'manager-gui');

You should also have a "manager-gui" rolename in the roles table. Add that if it doesn't exist. Hope this helps someone.

How to include scripts located inside the node_modules folder?

If you want a quick and easy solution (and you have gulp installed).

In my gulpfile.js I run a simple copy paste task that puts any files I might need into ./public/modules/ directory.

gulp.task('modules', function() {
    sources = [
      './node_modules/prismjs/prism.js',
      './node_modules/prismjs/themes/prism-dark.css',
    ]
    gulp.src( sources ).pipe(gulp.dest('./public/modules/'));
});

gulp.task('copy-modules', ['modules']);

The downside to this is that it isn't automated. However, if all you need is a few scripts and styles copied over (and kept in a list), this should do the job.

Replace multiple characters in a C# string

string ToBeReplaceCharacters = @"~()@#$%&amp;+,'&quot;&lt;&gt;|;\/*?";
string fileName = "filename;with<bad:separators?";

foreach (var RepChar in ToBeReplaceCharacters)
{
    fileName = fileName.Replace(RepChar.ToString(), "");
}

How to print_r $_POST array?

The foreach loops work just fine, but you can also simply

print_r($_POST);

Or for pretty printing in a browser:

echo "<pre>";
print_r($_POST);
echo "</pre>";

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

How to show PIL images on the screen?

You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:

import Tkinter as tk
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
#window.geometry("500x500") # (optional)    
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()

For Python 3, replace import Tkinter as tk with import tkinter as tk.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

For CentOS, run this: sudo yum install libXext libSM libXrender

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

Send email from localhost running XAMMP in PHP using GMAIL mail server

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost

Java: Unresolved compilation problem

try to clean the eclipse project

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

I just want to post my solution. Previous answers was pretty helpful for my research. I use length-stream to get the size of the stream, but the problem here is that the callback is fired near the end of the stream, so i also use stream-cache to cache the stream and pipe it to res object once i know the content-length. In case on an error,

var StreamCache = require('stream-cache');
var lengthStream = require('length-stream');

var _streamFile = function(res , stream , cb){
    var cache = new StreamCache();

    var lstream = lengthStream(function(length) {
        res.header("Content-Length", length);
        cache.pipe(res);
    });

    stream.on('error', function(err){
        return cb(err);
    });

    stream.on('end', function(){
        return cb(null , true);
    });

    return stream.pipe(lstream).pipe(cache);
}

How to get host name with port from a http or https request

If your server is running behind a proxy server, make sure your proxy header is set:

proxy_set_header X-Forwarded-Proto  $scheme;

Then to get the right scheme & url you can use springframework's classes:

public String getUrl(HttpServletRequest request) {
    HttpRequest httpRequest = new ServletServerHttpRequest(request);
    UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

    String scheme = uriComponents.getScheme();             // http / https
    String serverName = request.getServerName();     // hostname.com
    int serverPort = request.getServerPort();        // 80
    String contextPath = request.getContextPath();   // /app

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://");
    url.append(serverName);

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }
    url.append(contextPath);
    return url.toString();
}