Programs & Examples On #Document ready

ng-repeat finish event

Here's a simple approach using ng-init that doesn't even require a custom directive. It's worked well for me in certain scenarios e.g. needing to auto-scroll a div of ng-repeated items to a particular item on page load, so the scrolling function needs to wait until the ng-repeat has finished rendering to the DOM before it can fire.

<div ng-controller="MyCtrl">
    <div ng-repeat="thing in things">
        thing: {{ thing }}
    </div>
    <div ng-init="fireEvent()"></div>
</div>

myModule.controller('MyCtrl', function($scope, $timeout){
    $scope.things = ['A', 'B', 'C'];

    $scope.fireEvent = function(){

        // This will only run after the ng-repeat has rendered its things to the DOM
        $timeout(function(){
            $scope.$broadcast('thingsRendered');
        }, 0);

    };
});

Note that this is only useful for functions you need to call one time after the ng-repeat renders initially. If you need to call a function whenever the ng-repeat contents are updated then you'll have to use one of the other answers on this thread with a custom directive.

How can I run a directive after the dom has finished rendering?

there is a ngcontentloaded event, I think you can use it

.directive('directiveExample', function(){
   return {
       restrict: 'A',
       link: function(scope, elem, attrs){

                $$window = $ $window


                init = function(){
                    contentHeight = elem.outerHeight()
                    //do the things
                }

                $$window.on('ngcontentloaded',init)

       }
   }
});

$(document).ready shorthand

The shorthand is:

$(function() {
    // Code here
});

Change fill color on vector asset in Android Studio

To change vector image color you can directly use android:tint="@color/colorAccent"

<ImageView
        android:id="@+id/ivVectorImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_account_circle_black_24dp"
        android:tint="@color/colorAccent" />

To change color programatically

ImageView ivVectorImage = (ImageView) findViewById(R.id.ivVectorImage);
ivVectorImage.setColorFilter(getResources().getColor(R.color.colorPrimary));

How do I properly force a Git push?

First of all, I would not make any changes directly in the "main" repo. If you really want to have a "main" repo, then you should only push to it, never change it directly.

Regarding the error you are getting, have you tried git pull from your local repo, and then git push to the main repo? What you are currently doing (if I understood it well) is forcing the push and then losing your changes in the "main" repo. You should merge the changes locally first.

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

Apache redirect to another port

Just use a Reverse Proxy in your apache configuration (directly):

ProxyPass /foo http://foo.example.com/bar
ProxyPassReverse /foo http://foo.example.com/bar

Look here for apache documentation of how to use the mod

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).

If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.

I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.

It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:

1) You can change the recursion limit with sys.setrecursionlimit(n) until the maximum allowed for your platform:

sys.setrecursionlimit(limit):

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.

Eclipse HotKey: how to switch between tabs?

Switch like Windows in OS (go to window which last had focus)

CTRL-F6 in Eclipse, like ALT-TAB (on windows), brings up a list of tabs/windows available (if you keep the CTRL / ALT key depressed) and highlights the one you will jump to when you let go of this key. You do not have to select the window. If you want to traverse several tabs at once hold down the CTRL button and tap the TAB button. This is identical behaviour to ALT-TAB on Windows.

In this sense, CTRL-SHIFT-F6 in eclipse is the ALT-SHIFT-TAB analog. Personally, I change these bindings in Eclipse to be like Visual Studio. I.e. CTRL-TAB and CTRL-SHIFT-TAB and I do it like this:

Window>Preferences>General>Keys

Then set "Next Editor"=Ctrl+Tab and "Previous Editor"=Ctrl+Shift+Tab. Don't forget to click "Unbind Command" before setting the new binding.

Switch like browser (go to tab on the right of current tab)

This is CTRL-PageDown to go right, CTRL-PageUp to go left. Frustratingly, when you get to the end of the list of tabs (say far right hand tab) and then try to go right again Eclipse does not cycle round to the first tab (far left) like most browsers would.

Label on the left side instead above an input field

You can create such form where label and form control are side using two method -

1. Inline form layout

<form class="form-inline" role="form">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="email" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="reset" class="btn btn-default">Reset</button>
    <button type="submit" class="btn btn-primary">Login</button>
</form>

2. Horizontal Form Layout

<form class="form-horizontal">
    <div class="row">
        <div class="col-sm-4">
            <div class="form-group">
                <label for="inputEmail" class="control-label col-xs-3">Email</label>
                <div class="col-xs-9">
                    <input type="email" class="form-control" id="inputEmail" placeholder="Email">
                </div>
            </div>
        </div>
        <div class="col-sm-5">
            <div class="form-group">
                <label for="inputPassword" class="control-label col-xs-3">Password</label>
                <div class="col-xs-9">
                    <input type="password" class="form-control" id="inputPassword" placeholder="Password">
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <button type="reset" class="btn btn-default">Reset</button>
            <button type="submit" class="btn btn-primary">Login</button>
        </div>
    </div>
</form>

You can check out this page for more information and live demo - http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-forms.php

Center Oversized Image in Div

This is an old Q, but a modern solution without flexbox or position absolute works like this.

margin-left: 50%;
transform: translateX(-50%);

_x000D_
_x000D_
.outer {_x000D_
  border: 1px solid green;_x000D_
  margin: 20px auto;_x000D_
  width: 20%;_x000D_
  padding: 10px 0;_x000D_
  /*   overflow: hidden; */_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  width: 150%;_x000D_
  background-color: gold;_x000D_
  /* Set left edge of inner element to 50% of the parent element */_x000D_
  margin-left: 50%; _x000D_
  /* Move to the left by 50% of own width */_x000D_
  transform: translateX(-50%); _x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.

We have this situation before we add the CSS

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       +-----------------------------------------------------------+
       | Element E                                                 |
       +-----------------------------------------------------------+
       |                                           |
       +-------------------------------------------+

With the added style margin-left: 50% we have

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       |                     +-----------------------------------------------------------+
       |                     | Element E                                                 |
       |                     +-----------------------------------------------------------+
       |                     |                     |
       +---------------------|---------------------+
       |========= a ========>|

       a is 50% width of P

And the transform: translateX(-50%) shifts back to the left

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
+-----------------------------------------------------------+
| Element E                 |                               |
+-----------------------------------------------------------+
|<============ b ===========|                      |
       |                    |                      |
       +--------------------|----------------------+
       |========= a =======>|

       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

Run a vbscript from another vbscript

Just to complete, you could send 3 arguments like this:

objShell.Run "TestScript.vbs 42 ""an arg containing spaces"" foo" 

Undefined symbols for architecture arm64

This issue occurred for me after installing a pod via Podfile and pod install. After trying a bunch of different fixes I finally just imported the Pod manually (dragging the necessary files into my project) and that solved the problem.

How can I split a delimited string into an array in PHP?

In simple way you can go with explode($delimiter, $string);

But in a broad way, with Manual Programming :

        $string = "ab,cdefg,xyx,ht623";
        $resultArr = [];
        $strLength = strlen($string);
        $delimiter = ',';
        $j = 0;
        $tmp = '';
        for ($i = 0; $i < $strLength; $i++) {
            if($delimiter === $string[$i]) {
                $j++;
                $tmp = '';
                continue;
            }
            $tmp .= $string[$i];
            $resultArr[$j] = $tmp;
        }

Outpou : print_r($resultArr);

Array
(
    [0] => ab
    [1] => cdefg
    [2] => xyx
    [3] => ht623
)

How to post SOAP Request from PHP

PHP has SOAP support. Just call

$client = new SoapClient($url);

to connect to the SoapServer and then you can get list of functions and call functions simply by doing...

$client->__getTypes();      
$client->__getFunctions();  

$result = $client->functionName();  

for more http://www.php.net/manual/en/soapclient.soapclient.php

How to keep the spaces at the end and/or at the beginning of a String?

All answers here did not work for me. Instead, to add a space at the end of a string in XML i did this

<string name="more_store">more store<b> </b> </string>

Regex for empty string or white space

If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():

"    your string contents  ".trim();

// => "your string contents"

How to retry after exception?

The clearest way would be to explicitly set i. For example:

i = 0
while i < 100:
    i += 1
    try:
        # do stuff

    except MyException:
        continue

overlay a smaller image on a larger image python OpenCv

For just add an alpha channel to s_img I just use cv2.addWeighted before the line l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

as following:
s_img=cv2.addWeighted(l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]],0.5,s_img,0.5,0)

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

Excel is not updating cells, options > formula > workbook calculation set to automatic

I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:

CtrlAltF9:
Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

CtrlShiftAltF9:
Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!

hash function for string

First, is 40 collisions for 130 words hashed to 0..99 bad? You can't expect perfect hashing if you are not taking steps specifically for it to happen. An ordinary hash function won't have fewer collisions than a random generator most of the time.

A hash function with a good reputation is MurmurHash3.

Finally, regarding the size of the hash table, it really depends what kind of hash table you have in mind, especially, whether buckets are extensible or one-slot. If buckets are extensible, again there is a choice: you choose the average bucket length for the memory/speed constraints that you have.

Get a filtered list of files in a directory

glob.glob() is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match(), something like so:

files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]

More flexible, but as you note, less efficient.

How to run a PowerShell script

I have a very simple answer which works:

  1. Open PowerShell in administrator mode
  2. Run: set-executionpolicy unrestricted
  3. Open a regular PowerShell window and run your script.

I found this solution following the link that was given as part of error message: About Execution Policies

$_POST Array from html form

<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>


$id = implode(',',$_POST['id']);
echo $id

you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r.

print_r($_POST['id']);

Python Linked List

The following is what I came up with. It's similer to Riccardo C.'s, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.

class Node:

    def __init__(self, data=None):
        self.data = data
        self.next = None

    def __str__(self):
        return str(self.data)


class LinkedList:

    def __init__(self):
        self.head = None
        self.curr = None
        self.tail = None

    def __iter__(self):
        return self

    def next(self):
        if self.head and not self.curr:
            self.curr = self.head
            return self.curr
        elif self.curr.next:
            self.curr = self.curr.next
            return self.curr
        else:
            raise StopIteration

    def append(self, data):
        n = Node(data)
        if not self.head:
            self.head = n
            self.tail = n
        else:
            self.tail.next = n
            self.tail = self.tail.next


# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
    ll.append(i)

# print out the list
for n in ll:
    print n

"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""

Change CSS class properties with jQuery

In case you cannot use different stylesheet by dynamically loading it, you can use this function to modify CSS class. Hope it helps you...

function changeCss(className, classValue) {
    // we need invisible container to store additional css definitions
    var cssMainContainer = $('#css-modifier-container');
    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<div id="css-modifier-container"></div>');
        cssMainContainer.hide();
        cssMainContainer.appendTo($('body'));
    }

    // and we need one div for each class
    classContainer = cssMainContainer.find('div[data-class="' + className + '"]');
    if (classContainer.length == 0) {
        classContainer = $('<div data-class="' + className + '"></div>');
        classContainer.appendTo(cssMainContainer);
    }

    // append additional style
    classContainer.html('<style>' + className + ' {' + classValue + '}</style>');
}

This function will take any class name and replace any previously set values with the new value. Note, you can add multiple values by passing the following into classValue: "background: blue; color:yellow".

What's the most efficient way to erase duplicates and sort a vector?

The standard approach suggested by Nate Kohl, just using vector, sort + unique:

sort( vec.begin(), vec.end() );
vec.erase( unique( vec.begin(), vec.end() ), vec.end() );

doesn't work for a vector of pointers.

Look carefully at this example on cplusplus.com.

In their example, the "so called duplicates" moved to the end are actually shown as ? (undefined values), because those "so called duplicates" are SOMETIMES "extra elements" and SOMETIMES there are "missing elements" that were in the original vector.

A problem occurs when using std::unique() on a vector of pointers to objects (memory leaks, bad read of data from HEAP, duplicate frees, which cause segmentation faults, etc).

Here's my solution to the problem: replace std::unique() with ptgi::unique().

See the file ptgi_unique.hpp below:

// ptgi::unique()
//
// Fix a problem in std::unique(), such that none of the original elts in the collection are lost or duplicate.
// ptgi::unique() has the same interface as std::unique()
//
// There is the 2 argument version which calls the default operator== to compare elements.
//
// There is the 3 argument version, which you can pass a user defined functor for specialized comparison.
//
// ptgi::unique() is an improved version of std::unique() which doesn't looose any of the original data
// in the collection, nor does it create duplicates.
//
// After ptgi::unique(), every old element in the original collection is still present in the re-ordered collection,
// except that duplicates have been moved to a contiguous range [dupPosition, last) at the end.
//
// Thus on output:
//  [begin, dupPosition) range are unique elements.
//  [dupPosition, last) range are duplicates which can be removed.
// where:
//  [] means inclusive, and
//  () means exclusive.
//
// In the original std::unique() non-duplicates at end are moved downward toward beginning.
// In the improved ptgi:unique(), non-duplicates at end are swapped with duplicates near beginning.
//
// In addition if you have a collection of ptrs to objects, the regular std::unique() will loose memory,
// and can possibly delete the same pointer multiple times (leading to SEGMENTATION VIOLATION on Linux machines)
// but ptgi::unique() won't.  Use valgrind(1) to find such memory leak problems!!!
//
// NOTE: IF you have a vector of pointers, that is, std::vector<Object*>, then upon return from ptgi::unique()
// you would normally do the following to get rid of the duplicate objects in the HEAP:
//
//  // delete objects from HEAP
//  std::vector<Object*> objects;
//  for (iter = dupPosition; iter != objects.end(); ++iter)
//  {
//      delete (*iter);
//  }
//
//  // shrink the vector. But Object * pointers are NOT followed for duplicate deletes, this shrinks the vector.size())
//  objects.erase(dupPosition, objects.end));
//
// NOTE: But if you have a vector of objects, that is: std::vector<Object>, then upon return from ptgi::unique(), it
// suffices to just call vector:erase(, as erase will automatically call delete on each object in the
// [dupPosition, end) range for you:
//
//  std::vector<Object> objects;
//  objects.erase(dupPosition, last);
//
//==========================================================================================================
// Example of differences between std::unique() vs ptgi::unique().
//
//  Given:
//      int data[] = {10, 11, 21};
//
//  Given this functor: ArrayOfIntegersEqualByTen:
//      A functor which compares two integers a[i] and a[j] in an int a[] array, after division by 10:
//  
//  // given an int data[] array, remove consecutive duplicates from it.
//  // functor used for std::unique (BUGGY) or ptgi::unique(IMPROVED)
//
//  // Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
//  // Hence 50..59 are equal, 60..69 are equal, etc.
//  struct ArrayOfIntegersEqualByTen: public std::equal_to<int>
//  {
//      bool operator() (const int& arg1, const int& arg2) const
//      {
//          return ((arg1/10) == (arg2/10));
//      }
//  };
//  
//  Now, if we call (problematic) std::unique( data, data+3, ArrayOfIntegersEqualByTen() );
//  
//  TEST1: BEFORE UNIQ: 10,11,21
//  TEST1: AFTER UNIQ: 10,21,21
//  DUP_INX=2
//  
//      PROBLEM: 11 is lost, and extra 21 has been added.
//  
//  More complicated example:
//  
//  TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
//  TEST2: AFTER UNIQ: 10,20,30,23,11,31,23,24,11
//  DUP_INX=5
//  
//      Problem: 21 and 22 are deleted.
//      Problem: 11 and 23 are duplicated.
//  
//  
//  NOW if ptgi::unique is called instead of std::unique, both problems go away:
//  
//  DEBUG: TEST1: NEW_WAY=1
//  TEST1: BEFORE UNIQ: 10,11,21
//  TEST1: AFTER UNIQ: 10,21,11
//  DUP_INX=2
//  
//  DEBUG: TEST2: NEW_WAY=1
//  TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
//  TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
//  DUP_INX=5
//
//  @SEE: look at the "case study" below to understand which the last "AFTER UNIQ" results with that order:
//  TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
//
//==========================================================================================================
// Case Study: how ptgi::unique() works:
//  Remember we "remove adjacent duplicates".
//  In this example, the input is NOT fully sorted when ptgi:unique() is called.
//
//  I put | separatators, BEFORE UNIQ to illustrate this
//  10  | 20,21,22 |  30,31 |  23,24 | 11
//
//  In example above, 20, 21, 22 are "same" since dividing by 10 gives 2 quotient.
//  And 30,31 are "same", since /10 quotient is 3.
//  And 23, 24 are same, since /10 quotient is 2.
//  And 11 is "group of one" by itself.
//  So there are 5 groups, but the 4th group (23, 24) happens to be equal to group 2 (20, 21, 22)
//  So there are 5 groups, and the 5th group (11) is equal to group 1 (10)
//
//  R = result
//  F = first
//
//  10, 20, 21, 22, 30, 31, 23, 24, 11
//  R    F
//
//  10 is result, and first points to 20, and R != F (10 != 20) so bump R:
//       R
//       F
//
//  Now we hits the "optimized out swap logic".
//  (avoid swap because R == F)
//
//  // now bump F until R != F (integer division by 10)
//  10, 20, 21, 22, 30, 31, 23, 24, 11
//       R   F              // 20 == 21 in 10x
//       R       F              // 20 == 22 in 10x
//       R           F          // 20 != 30, so we do a swap of ++R and F
//  (Now first hits 21, 22, then finally 30, which is different than R, so we swap bump R to 21 and swap with  30)
//  10, 20, 30, 22, 21, 31, 23, 24, 11  // after R & F swap (21 and 30)
//           R       F 
//
//  10, 20, 30, 22, 21, 31, 23, 24, 11
//           R          F           // bump F to 31, but R and F are same (30 vs 31)
//           R               F      // bump F to 23, R != F, so swap ++R with F
//  10, 20, 30, 22, 21, 31, 23, 24, 11
//                  R           F       // bump R to 22
//  10, 20, 30, 23, 21, 31, 22, 24, 11  // after the R & F swap (22 & 23 swap)
//                  R            F      // will swap 22 and 23
//                  R                F      // bump F to 24, but R and F are same in 10x
//                  R                    F  // bump F, R != F, so swap ++R  with F
//                      R                F  // R and F are diff, so swap ++R  with F (21 and 11)
//  10, 20, 30, 23, 11, 31, 22, 24, 21
//                      R                F  // aftter swap of old 21 and 11
//                      R                  F    // F now at last(), so loop terminates
//                          R               F   // bump R by 1 to point to dupPostion (first duplicate in range)
//
//  return R which now points to 31
//==========================================================================================================
// NOTES:
// 1) the #ifdef IMPROVED_STD_UNIQUE_ALGORITHM documents how we have modified the original std::unique().
// 2) I've heavily unit tested this code, including using valgrind(1), and it is *believed* to be 100% defect-free.
//
//==========================================================================================================
// History:
//  130201  dpb [email protected] created
//==========================================================================================================

#ifndef PTGI_UNIQUE_HPP
#define PTGI_UNIQUE_HPP

// Created to solve memory leak problems when calling std::unique() on a vector<Route*>.
// Memory leaks discovered with valgrind and unitTesting.


#include <algorithm>        // std::swap

// instead of std::myUnique, call this instead, where arg3 is a function ptr
//
// like std::unique, it puts the dups at the end, but it uses swapping to preserve original
// vector contents, to avoid memory leaks and duplicate pointers in vector<Object*>.

#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
#error the #ifdef for IMPROVED_STD_UNIQUE_ALGORITHM was defined previously.. Something is wrong.
#endif

#undef IMPROVED_STD_UNIQUE_ALGORITHM
#define IMPROVED_STD_UNIQUE_ALGORITHM

// similar to std::unique, except that this version swaps elements, to avoid
// memory leaks, when vector contains pointers.
//
// Normally the input is sorted.
// Normal std::unique:
// 10 20 20 20 30   30 20 20 10
// a  b  c  d  e    f  g  h  i
//
// 10 20 30 20 10 | 30 20 20 10
// a  b  e  g  i    f  g  h  i
//
// Now GONE: c, d.
// Now DUPS: g, i.
// This causes memory leaks and segmenation faults due to duplicate deletes of same pointer!


namespace ptgi {

// Return the position of the first in range of duplicates moved to end of vector.
//
// uses operator==  of class for comparison
//
// @param [first, last) is a range to find duplicates within.
//
// @return the dupPosition position, such that [dupPosition, end) are contiguous
// duplicate elements.
// IF all items are unique, then it would return last.
//
template <class ForwardIterator>
ForwardIterator unique( ForwardIterator first, ForwardIterator last)
{
    // compare iterators, not values
    if (first == last)
        return last;

    // remember the current item that we are looking at for uniqueness
    ForwardIterator result = first;

    // result is slow ptr where to store next unique item
    // first is  fast ptr which is looking at all elts

    // the first iterator moves over all elements [begin+1, end).
    // while the current item (result) is the same as all elts
    // to the right, (first) keeps going, until you find a different
    // element pointed to by *first.  At that time, we swap them.

    while (++first != last)
    {
        if (!(*result == *first))
        {
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
            // inc result, then swap *result and *first

//          THIS IS WHAT WE WANT TO DO.
//          BUT THIS COULD SWAP AN ELEMENT WITH ITSELF, UNCECESSARILY!!!
//          std::swap( *first, *(++result));

            // BUT avoid swapping with itself when both iterators are the same
            ++result;
            if (result != first)
                std::swap( *first, *result);
#else
            // original code found in std::unique()
            // copies unique down
            *(++result) = *first;
#endif
        }
    }

    return ++result;
}

template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique( ForwardIterator first, ForwardIterator last, BinaryPredicate pred)
{
    if (first == last)
        return last;

    // remember the current item that we are looking at for uniqueness
    ForwardIterator result = first;

    while (++first != last)
    {
        if (!pred(*result,*first))
        {
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
            // inc result, then swap *result and *first

//          THIS COULD SWAP WITH ITSELF UNCECESSARILY
//          std::swap( *first, *(++result));
//
            // BUT avoid swapping with itself when both iterators are the same
            ++result;
            if (result != first)
                std::swap( *first, *result);

#else
            // original code found in std::unique()
            // copies unique down
            // causes memory leaks, and duplicate ptrs
            // and uncessarily moves in place!
            *(++result) = *first;
#endif
        }
    }

    return ++result;
}

// from now on, the #define is no longer needed, so get rid of it
#undef IMPROVED_STD_UNIQUE_ALGORITHM

} // end ptgi:: namespace

#endif

And here is the UNIT Test program that I used to test it:

// QUESTION: in test2, I had trouble getting one line to compile,which was caused  by the declaration of operator()
// in the equal_to Predicate.  I'm not sure how to correctly resolve that issue.
// Look for //OUT lines
//
// Make sure that NOTES in ptgi_unique.hpp are correct, in how we should "cleanup" duplicates
// from both a vector<Integer> (test1()) and vector<Integer*> (test2).
// Run this with valgrind(1).
//
// In test2(), IF we use the call to std::unique(), we get this problem:
//
//  [dbednar@ipeng8 TestSortRoutes]$ ./Main7
//  TEST2: ORIG nums before UNIQUE: 10, 20, 21, 22, 30, 31, 23, 24, 11
//  TEST2: modified nums AFTER UNIQUE: 10, 20, 30, 23, 11, 31, 23, 24, 11
//  INFO: dupInx=5
//  TEST2: uniq = 10
//  TEST2: uniq = 20
//  TEST2: uniq = 30
//  TEST2: uniq = 33427744
//  TEST2: uniq = 33427808
//  Segmentation fault (core dumped)
//
// And if we run valgrind we seen various error about "read errors", "mismatched free", "definitely lost", etc.
//
//  valgrind --leak-check=full ./Main7
//  ==359== Memcheck, a memory error detector
//  ==359== Command: ./Main7
//  ==359== Invalid read of size 4
//  ==359== Invalid free() / delete / delete[]
//  ==359== HEAP SUMMARY:
//  ==359==     in use at exit: 8 bytes in 2 blocks
//  ==359== LEAK SUMMARY:
//  ==359==    definitely lost: 8 bytes in 2 blocks
// But once we replace the call in test2() to use ptgi::unique(), all valgrind() error messages disappear.
//
// 130212   dpb [email protected] created
// =========================================================================================================

#include <iostream> // std::cout, std::cerr
#include <string>
#include <vector>   // std::vector
#include <sstream>  // std::ostringstream
#include <algorithm>    // std::unique()
#include <functional>   // std::equal_to(), std::binary_function()
#include <cassert>  // assert() MACRO

#include "ptgi_unique.hpp"  // ptgi::unique()



// Integer is small "wrapper class" around a primitive int.
// There is no SETTER, so Integer's are IMMUTABLE, just like in JAVA.

class Integer
{
private:
    int num;
public:

    // default CTOR: "Integer zero;"
    // COMPRENSIVE CTOR:  "Integer five(5);"
    Integer( int num = 0 ) :
        num(num)
    {
    }

    // COPY CTOR
    Integer( const Integer& rhs) :
        num(rhs.num)
    {
    }

    // assignment, operator=, needs nothing special... since all data members are primitives

    // GETTER for 'num' data member
    // GETTER' are *always* const
    int getNum() const
    {
        return num;
    }   

    // NO SETTER, because IMMUTABLE (similar to Java's Integer class)

    // @return "num"
    // NB: toString() should *always* be a const method
    //
    // NOTE: it is probably more efficient to call getNum() intead
    // of toString() when printing a number:
    //
    // BETTER to do this:
    //  Integer five(5);
    //  std::cout << five.getNum() << "\n"
    // than this:
    //  std::cout << five.toString() << "\n"

    std::string toString() const
    {
        std::ostringstream oss;
        oss << num;
        return oss.str();
    }
};

// convenience typedef's for iterating over std::vector<Integer>
typedef std::vector<Integer>::iterator      IntegerVectorIterator;
typedef std::vector<Integer>::const_iterator    ConstIntegerVectorIterator;

// convenience typedef's for iterating over std::vector<Integer*>
typedef std::vector<Integer*>::iterator     IntegerStarVectorIterator;
typedef std::vector<Integer*>::const_iterator   ConstIntegerStarVectorIterator;

// functor used for std::unique or ptgi::unique() on a std::vector<Integer>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTen: public std::equal_to<Integer>
{
    bool operator() (const Integer& arg1, const Integer& arg2) const
    {
        return ((arg1.getNum()/10) == (arg2.getNum()/10));
    }
};

// functor used for std::unique or ptgi::unique on a std::vector<Integer*>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTenPointer: public std::equal_to<Integer*>
{
    // NB: the Integer*& looks funny to me!
    // TECHNICAL PROBLEM ELSEWHERE so had to remove the & from *&
//OUT   bool operator() (const Integer*& arg1, const Integer*& arg2) const
//
    bool operator() (const Integer* arg1, const Integer* arg2) const
    {
        return ((arg1->getNum()/10) == (arg2->getNum()/10));
    }
};

void test1();
void test2();
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums );

int main()
{
    test1();
    test2();
    return 0;
}

// test1() uses a vector<Object> (namely vector<Integer>), so there is no problem with memory loss
void test1()
{
    int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};

    // turn C array into C++ vector
    std::vector<Integer> nums(data, data+9);

    // arg3 is a functor
    IntegerVectorIterator dupPosition = ptgi::unique( nums.begin(), nums.end(), IntegerEqualByTen() );

    nums.erase(dupPosition, nums.end());

    nums.erase(nums.begin(), dupPosition);
}

//==================================================================================
// test2() uses a vector<Integer*>, so after ptgi:unique(), we have to be careful in
// how we eliminate the duplicate Integer objects stored in the heap.
//==================================================================================
void test2()
{
    int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};

    // turn C array into C++ vector of Integer* pointers
    std::vector<Integer*> nums;

    // put data[] integers into equivalent Integer* objects in HEAP
    for (int inx = 0; inx < 9; ++inx)
    {
        nums.push_back( new Integer(data[inx]) );
    }

    // print the vector<Integer*> to stdout
    printIntegerStarVector( "TEST2: ORIG nums before UNIQUE", nums );

    // arg3 is a functor
#if 1
    // corrected version which fixes SEGMENTATION FAULT and all memory leaks reported by valgrind(1)
    // I THINK we want to use new C++11 cbegin() and cend(),since the equal_to predicate is passed "Integer *&"

//  DID NOT COMPILE
//OUT   IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<ConstIntegerStarVectorIterator>(nums.begin()), const_cast<ConstIntegerStarVectorIterator>(nums.end()), IntegerEqualByTenPointer() );

    // DID NOT COMPILE when equal_to predicate declared "Integer*& arg1, Integer*&  arg2"
//OUT   IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<nums::const_iterator>(nums.begin()), const_cast<nums::const_iterator>(nums.end()), IntegerEqualByTenPointer() );


    // okay when equal_to predicate declared "Integer* arg1, Integer*  arg2"
    IntegerStarVectorIterator dupPosition = ptgi::unique(nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#else
    // BUGGY version that causes SEGMENTATION FAULT and valgrind(1) errors
    IntegerStarVectorIterator dupPosition = std::unique( nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#endif

    printIntegerStarVector( "TEST2: modified nums AFTER UNIQUE", nums );
    int dupInx = dupPosition - nums.begin();
    std::cout << "INFO: dupInx=" << dupInx <<"\n";

    // delete the dup Integer* objects in the [dupPosition, end] range
    for (IntegerStarVectorIterator iter = dupPosition; iter != nums.end(); ++iter)
    {
        delete (*iter);
    }

    // shrink the vector
    // NB: the Integer* ptrs are NOT followed by vector::erase()
    nums.erase(dupPosition, nums.end());


    // print the uniques, by following the iter to the Integer* pointer
    for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end();  ++iter)
    {
        std::cout << "TEST2: uniq = " << (*iter)->getNum() << "\n";
    }

    // remove the unique objects from heap
    for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end();  ++iter)
    {
        delete (*iter);
    }

    // shrink the vector
    nums.erase(nums.begin(), nums.end());

    // the vector should now be completely empty
    assert( nums.size() == 0);
}

//@ print to stdout the string: "info_msg: num1, num2, .... numN\n"
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums )
{
    std::cout << msg << ": ";
    int inx = 0;
    ConstIntegerStarVectorIterator  iter;

    // use const iterator and const range!
    // NB: cbegin() and cend() not supported until LATER (c++11)
    for (iter = nums.begin(), inx = 0; iter != nums.end(); ++iter, ++inx)
    {
        // output a comma seperator *AFTER* first
        if (inx > 0)
            std::cout << ", ";

        // call Integer::toString()
        std::cout << (*iter)->getNum();     // send int to stdout
//      std::cout << (*iter)->toString();   // also works, but is probably slower

    }

    // in conclusion, add newline
    std::cout << "\n";
}

How can I get a channel ID from YouTube?

2017 Update: Henry's answer may be a little off the mark here. If you look for data-channel-external-id in the source code you may find more than one ID, and only the first occurrence is actually correct. Get the channel_id used in <link rel="alternate" type="application/rss+xml" title="RSS" href="https://www.youtube.com/feeds/videos.xml?channel_id=<VALUE_HERE"> instead.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How can I check if a directory exists in a Bash shell script?

Here's a very pragmatic idiom:

(cd $dir) || return # Is this a directory,
                    # and do we have access?

I typically wrap it in a function:

can_use_as_dir() {
    (cd ${1:?pathname expected}) || return
}

Or:

assert_dir_access() {
    (cd ${1:?pathname expected}) || exit
}

The nice thing about this approach is that I do not have to think of a good error message.

cd will give me a standard one line message to standard error already. It will also give more information than I will be able to provide. By performing the cd inside a subshell ( ... ), the command does not affect the current directory of the caller. If the directory exists, this subshell and the function are just a no-op.

Next is the argument that we pass to cd: ${1:?pathname expected}. This is a more elaborate form of parameter substitution which is explained in more detail below.

Tl;dr: If the string passed into this function is empty, we again exit from the subshell ( ... ) and return from the function with the given error message.


Quoting from the ksh93 man page:

${parameter:?word}

If parameter is set and is non-null then substitute its value; otherwise, print word and exit from the shell (if not interactive). If word is omitted then a standard message is printed.

and

If the colon : is omitted from the above expressions, then the shell only checks whether parameter is set or not.

The phrasing here is peculiar to the shell documentation, as word may refer to any reasonable string, including whitespace.

In this particular case, I know that the standard error message 1: parameter not set is not sufficient, so I zoom in on the type of value that we expect here - the pathname of a directory.

A philosophical note:

The shell is not an object oriented language, so the message says pathname, not directory. At this level, I'd rather keep it simple - the arguments to a function are just strings.

Dictionary of dictionaries in Python?

If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:

def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]

Ignore mapping one property with Automapper

You can do this:

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.Ignore());

Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field

conf.CreateMap<SourceType, DestinationType>()
   .ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());

What can I use for good quality code coverage for C#/.NET?

There are pre-release (beta) versions of NCover available for free. They work fine for most cases, especially when combined with NCoverExplorer.

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

SQL> -- original . . .
SQL> select
  2  to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
  3  from dual;

DT
----------------------------------------
Friday    the 13th of May      , 2016

SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  * *', ' ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May , 2016

SQL>
SQL> -- and space before commma . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *(,*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

SQL>
SQL> -- space before punctuation . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *([.,/:;]*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

Change one value based on another value in pandas

The original question addresses a specific narrow use case. For those who need more generic answers here are some examples:

Creating a new column using data from other columns

Given the dataframe below:

import pandas as pd
import numpy as np

df = pd.DataFrame([['dog', 'hound', 5],
                   ['cat', 'ragdoll', 1]],
                  columns=['animal', 'type', 'age'])

In[1]:
Out[1]:
  animal     type  age
----------------------
0    dog    hound    5
1    cat  ragdoll    1

Below we are adding a new description column as a concatenation of other columns by using the + operation which is overridden for series. Fancy string formatting, f-strings etc won't work here since the + applies to scalars and not 'primitive' values:

df['description'] = 'A ' + df.age.astype(str) + ' years old ' \
                    + df.type + ' ' + df.animal

In [2]: df
Out[2]:
  animal     type  age                description
-------------------------------------------------
0    dog    hound    5    A 5 years old hound dog
1    cat  ragdoll    1  A 1 years old ragdoll cat

We get 1 years for the cat (instead of 1 year) which we will be fixing below using conditionals.

Modifying an existing column with conditionals

Here we are replacing the original animal column with values from other columns, and using np.where to set a conditional substring based on the value of age:

# append 's' to 'age' if it's greater than 1
df.animal = df.animal + ", " + df.type + ", " + \
    df.age.astype(str) + " year" + np.where(df.age > 1, 's', '')

In [3]: df
Out[3]:
                 animal     type  age
-------------------------------------
0   dog, hound, 5 years    hound    5
1  cat, ragdoll, 1 year  ragdoll    1

Modifying multiple columns with conditionals

A more flexible approach is to call .apply() on an entire dataframe rather than on a single column:

def transform_row(r):
    r.animal = 'wild ' + r.type
    r.type = r.animal + ' creature'
    r.age = "{} year{}".format(r.age, r.age > 1 and 's' or '')
    return r

df.apply(transform_row, axis=1)

In[4]:
Out[4]:
         animal            type      age
----------------------------------------
0    wild hound    dog creature  5 years
1  wild ragdoll    cat creature   1 year

In the code above the transform_row(r) function takes a Series object representing a given row (indicated by axis=1, the default value of axis=0 will provide a Series object for each column). This simplifies processing since we can access the actual 'primitive' values in the row using the column names and have visibility of other cells in the given row/column.

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Private vs Protected - Visibility Good-Practice Concern

No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.

If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.

A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.

How to create a file name with the current date & time in Python?

now is a class method in the class datetime in the module datetime. So you need

datetime.datetime.now()

Or you can use a different import

from datetime import datetime

Done this way allows you to use datetime.now as per the code in the question.

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Merge two Excel tables Based on matching data in Columns

Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.

My setup was as follows:

  • Sheet1: full data of 2014
  • Sheet2: updated rows for 2015 in A1:D50, sorted by first column
  • Sheet3: merged rows
  • My data does not have a header row

I put the following formula in cell A1 of Sheet3:

=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)

Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.

Notes:

  • In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.

  • A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.

After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:

=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)

and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.

Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.

Cells A2, A3, etc. will get these formulas:

=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)

Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.

Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

What is the purpose and use of **kwargs?

Motif: *args and **kwargs serves as a placeholder for the arguments that need to be passed to a function call

using *args and **kwargs to call a function

def args_kwargs_test(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

Now we'll use *args to call the above defined function

#args can either be a "list" or "tuple"
>>> args = ("two", 3, 5)  
>>> args_kwargs_test(*args)

result:

arg1: two
arg2: 3
arg3: 5


Now, using **kwargs to call the same function

#keyword argument "kwargs" has to be a dictionary
>>> kwargs = {"arg3":3, "arg2":'two', "arg1":5}
>>> args_kwargs_test(**kwargs)

result:

arg1: 5
arg2: two
arg3: 3

Bottomline : *args has no intelligence, it simply interpolates the passed args to the parameters(in left-to-right order) while **kwargs behaves intelligently by placing the appropriate value @ the required place

A cycle was detected in the build path of project xxx - Build Path Problem

I faced similar problem a while ago and decided to write Eclipse plug-in that shows complete build path dependency tree of a Java project (although not in graphic mode - result is written into file). The plug-in's sources are here http://github.com/PetrGlad/dependency-tree

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

Targeting both 32bit and 64bit with Visual Studio in same solution/project

Regarding your last question. Most likely you cant solve this inside a single MSI. If you are using registry/system folders or anything related, the MSI itself must be aware of this and you must prepare a 64bit MSI to properly install on 32 bit machine.

There is a possibility that you can make you product installed as a 32 it application and still be able to make it run as 64 bit one, but i think that may be somewhat hard to achieve.

that being said i think you should be able to keep a single code base for everything. In my current work place we have managed to do so. (but it did took some juggling to make everything play together)

Hope this helps. Heres a link to some info related to 32/64 bit issues: http://blog.typemock.com/2008/07/registry-on-windows-64-bit-double-your.html

Javascript validation: Block special characters

A few of the options are deprecated as of today. So watch out for those.

If you try <input onkeypress="blockSpecialCharacters(event)" />, an IDE like WebStorm will slash out event and tell you:

Deprecated symbol used, consults docs for better alternative

Then when you get to the JavaScript, console.log(e.keyCode) will also give keyCode and say:

Deprecated symbol used, consults docs for better alternative

Anyways I did it using jQuery.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<input id="theInput" />

<script>
    function blockSpecialCharacters(e) {
            let key = e.key;
            let keyCharCode = key.charCodeAt(0);

            // 0-9
            if(keyCharCode >= 48 && keyCharCode <= 57) {
                return key;
            }
            // A-Z
            if(keyCharCode >= 65 && keyCharCode <= 90) {
                return key;
            }
            // a-z
            if(keyCharCode >= 97 && keyCharCode <= 122) {
                return key;
            }

            return false;
    }

    $('#theInput').keypress(function(e) {
        blockSpecialCharacters(e);
    });
</script>

How do I check if a string is a number (float)?

The input may be as follows:

a="50" b=50 c=50.1 d="50.1"


1-General input:

The input of this function can be everything!

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed.

is_numeric function

import ast
import numbers              
def is_numeric(obj):
    if isinstance(obj, numbers.Number):
        return True
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            #if used + or - in digit :
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

test:

>>> is_numeric("54")
True
>>> is_numeric("54.545")
True
>>> is_numeric("0x45")
True

is_float function

Finds whether the given variable is float. float strings consist of optional sign, any number of digits, ...

import ast

def is_float(obj):
    if isinstance(obj, float):
        return True
    if isinstance(obj, int):
        return False
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        if not isinstance(nodes[-1].n, float):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

test:

>>> is_float("5.4")
True
>>> is_float("5")
False
>>> is_float(5)
False
>>> is_float("5")
False
>>> is_float("+5.4")
True

what is ast?


2- If you are confident that the variable content is String:

use str.isdigit() method

>>> a=454
>>> a.isdigit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
>>> a="454"
>>> a.isdigit()
True

3-Numerical input:

detect int value:

>>> isinstance("54", int)
False
>>> isinstance(54, int)
True
>>> 

detect float:

>>> isinstance("45.1", float)
False
>>> isinstance(45.1, float)
True

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

Use IIF.

<asp:Label ID="Label18" Text='<%# IIF(Eval("item") Is DBNull.Value,"0", Eval("item") %>' 
runat="server"></asp:Label>

Execute and get the output of a shell command in node.js

This is the method I'm using in a project I am currently working on.

var exec = require('child_process').exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
};

Example of retrieving a git user:

module.exports.getGitUser = function(callback){
    execute("git config --global user.name", function(name){
        execute("git config --global user.email", function(email){
            callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
        });
    });
};

Visual Studio Code Tab Key does not insert a tab

I am using code on xfce - did the following to fix the Tab key behavior:

File -> Preferences -> Settings

search for "keyboard.dispatch"

copy to right panel and change value from "code" to "keyCode"

Reload code

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

Converting Select results into Insert script - SQL Server

I think its also possible with adhoc queries you can export result to excel file and then import that file into your datatable object or use it as it is and then import the excel file into the second database have a look at this link this can help u alot.

http://vscontrols.blogspot.com/2010/09/import-and-export-excel-to-sql-server.html

JavaScript closures vs. anonymous functions

You are both using closures.

I 'm going with the Wikipedia definition here:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

Your friend's attempt clearly uses the variable i, which is non-local, by taking its value and making a copy to store into the local i2.

Your own attempt passes i (which at the call site is in scope) to an anonymous function as an argument. This is not a closure so far, but then that function returns another function that references the same i2. Since inside the inner anonymous function i2 is not a local, this creates a closure.

Easiest way to ignore blank lines when reading a file in Python

When a treatment of text must be done to just extract data from it, I always think first to the regexes, because:

  • as far as I know, regexes have been invented for that

  • iterating over lines appears clumsy to me: it essentially consists to search the newlines then to search the data to extract in each line; that makes two searches instead of a direct unique one with a regex

  • way of bringing regexes into play is easy; only the writing of a regex string to be compiled into a regex object is sometimes hard, but in this case the treatment with an iteration over lines will be complicated too

For the problem discussed here, a regex solution is fast and easy to write:

import re
names = re.findall('\S+',open(filename).read())

I compared the speeds of several solutions:

import re
from time import clock

A,AA,B1,B2,BS,reg = [],[],[],[],[],[]
D,Dsh,C1,C2 = [],[],[],[]
F1,F2,F3  = [],[],[]

def nonblank_lines(f):
    for l in f:
        line = l.rstrip()
        if line:  yield line

def short_nonblank_lines(f):
    for l in f:
        line = l[0:-1]
        if line:  yield line

for essays in xrange(50):

    te = clock()
    with open('raa.txt') as f:
        names_listA = [line.strip() for line in f if line.strip()] # Felix Kling
    A.append(clock()-te)

    te = clock()
    with open('raa.txt') as f:
        names_listAA = [line[0:-1] for line in f if line[0:-1]] # Felix Kling with line[0:-1]
    AA.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        namesB1 = [ name for name in (l.strip() for l in f_in) if name ] # aaronasterling without list()
    B1.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        namesB2 = [ name for name in (l[0:-1] for l in f_in) if name ] # aaronasterling without list() and with line[0:-1]
    B2.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        namesBS = [ name for name in f_in.read().splitlines() if name ] # a list comprehension with read().splitlines()
    BS.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f:
        xreg = re.findall('\S+',f.read()) #  eyquem
    reg.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        linesC1 = list(line for line in (l.strip() for l in f_in) if line) # aaronasterling
    C1.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        linesC2 = list(line for line in (l[0:-1] for l in f_in) if line) # aaronasterling  with line[0:-1]
    C2.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        yD = [ line for line in nonblank_lines(f_in)  ] # aaronasterling  update
    D.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        yDsh = [ name for name in short_nonblank_lines(f_in)  ] # nonblank_lines with line[0:-1]
    Dsh.append(clock()-te)

    #-------------------------------------------------------
    te = clock()
    with open('raa.txt') as f_in:
        linesF1 = filter(None, (line.rstrip() for line in f_in)) # aaronasterling update 2
    F1.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        linesF2 = filter(None, (line[0:-1] for line in f_in)) # aaronasterling update 2 with line[0:-1]
    F2.append(clock()-te)

    te = clock()
    with open('raa.txt') as f_in:
        linesF3 =  filter(None, f_in.read().splitlines()) # aaronasterling update 2 with read().splitlines()
    F3.append(clock()-te)


print 'names_listA == names_listAA==namesB1==namesB2==namesBS==xreg\n  is ',\
       names_listA == names_listAA==namesB1==namesB2==namesBS==xreg
print 'names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3\n  is ',\
       names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3,'\n\n\n'


def displ((fr,it,what)):  print fr + str( min(it) )[0:7] + '   ' + what

map(displ,(('* ', A,    '[line.strip() for line in f if line.strip()]               * Felix Kling\n'),

           ('  ', B1,   '    [name for name in (l.strip() for l in f_in) if name ]    aaronasterling without list()'),
           ('* ', C1,   'list(line for line in (l.strip() for l in f_in) if line)   * aaronasterling\n'),          

           ('* ', reg,  're.findall("\S+",f.read())                                 * eyquem\n'),

           ('* ', D,    '[ line for line in       nonblank_lines(f_in)  ]           * aaronasterling  update'),
           ('  ', Dsh,  '[ line for line in short_nonblank_lines(f_in)  ]             nonblank_lines with line[0:-1]\n'),

           ('* ', F1 ,  'filter(None, (line.rstrip() for line in f_in))             * aaronasterling update 2\n'),

           ('  ', B2,   '    [name for name in (l[0:-1]   for l in f_in) if name ]    aaronasterling without list() and with line[0:-1]'),
           ('  ', C2,   'list(line for line in (l[0:-1]   for l in f_in) if line)     aaronasterling  with line[0:-1]\n'),

           ('  ', AA,   '[line[0:-1] for line in f if line[0:-1]  ]                   Felix Kling with line[0:-1]\n'),

           ('  ', BS,   '[name for name in f_in.read().splitlines() if name ]        a list comprehension with read().splitlines()\n'),

           ('  ', F2 ,  'filter(None, (line[0:-1] for line in f_in))                  aaronasterling update 2 with line[0:-1]'),

           ('  ', F3 ,  'filter(None, f_in.read().splitlines()                        aaronasterling update 2 with read().splitlines()'))
    )

Solution with regex is straightforward and neat. Though, it isn't among the fastest ones. The solution of aaronasterling with filter() is surprisigly fast for me (I wasn't aware of this particular filter()'s speed) and times of optimized solutions go down until 27 % of the biggest time. I wonder what makes the miracle of the filter-splitlines association:

names_listA == names_listAA==namesB1==namesB2==namesBS==xreg
  is  True
names_listA == yD==yDsh==linesC1==linesC2==linesF1==linesF2==linesF3
  is  True 



* 0.08266   [line.strip() for line in f if line.strip()]               * Felix Kling

  0.07535       [name for name in (l.strip() for l in f_in) if name ]    aaronasterling without list()
* 0.06912   list(line for line in (l.strip() for l in f_in) if line)   * aaronasterling

* 0.06612   re.findall("\S+",f.read())                                 * eyquem

* 0.06486   [ line for line in       nonblank_lines(f_in)  ]           * aaronasterling  update
  0.05264   [ line for line in short_nonblank_lines(f_in)  ]             nonblank_lines with line[0:-1]

* 0.05451   filter(None, (line.rstrip() for line in f_in))             * aaronasterling update 2

  0.04689       [name for name in (l[0:-1]   for l in f_in) if name ]    aaronasterling without list() and with line[0:-1]
  0.04582   list(line for line in (l[0:-1]   for l in f_in) if line)     aaronasterling  with line[0:-1]

  0.04171   [line[0:-1] for line in f if line[0:-1]  ]                   Felix Kling with line[0:-1]

  0.03265   [name for name in f_in.read().splitlines() if name ]        a list comprehension with read().splitlines()

  0.03638   filter(None, (line[0:-1] for line in f_in))                  aaronasterling update 2 with line[0:-1]
  0.02198   filter(None, f_in.read().splitlines()                        aaronasterling update 2 with read().splitlines()

But this problem is particular, the most simple of all: only one name in each line. So the solutions are only games with lines, splitings and [0:-1] cuts.

On the contrary, regex doesn't matter with lines, it straightforwardly finds the desired data: I consider it is a more natural way of resolution, applying from the simplest to the more complex cases, and hence is often the way to be prefered in treatments of texts.

EDIT

I forgot to say that I use Python 2.7 and I measured the above times with a file containing 500 times the following chain

SMITH
JONES
WILLIAMS
TAYLOR
BROWN
DAVIES
EVANS
WILSON
THOMAS
JOHNSON

ROBERTS
ROBINSON
THOMPSON
WRIGHT
WALKER
WHITE
EDWARDS
HUGHES
GREEN
HALL

LEWIS
HARRIS
CLARKE
PATEL
JACKSON
WOOD
TURNER
MARTIN
COOPER
HILL

WARD
MORRIS
MOORE
CLARK
LEE
KING
BAKER
HARRISON
MORGAN
ALLEN

JAMES
SCOTT
PHILLIPS
WATSON
DAVIS
PARKER
PRICE
BENNETT
YOUNG
GRIFFITHS

MITCHELL
KELLY
COOK
CARTER
RICHARDSON
BAILEY
COLLINS
BELL
SHAW
MURPHY

MILLER
COX
RICHARDS
KHAN
MARSHALL
ANDERSON
SIMPSON
ELLIS
ADAMS
SINGH

BEGUM
WILKINSON
FOSTER
CHAPMAN
POWELL
WEBB
ROGERS
GRAY
MASON
ALI

HUNT
HUSSAIN
CAMPBELL
MATTHEWS
OWEN
PALMER
HOLMES
MILLS
BARNES
KNIGHT

LLOYD
BUTLER
RUSSELL
BARKER
FISHER
STEVENS
JENKINS
MURRAY
DIXON
HARVEY

Preferred way of loading resources in Java

Well, it partly depends what you want to happen if you're actually in a derived class.

For example, suppose SuperClass is in A.jar and SubClass is in B.jar, and you're executing code in an instance method declared in SuperClass but where this refers to an instance of SubClass. If you use this.getClass().getResource() it will look relative to SubClass, in B.jar. I suspect that's usually not what's required.

Personally I'd probably use Foo.class.getResourceAsStream(name) most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo, that's the most robust way of doing it IMO.

Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.

where is create-react-app webpack config and files?

Webpack configuration is being handled by react-scripts. You can find all webpack config inside node_modules react-scripts/config.

And If you want to customize webpack config, you can follow this customize-webpack-config

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

I finally figured out a solution and create a Kotlin class for it

object KeyboardUtils {

    fun showKeyboard(editText: EditText) {
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideKeyboard(editText: EditText) {
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

}

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

Selecting Folder Destination in Java?

Along with JFileChooser is possible use this:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

for have a Look and Feel like Windows.

for others settings, view here: https://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#available

Including non-Python files with setup.py

Figured out a workaround: I renamed my lgpl2.1_license.txt to lgpl2.1_license.txt.py, and put some triple quotes around the text. Now I don't need to use the data_files option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.

Named capturing groups in JavaScript regex?

Don't have ECMAScript 2018?

My goal was to make it work as similar as possible to what we are used to with named groups. Whereas in ECMAScript 2018 you can place ?<groupname> inside the group to indicate a named group, in my solution for older javascript, you can place (?!=<groupname>) inside the group to do the same thing. So it's an extra set of parenthesis and an extra !=. Pretty close!

I wrapped all of it into a string prototype function

Features

  • works with older javascript
  • no extra code
  • pretty simple to use
  • Regex still works
  • groups are documented within the regex itself
  • group names can have spaces
  • returns object with results

Instructions

  • place (?!={groupname}) inside each group you want to name
  • remember to eliminate any non-capturing groups () by putting ?: at the beginning of that group. These won't be named.

arrays.js

// @@pattern - includes injections of (?!={groupname}) for each group
// @@returns - an object with a property for each group having the group's match as the value 
String.prototype.matchWithGroups = function (pattern) {
  var matches = this.match(pattern);
  return pattern
  // get the pattern as a string
  .toString()
  // suss out the groups
  .match(/<(.+?)>/g)
  // remove the braces
  .map(function(group) {
    return group.match(/<(.+)>/)[1];
  })
  // create an object with a property for each group having the group's match as the value 
  .reduce(function(acc, curr, index, arr) {
    acc[curr] = matches[index + 1];
    return acc;
  }, {});
};    

usage

function testRegGroups() {
  var s = '123 Main St';
  var pattern = /((?!=<house number>)\d+)\s((?!=<street name>)\w+)\s((?!=<street type>)\w+)/;
  var o = s.matchWithGroups(pattern); // {'house number':"123", 'street name':"Main", 'street type':"St"}
  var j = JSON.stringify(o);
  var housenum = o['house number']; // 123
}

result of o

{
  "house number": "123",
  "street name": "Main",
  "street type": "St"
}

JAX-WS client : what's the correct path to access the local WSDL?

Had the exact same problem that is described herein. No matter what I did, following the above examples, to change the location of my WSDL file (in our case from a web server), it was still referencing the original location embedded within the source tree of the server process.

After MANY hours trying to debug this, I noticed that the Exception was always being thrown from the exact same line (in my case 41). Finally this morning, I decided to just send my source client code to our trade partner so they can at least understand how the code looks, but perhaps build their own. To my shock and horror I found a bunch of class files mixed in with my .java files within my client source tree. How bizarre!! I suspect these were a byproduct of the JAX-WS client builder tool.

Once I zapped those silly .class files and performed a complete clean and rebuild of the client code, everything works perfectly!! Redonculous!!

YMMV, Andrew

How to get unique values in an array

You only need vanilla JS to find uniques with Array.some and Array.reduce. With ES2015 syntax it's only 62 characters.

a.reduce((c, v) => b.some(w => w === v) ? c : c.concat(v)), b)

Array.some and Array.reduce are supported in IE9+ and other browsers. Just change the fat arrow functions for regular functions to support in browsers that don't support ES2015 syntax.

var a = [1,2,3];
var b = [4,5,6];
// .reduce can return a subset or superset
var uniques = a.reduce(function(c, v){
    // .some stops on the first time the function returns true                
    return (b.some(function(w){ return w === v; }) ?  
      // if there's a match, return the array "c"
      c :     
      // if there's no match, then add to the end and return the entire array                                        
      c.concat(v)}),                                  
  // the second param in .reduce is the starting variable. This is will be "c" the first time it runs.
  b);                                                 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

How to configure log4j to only keep log files for the last seven days?

I assume you're using RollingFileAppender? In which case, it has a property called MaxBackupIndex which you can set to limit the number of files. For example:

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

recursively use scp but excluding some folders

You can specify GLOBIGNORE and use the pattern *

GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir

You may wish to have general rules which you combine or override by using export GLOBIGNORE, but for ad-hoc usage simply the above will do. The : character is used as delimiter for multiple values.

How can you remove all documents from a collection with Mongoose?

DateTime.remove({}, callback) The empty object will match all of them.

How do I install cURL on cygwin?

In order to install any package,we must first find the setup.exe file.I could not locate this file.so i downloaded this file (or you can do a wget).I am on windows64 bit.So ,if you go to https://cygwin.com/install.html ,you can download setup-x86_64.exe file from the install and updates section,move this setup-x86_64.exe to your c:/cygwin64,and then run it from there ( setup-x86_64.exe -q -P curl)

How can I remove time from date with Moment.js?

The correct way would be to specify the input as per your requirement which will give you more flexibility.

The present definition includes the following

LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A'

You can use any of these or change the input passed into moment().format(). For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').

Resource files not found from JUnit test cases

This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.

You can verify that by checking your effective POM using this command

mvn help:effective-pom

    <finalName>name</finalName>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>

For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.

    <resources>
        <resource>
            <directory>/home/josh/desktop/app_resources</directory>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>/home/josh/desktop/test_resources</directory>
        </testResource>
    </testResources>

jQuery: Check if button is clicked

try something like :

var focusout = false;

$("#Button1").click(function () {
    if (focusout == true) {
        focusout = false;
        return;
    }
    else {
        GetInfo();
    }
});

$("#Text1").focusout(function () {
    focusout = true;
    GetInfo();
});

Error inflating when extending a class

in my case I added such cyclic resource:

<drawable name="above_shadow">@drawable/above_shadow</drawable>

then changed to

<drawable name="some_name">@drawable/other_name</drawable>

and it worked

SQL Query Multiple Columns Using Distinct on One Column Only

select * from 
(select 
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1

How many threads is too many?

ryeguy, I am currently developing a similar application and my threads number is set to 15. Unfortunately if I increase it at 20, it crashes. So, yes, I think the best way to handle this is to measure whether or not your current configuration allows more or less than a number X of threads.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

How can I load storyboard programmatically from class?

The extension below will allow you to load a Storyboard and it's associated UIViewController. Example: If you have a UIViewController named ModalAlertViewController and a storyboard named "ModalAlert" e.g.

let vc: ModalAlertViewController = UIViewController.loadStoryboard("ModalAlert")

Will load both the Storyboard and UIViewController and vc will be of type ModalAlertViewController. Note Assumes that the storyboard's Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.

extension UIViewController {
    /// Loads a `UIViewController` of type `T` with storyboard. Assumes that the storyboards Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
    /// - Parameter storyboardName: Name of the storyboard without .xib/nib suffix.
    static func loadStoryboard<T: UIViewController>(_ storyboardName: String) -> T? {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        if let vc = storyboard.instantiateViewController(withIdentifier: storyboardName) as? T {
            vc.loadViewIfNeeded() // ensures vc.view is loaded before returning
            return vc
        }
        return nil
    }
}

How to read from stdin line by line in Node

if you want to ask the user number of lines first:

_x000D_
_x000D_
    //array to save line by line 
    let xInputs = [];

    const getInput = async (resolve)=>{
            const readline = require('readline').createInterface({
                input: process.stdin,
                output: process.stdout,
            });
            readline.on('line',(line)=>{
            readline.close();
            xInputs.push(line);
            resolve(line);
            })
    }

    const getMultiInput = (numberOfInputLines,callback)=>{
        let i = 0;
        let p = Promise.resolve(); 
        for (; i < numberOfInputLines; i++) {
            p = p.then(_ => new Promise(resolve => getInput(resolve)));
        }
        p.then(()=>{
            callback();
        });
    }

    //get number of lines 
    const readline = require('readline').createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false
    });
    readline.on('line',(line)=>{
        getMultiInput(line,()=>{
           //get here the inputs from xinputs array 
        });
        readline.close();
    })
_x000D_
_x000D_
_x000D_

Convert list to array in Java

You can use toArray() api as follows,

ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);

Values from the array are,

for(String value : stringList)
{
    System.out.println(value);
}

Inserting a value into all possible locations in a list

Use insert() to insert an element before a given position.

For instance, with

arr = ['A','B','C']
arr.insert(0,'D')

arr becomes ['D','A','B','C'] because D is inserted before the element at index 0.

Now, for

arr = ['A','B','C']
arr.insert(4,'D')

arr becomes ['A','B','C','D'] because D is inserted before the element at index 4 (which is 1 beyond the end of the array).

However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.

Here's some example code:

import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
    print perm

will print out

('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

How to unmount a busy device

Just in case someone has the same pb. :

I couldn't unmount the mount point (here /mnt) of a chroot jail.

Here are the commands I typed to investigate :

$ umount /mnt
umount: /mnt: target is busy.
$ df -h | grep /mnt
/dev/mapper/VGTout-rootFS  4.8G  976M  3.6G  22% /mnt
$ fuser -vm /mnt/
                     USER        PID ACCESS COMMAND
/mnt:                root     kernel mount /mnt
$ lsof +f -- /dev/mapper/VGTout-rootFS
$

As you can notice, even lsof returns nothing.

Then I had the idea to type this :

$ df -ah | grep /mnt
/dev/mapper/VGTout-rootFS  4.8G  976M  3.6G  22% /mnt
dev                        2.9G     0  2.9G   0% /mnt/dev
$ umount /mnt/dev
$ umount /mnt
$ df -ah | grep /mnt
$

Here it was a /mnt/dev bind to /dev that I had created to be able to repair my system inside from the chroot jail.

After umounting it, my pb. is now solved.

Git remote branch deleted, but still it appears in 'branch -a'

Use:

git remote prune <remote>

Where <remote> is a remote source name like origin or upstream.

Example: git remote prune origin

$on and $broadcast in angular

If you want to $broadcast use the $rootScope:

$scope.startScanner = function() {

    $rootScope.$broadcast('scanner-started');
}

And then to receive, use the $scope of your controller:

$scope.$on('scanner-started', function(event, args) {

    // do what you want to do
});

If you want you can pass arguments when you $broadcast:

$rootScope.$broadcast('scanner-started', { any: {} });

And then receive them:

$scope.$on('scanner-started', function(event, args) {

    var anyThing = args.any;
    // do what you want to do
});

Documentation for this inside the Scope docs.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

First thing Correctly specify all settings in the .ENV file for Mail.

I LOST 6 HOURS FOR THIS

Example

MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password //Create password for Apps in settings. NOT PASTE YOUR REAL MAIL PASSWORD
MAIL_ENCRYPTION=SSL
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

How to change default language for SQL Server?

Please try below:

DECLARE @Today DATETIME;  
SET @Today = '12/5/2007';  

SET LANGUAGE Italian;  
SELECT DATENAME(month, @Today) AS 'Month Name';  

SET LANGUAGE us_english;  
SELECT DATENAME(month, @Today) AS 'Month Name' ;  
GO  

Reference:

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

Measure string size in Bytes in php

PHP's strlen() function returns the number of ASCII characters.

strlen('borsc') -> 5 (bytes)

strlen('boršc') -> 7 (bytes)

$limit_in_kBytes = 20000;

$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
    $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
    // here you can handle (0 - n) parts of string
    $pointer++;
}

$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string

.. or you can use a function like this:

function parseStrToArr($string, $limit_in_kBytes){
    $ret = array();

    $pointer = 0;
    while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
        $ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
        $pointer++;
    }

    $ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);

    return $ret;
}

$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);

Insert variable values in the middle of a string

String.Format("Hi We have these flights for you: {0}. Which one do you want",
                              flights);

EDIT: you can even save the "template" string separately (for instance you could store it in a configuration file and retrieve it from there), like this:

string flights = "Flight A, B,C,D";

string template = @"Hi We have these flights for you: {0}. Which one do you want";
Console.WriteLine(String.Format(template, flights));

EDIT2: whoops, sorry I see that @DanPuzey had already suggested something very similar to my EDIT (but somewhat better)

jQuery $.ajax request of dataType json will not retrieve data from PHP script

I think I know this one...

Try sending your JSON as JSON by using PHP's header() function:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header.

jQuery used to be fine without the header, but it was changed a few versions back.

ALSO

Be sure that your script is returning valid JSON. Use Firebug or Google Chrome's Developer Tools to check the request's response in the console.

UPDATE

You will also want to update your code to sanitize the $_POST to avoid sql injection attacks. As well as provide some error catching.

if (isset($_POST['get_member'])) {

    $member_id = mysql_real_escape_string ($_POST["get_member"]);

    $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';";

    if ($result = mysql_query( $query )) {

       $row = mysql_fetch_array($result);

       $type = $row['type'];
       $name = $row['name'];
       $fname = $row['fname'];
       $lname = $row['lname'];
       $email = $row['email'];
       $phone = $row['phone'];
       $website = $row['website'];
       $image = $row['image'];

       /* JSON Row */
       $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

    } else {

        /* Your Query Failed, use mysql_error to report why */
        $json = array('error' => 'MySQL Query Error');

    }

     /* Send as JSON */
     header("Content-Type: application/json", true);

    /* Return JSON */
    echo json_encode($json);

    /* Stop Execution */
    exit;

}

C# go to next item in list based on if statement in foreach

Use continue; instead of break; to enter the next iteration of the loop without executing any more of the contained code.

foreach (Item item in myItemsList)
{
   if (item.Name == string.Empty)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
      continue;
   }

   if (item.Weight > 100)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
      continue;
   }
}

Official docs are here, but they don't add very much color.

How to label each equation in align environment?

\tag also works in align*. Example:

\begin{align*}
  a(x)^{2} &= bx\tag{1}\\ 
  a(x)^{2} &= b\tag{2}\\ 
  ax &= b\tag{3}\\ 
  a(x)^{2}+bx &= c\tag{4}\\ 
  a(x)^{2}+c &= bx\tag{5}\\ 
  a(x)^{2} &= bx+c\tag{6}\\ \\ 
  Where\quad a, b, c \, \in N
\end{align*}

Output:

PDF output for \tag example

Do subclasses inherit private fields?

No, private fields are not inherited. The only reason is that subclass can not access them directly.

Setting Column width in Apache POI

With Scala there is a nice Wrapper spoiwo

You can do it like this:

Workbook(mySheet.withColumns(
      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))
    )

How to install SimpleJson Package for Python

Really simple way is:

pip install simplejson

CAST DECIMAL to INT

Try cast (columnName as unsigned)

unsigned is positive value only

If you want to include negative value, then cast (columnName as signed),
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)

Is there a way to make mv create the directory to be moved to if it doesn't exist?

Making use of the tricks in "Getting the last argument passed to a shell script" we can make a simple shell function that should work no matter how many files you want to move:

# Bash only
mvdir() { mkdir -p "${@: -1}" && mv "$@"; }

# Other shells may need to search for the last argument
mvdir() { for last; do true; done; mkdir -p "$last" && mv "$@"; }

How to implement band-pass Butterworth filter with Scipy.signal.butter

You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high] (expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band".

Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

Tests not running in Test Explorer

In my case I had an async void Method and I replaced with async Task ,so the test run as i expected :

    [TestMethod]
    public async  void SendTest(){}

replace with :

    [TestMethod]
    public async  Task SendTest(){}

How to count items in JSON object using command line?

A simple solution is to install jshon library :

jshon -l < /tmp/test.json
2

What's the difference between StaticResource and DynamicResource in WPF?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

What's the difference between ViewData and ViewBag?

viewdata: is a dictionary used to store data between View and controller , u need to cast the view data object to its corresponding model in the view to be able to retrieve data from it ...

ViewBag: is a dynamic property similar in its working to the view data, However it is better cuz it doesn't need to be casted to its corressponding model before using it in the view ...

R legend placement in a plot

You have to add the size of the legend box to the ylim range

#Plot an empty graph and legend to get the size of the legend
x <-1:10
y <-11:20
plot(x,y,type="n", xaxt="n", yaxt="n")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"),plot = FALSE)

#custom ylim. Add the height of legend to upper bound of the range
my.range <- range(y)
my.range[2] <- 1.04*(my.range[2]+my.legend.size$rect$h)

#draw the plot with custom ylim
plot(x,y,ylim=my.range, type="l")
my.legend.size <-legend("topright",c("Series1","Series2","Series3"))

enter image description here

How can you undo the last git add?

You could use git reset (see docs)

Getting first and last day of the current month

Try this code it is already built in c#

int lastDay = DateTime.DaysInMonth (2014, 2);

and the first day is always 1.

Good Luck!

How can I search sub-folders using glob.glob module?

As pointed out by Martijn, glob can only do this through the **operator introduced in Python 3.5. Since the OP explicitly asked for the glob module, the following will return a lazy evaluation iterator that behaves similarly

import os, glob, itertools

configfiles = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.txt'))
                         for root, dirs, files in os.walk('C:/Users/sam/Desktop/file1/'))

Note that you can only iterate once over configfiles in this approach though. If you require a real list of configfiles that can be used in multiple operations you would have to create this explicitly by using list(configfiles).

bootstrap popover not showing on top of all elements

I just had a situation that was similar to this, involving the DataTables JQuery library with scrolling enabled.

What turned out to be had nothing to do with Z-indices, but with one of the enclosing divs having the CSS overflow property set as hidden.

I fixed it by adding an event to my element triggering the popover which also changed the overflow property of the responsible div to visible.

How to put text over images in html?

You can create a div with the exact same size as the image.

<div class="imageContainer">Some Text</div>

use the css background-image property to show the image

 .imageContainer {
       width:200px; 
       height:200px; 
       background-image: url(locationoftheimage);
 }

more here

note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.

How to skip the OPTIONS preflight request?

setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation

$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);

How to get the file name from a full path using JavaScript?

I use:

var lastPart = path.replace(/\\$/,'').split('\\').pop();

It replaces the last \ so it also works with folders.

How to break out of nested loops?

I note that the question is simply, "Is there any other way to break all of the loops?" I don't see any qualification but that it not be goto, in particular the OP didn't ask for a good way. So, how about we longjmp out of the inner loop? :-)

#include <stdio.h>
#include <setjmp.h>

int main(int argc, char* argv[]) {
  int counter = 0;
  jmp_buf look_ma_no_goto;
  if (!setjmp(look_ma_no_goto)) {
    for (int i = 0; i < 1000; i++) {
      for (int j = 0; j < 1000; j++) {
        if (i == 500 && j == 500) {
          longjmp(look_ma_no_goto, 1);
        }
        counter++;
      }
    }
  }
  printf("counter=%d\n", counter);
}

The setjmp function returns twice. The first time, it returns 0 and the program executes the nested for loops. Then when the both i and j are 500, it executes longjmp, which causes setjmp to return again with the value 1, skipping over the loop.

Not only will longjmp get you out of nested loops, it works with nested functions too!

How to update/modify an XML file in python?

While I agree with Tim and Oben Sonne that you should use an XML library, there are ways to still manipulate it as a simple string object.

I likely would not try to use a single file pointer for what you are describing, and instead read the file into memory, edit it, then write it out.:

inFile = open('file.xml', 'r')
data = inFile.readlines()
inFile.close()
# some manipulation on `data`
outFile = open('file.xml', 'w')
outFile.writelines(data)
outFile.close()

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

There are two steps to fix this.

First edit phpMyAdmin/libraries/DatabaseInterface.class.php

Change:

    if (PMA_MYSQL_INT_VERSION >  50503) {
        $default_charset = 'utf8mb4';
        $default_collation = 'utf8mb4_general_ci';
    } else {
        $default_charset = 'utf8';
        $default_collation = 'utf8_general_ci';
    }

To:

    //if (PMA_MYSQL_INT_VERSION >  50503) {
    //    $default_charset = 'utf8mb4';
    //    $default_collation = 'utf8mb4_general_ci';
    //} else {
        $default_charset = 'utf8';
        $default_collation = 'utf8_general_ci';
    //}

Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.

Then restart your phpMyAdmin.

(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)

How to change port for jenkins window service when 8080 is being used

In linux,

sudo vi /etc/sysconfig/jenkins

set following configuration with any available port

JENKINS_PORT="8082"

Error 500: Premature end of script headers

Check your line endings! If you see an error about the file not being found, followed by this "premature of end headers" error in your Apache log - it may be that you have Windows line endings in your script in instead of Unix style. I ran into that problem / solution.

What is the behavior of integer division?

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

Duplicate Entire MySQL Database

To remote server

mysqldump mydbname | ssh host2 "mysql mydbcopy"

To local server

mysqldump mydbname | mysql mydbcopy

convert iso date to milliseconds in javascript

Another solution could be to use Number object parser like this:

_x000D_
_x000D_
let result = Number(new Date("2012-02-10T13:19:11+0000"));_x000D_
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();_x000D_
console.log(result);_x000D_
console.log(resultWithGetTime);
_x000D_
_x000D_
_x000D_

This converts to milliseconds just like getTime() on Date object

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.

Resolution:

The directory /usr/include/c++/4.4.6/x86_64-redhat-linux was missing.

I did the following:

cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32

I'm now able to compile 32bit binaries on a 64bit OS.

Pass a String from one Activity to another Activity in Android

Post Value from

Intent ii = new Intent(this, GameStartPage.class);

// ii.putExtra("pkgName", B2MAppsPKGName);

ii.putExtra("pkgName", YourValue);
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(ii);

Get Value from

pkgn = getIntent().getExtras().getString("pkgName");

How much faster is C++ than C#?

It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.

I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.

#include "stdafx.h"

using namespace System;
using namespace System::Diagnostics;

bool EqualMe(String^ first, String^ second)
{
    return first->Equals(second);
}
int main(array<String ^> ^args)
{
    Stopwatch^ sw = gcnew Stopwatch();
    sw->Start();
    for (int i = 0; i < 100000; i++)
    {
        EqualMe(L"one", L"two");
    }
    sw->Stop();
    Console::WriteLine(sw->ElapsedTicks);
    return 0;
}

In Python, how do I iterate over a dictionary in sorted key order?

Greg's answer is right. Note that in Python 3.0 you'll have to do

sorted(dict.items())

as iteritems will be gone.

Add a new item to a dictionary in Python

It occurred to me that you may have actually be asking how to implement the + operator for dictionaries, the following seems to work:

>>> class Dict(dict):
...     def __add__(self, other):
...         copy = self.copy()
...         copy.update(other)
...         return copy
...     def __radd__(self, other):
...         copy = other.copy()
...         copy.update(self)
...         return copy
... 
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}

Note that this is more overhead then using dict[key] = value or dict.update(), so I would recommend against using this solution unless you intend to create a new dictionary anyway.

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

In my case it was a Chrome extension and Firefox add-on by Avira called "Avira Browser Safety". I had problems with version 1.7.4. In my specific case I wanted to login to a website called gliffy.com for making diagrams, but after logging in I got an blank page. If you use F12 (console) in Chrome you can see all these ERR_BLOCKED_BY_CLIENT (and other) errors.

Git ignore file for Xcode projects

A Structure of a standerd .gitignore file for Xcode project >

.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
!default.xcworkspace
xcuserdata
profile
*.moved-aside
DerivedData
.idea/

Limiting double to 3 decimal places

double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));

Hide div by default and show it on click with bootstrap

Just add water style="display:none"; to the <div>

Fiddles I say: http://jsfiddle.net/krY56/13/

jQuery:

function toggler(divId) {
    $("#" + divId).toggle();
}

Preferred to have a CSS Class .hidden

.hidden {
     display:none;
}

How do I get the value of a textbox using jQuery?

There's a .val() method:

If you've got an input with an id of txtEmail you can use the following code to access the value of the text box:

$("#txtEmail").val()

You can also use the val(string) method to set that value:

$("#txtEmail").val("something")

Source file not compiled Dev C++

You can always try doing it manually from the command prompt. Navigate to the path of the file and type:

gcc filename.c -o filename

Set JavaScript variable = null, or leave undefined?

The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.

if(a === null) {

}

...is not the same as:

if(a === undefined) {

}

That said, a == null && a == undefined will return true.

Fiddle

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 

C#:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

how to remove json object key and value.?

I had issues with trying to delete a returned JSON object and found that it was actually a string. If you JSON.parse() before deleting you can be sure your key will get deleted.

let obj;
console.log(this.getBody()); // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = this.getBody();
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805,"BRL":4.0851}
obj = JSON.parse(this.getBody());
delete obj["BRL"];
console.log(obj) // {"AED":3.6729,"AZN":1.69805}

How to get the body's content of an iframe in Javascript?

To get body content from javascript ,i have tried the following code:

var frameObj = document.getElementById('id_description_iframe');

var frameContent = frameObj.contentWindow.document.body.innerHTML;

where "id_description_iframe" is your iframe's id. This code is working fine for me.

How to change the spinner background in Android?

As Jakob pointed out, android:popupBackground is the key attribute for the dropdown (opened state of the Spinner), but instead of using just a colour, I got the best results with a 9-patch drawable like this:

enter image description here
menu_dropdown_panel.9.png

Note that it's very easy to generate this 9-patch image for the background colour of your choice, for example using this online tool as I explained in this answer!

So, my Spinner XML definition looks like:

<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/navigationBlue"
    android:spinnerMode="dropdown"
    android:popupBackground="@drawable/menu_dropdown_panel"
    />

And the result:

(For custom fonts, as in the screenshot above, a custom SpinnerAdapter is needed too.)

Works at least on Android 4.0+ (API level 14+).

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Try with:

eval $(aws ecr get-login --no-include-email | sed 's|https://||')

before push.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

How do I view the SQL generated by the Entity Framework?

I am doing integration test, and needed this to debug the generated SQL statement in Entity Framework Core 2.1, so I use DebugLoggerProvider or ConsoleLoggerProvider like so:

[Fact]
public async Task MyAwesomeTest
    {
        //setup log to debug sql queries
        var loggerFactory = new LoggerFactory();
        loggerFactory.AddProvider(new DebugLoggerProvider());
        loggerFactory.AddProvider(new ConsoleLoggerProvider(new ConsoleLoggerSettings()));

        var builder = new DbContextOptionsBuilder<DbContext>();
        builder
            .UseSqlServer("my connection string") //"Server=.;Initial Catalog=TestDb;Integrated Security=True"
            .UseLoggerFactory(loggerFactory);

        var dbContext = new DbContext(builder.Options);

        ........

Here is a sample output from Visual Studio console:

Sample SQL statement output

Can HTML be embedded inside PHP "if" statement?

I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.

In the php

<?php 
  $var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';

  if ($var1 == 'Alice') {
    $html = file_get_contents('/path/to/file.html'); //get the html template
    $template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
    $template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
    $html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
  }

  echo $html_output;
?>

In the html (/path/to/file.html)

<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>

The output of this would be:

Alice ate apples for lunch with Bob.

How to include layout inside layout?

Use <include /> tag.

          <include 
            android:id="@+id/some_id_if_needed"
            layout="@layout/some_layout"/>

Also, read Creating Reusable UI Components and Merging Layouts articles.

IndentationError: unexpected indent error

This error occur when you don't correctly write blocks. Forgetting a ":", or not using "Tab" button for blocks and use spaces. When you are transporting a code from one editor to another editor,it can happen. And never forget this: errors aren't always on that line. I came here for this, but I've forgotten an except after a try. because of my unstandard editor, it happend. But it's possible in normal editor.

Make an html number input always display 2 decimal places

The accepted solution here is incorrect. Try this in the HTML:

onchange="setTwoNumberDecimal(this)" 

and the function to look like:

 function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };

CSS3 transition doesn't work with display property

max-height

.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}

.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}

https://www.codehive.io/boards/bUoLvRg

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

Changing Node.js listening port

you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me

backendSettings = {
"scheme":"https / http ",
"host":"Your website url",
"port":49165, //port number 
'sslKeyPath': 'Path for key',
'sslCertPath': 'path for SSL certificate',
'sslCAPath': '',
"resource":"/socket.io",
"baseAuthPath": '/nodejs/',
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":443,
"scheme": 'https / http', //whatever is your website scheme
"host":"host name",
"messagePath":"/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":false,
"addUserToChannelUrl": 'user/channel/add/:channel/:uid',
"publishMessageToContentChannelUrl": 'content/token/message',
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};

In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port. For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts

link_to image tag. how to add class to a tag

Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)

<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>

Hope this helps!

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

How to do a PUT request with curl?

curl -X PUT -d 'new_value' URL_PATH/key

where,

X - option to be used for request command

d - option to be used in order to put data on remote url

URL_PATH - remote url

new_value - value which we want to put to the server's key

How can I get the console logs from the iOS Simulator?

iOS 8 and iOS 9

Under iOS 8 and iOS 9 this location is now:

~/Library/Logs/CoreSimulator/<DEVICE_CODE>

So, the following will work:

tail -f ~/Library/Logs/CoreSimulator/<DEVICE_CODE>/system.log

The DEVICE_CODE value can be found via the following console command:

instruments -s devices

simulate background-size:cover on <video> or <img>

The other answers were good but they involve javascript or they doesn't center the video horizontally AND vertically.

You can use this full CSS solution to have a video that simulate the background-size: cover property:

  video {
    position: fixed;           // Make it full screen (fixed)
    right: 0;
    bottom: 0;
    z-index: -1;               // Put on background

    min-width: 100%;           // Expand video
    min-height: 100%;
    width: auto;               // Keep aspect ratio
    height: auto;

    top: 50%;                  // Vertical center offset
    left: 50%;                 // Horizontal center offset

    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);         // Cover effect: compensate the offset

    background: url(bkg.jpg) no-repeat;      // Background placeholder, not always needed
    background-size: cover;
  }

Convert Select Columns in Pandas Dataframe to Numpy Array

The best way for converting to Numpy Array is using '.to_numpy(self, dtype=None, copy=False)'. It is new in version 0.24.0.Refrence

You can also use '.array'.Refrence

Pandas .as_matrix deprecated since version 0.23.0.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

How can I check the extension of a file?

Use pathlib From Python3.4 onwards.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'

How to focus on a form input text field on page load using jQuery?

Sorry for bumping an old question. I found this via google.

Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.

eg.

$('#myform input,#myform textarea').first().focus();

This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.

Compute a confidence interval from sample data

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module:

from statistics import NormalDist

def confidence_interval(data, confidence=0.95):
  dist = NormalDist.from_samples(data)
  z = NormalDist().inv_cdf((1 + confidence) / 2.)
  h = dist.stdev * z / ((len(data) - 1) ** .5)
  return dist.mean - h, dist.mean + h

This:

  • Creates a NormalDist object from the data sample (NormalDist.from_samples(data), which gives us access to the sample's mean and standard deviation via NormalDist.mean and NormalDist.stdev.

  • Compute the Z-score based on the standard normal distribution (represented by NormalDist()) for the given confidence using the inverse of the cumulative distribution function (inv_cdf).

  • Produces the confidence interval based on the sample's standard deviation and mean.


This assumes the sample size is big enough (let's say more than ~100 points) in order to use the standard normal distribution rather than the student's t distribution to compute the z value.

Which maven dependencies to include for spring 3.0?

Since this questions seems to still get quite a lot of views, it might be useful to note that for Spring 4+ it's easiest to start using Spring Boot and the Spring Boot starter POMs.

Using Spring Boot there's less dependencies to manage (and thus fewer conflicts), and setting up a working, well integrated Spring Context is a whole lot easier. I highly recommend it.

How to get the ASCII value of a character

From here:

The function ord() gets the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick.

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'
>>>

In Python 2, there was also the unichr function, returning the Unicode character whose ordinal is the unichr argument:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3 you can use chr instead of unichr.


ord() - Python 3.6.5rc1 documentation

ord() - Python 2.7.14 documentation

How to give a user only select permission on a database

You can use Create USer to create a user

CREATE LOGIN sam
    WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO 

and to Grant (Read-only access) you can use the following

GRANT SELECT TO sam

Hope that helps.

how to clear JTable

Basically, it depends on the TableModel that you are using for your JTable. If you are using the DefaultTableModel then you can do it in two ways:

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed

or

DefaultTableModel dm = (DefaultTableModel)table.getModel();
while(dm.getRowCount() > 0)
{
    dm.removeRow(0);
}

See the JavaDoc of DefaultTableModel for more details

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.


Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() + Series.map()

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:

df.Date.map(df.groupby('Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot

perfplot.show(
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
    kernels=[
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:  df.A.map(df.groupby('A')['B'].sum()),
    ],
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],
    xlabel='N',
    logy=True,
    logx=True
)

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Delete item from array and shrink array

without using the System.arraycopy method you can delete an element from an array with the following

    int i = 0;
    int x = 0;
    while(i < oldArray.length){
        if(oldArray[i] == 3)i++;

        intArray[x] = oldArray[i];
        i++;
        x++;
    }

where 3 is the value you want to remove.

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

How to append to New Line in Node.js

It looks like you're running this on Windows (given your H://log.txt file path).

Try using \r\n instead of just \n.

Honestly, \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

Spring 3 MVC resources and tag <mvc:resources />

Different order make it works :)

<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />

What is the difference between function and procedure in PL/SQL?

In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.

how to align text vertically center in android

just use like this to make anything to center

 android:layout_gravity="center"
 android:gravity="center"

updated :

android:layout_gravity="center|right"
android:gravity="center|right"

Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView

<LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"  >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center" 
            android:gravity="center|right"
            android:text="hello" 
            android:textSize="20dp" />
    </LinearLayout>

How to set default values in Rails?

If you are referring to ActiveRecord objects, you have (more than) two ways of doing this:

1. Use a :default parameter in the DB

E.G.

class AddSsl < ActiveRecord::Migration
  def self.up
    add_column :accounts, :ssl_enabled, :boolean, :default => true
  end

  def self.down
    remove_column :accounts, :ssl_enabled
  end
end

More info here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

2. Use a callback

E.G. before_validation_on_create

More info here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002147

What is the difference between Promises and Observables?

Even though this answer is late, i have summarized the differences below,

Observable:

  1. Observable is just a function that takes an observer and returns a function Observer: an object with next, error.
  2. Observer allows to subscribe/unsubscribe to its data stream, emit next value to the observer, notify the observer about errors and inform the observer about the stream completion
  3. Observer provides a function to handle next value,errors and end of stream(ui events,http responses,data with web sockets).
  4. Works with multiple values over time
  5. It is cancel-able/retry-able and supports operators such as map,filter,reduce etc.
  6. Creating an Observable can be -Observable.create() - returns Observable that can invoke methods on -Observer Observable.from() - converts an array or iterable into -Observable Observable.fromEvent() - converts an event into Observable -Observable.fromPromise() - converts a Promise into Observable -Observable.range() - returns a sequence of integers in the speci?ed range

Promise:

  1. A promise represents a task that will finish in the future;

  2. Promises become resolved by a value;

  3. Promises get rejected by exceptions;

  4. Not cancellable and it returns a single value

  5. A promise expose a function (then)

    -then returns a new promise;

    -allows for the attachment of that will be executed based on state;

    -handlers are guaranteed to execute in order attached;

Horizontal scroll css?

use max-width instead of width

max-width:530px;

demo:http://jsfiddle.net/FPBWr/161/

Align button to the right

Maybe you can use float:right;:

_x000D_
_x000D_
.one {_x000D_
  padding-left: 1em;_x000D_
  text-color: white;_x000D_
   display:inline; _x000D_
}_x000D_
.two {_x000D_
  background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
  float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
 _x000D_
  </head>_x000D_
  <body>_x000D_
      <div class="row">_x000D_
       <h3 class="one">Text</h3>_x000D_
       <button class="btn btn-secondary pull-right">Button</button>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Node: log in a file instead of the console

If you are looking for something in production winston is probably the best choice.

If you just want to do dev stuff quickly, output directly to a file (I think this works only for *nix systems):

nohup node simple-server.js > output.log &

How to select a div element in the code-behind page?

@CarlosLanderas is correct depending on where you've placed the DIV control. The DIV by the way is not technically an ASP control, which is why you cannot find it directly like other controls. But the best way around this is to turn it into an ASP control.

Use asp:Panel instead. It is rendered into a <div> tag anyway...

<asp:Panel id="divSubmitted" runat="server" style="text-align:center" visible="false">
   <asp:Label ID="labSubmitted" runat="server" Text="Roll Call Submitted"></asp:Label>
</asp:Panel>

And in code behind, simply find the Panel control as per normal...

Panel DivCtl1 = (Panel)gvRollCall.FooterRow.FindControl("divSubmitted");
if (DivCtl1 != null)
    DivCtl1.Visible = true;

Please note that I've used FooterRow, as my "psuedo div" is inside the footer row of a Gridview control.

Good coding!

Convert .pem to .crt and .key

This is what I did on windows.

  1. Download a zip file that contains the open ssl exe from Google
  2. Unpack the zip file and go into the bin folder.
  3. Go to the address bar in the bin folder and type cmd. This will open a command prompt at this folder.
  4. move/Put the .pem file into this bin folder.
  5. Run two commands. One creates the cert and the second the key file
openssl x509 -outform der -in yourPemFilename.pem -out certfileOutName.crt
openssl rsa -in yourPemFilename.pem -out keyfileOutName.key

Creating a JSON Array in node js

This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });

Call a REST API in PHP

Use Guzzle. It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.

Here's an example from the Web site:

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
    'auth' =>  ['user', 'pass']
]);
echo $res->getStatusCode();           // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();                 // {"type":"User"...'
var_export($res->json());             // Outputs the JSON decoded data

How to convert timestamp to datetime in MySQL?

SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

How do I get interactive plots again in Spyder/IPython/matplotlib?

After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel enter image description here

And you will surely get Interactive Plot. Happy Coding!

Does Java support structs?

With Project JUnion you can use structs in Java by annotating a class with @Struct annotation

@Struct
class Member {
  string FirstName; 
  string LastName;  
  int BirthYear; 
}

More info at the project's website: https://tehleo.github.io/junion/

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

How do I select the parent form based on which submit button is clicked?

To get the form that the submit is inside why not just

this.form

Easiest & quickest path to the result.

Cannot edit in read-only editor VS Code

The easiest way to fix this was to press (CTRL) and (,) in VS Code to open Settings.

After that, on the search bar search for code runner, then scroll down and search for Run In Terminal and check that box as highlighted in the below image:

How to get a variable from a file to another file in Node.js

You need module.exports:

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

Or you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

If all you want out of the file is variableName then

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):

Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.

  • For Node v13.9.0 and beyond, experimental modules are enabled by default
  • For versions of Node less than version 13.9.0, use --experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:

  • Files ending in .mjs.
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
  • Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.

Once you have it setup, you can use import and export.

Using the example above, there are two approaches you can take

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

What is the largest Safe UDP Packet Size on the Internet

512 is your best bet. It's used elsewhere and is a nice even number (half of 1024).

Phone number validation Android

Here is how you can do it succinctly in Kotlin:

fun String.isPhoneNumber() =
            length in 4..10 && all { it.isDigit() }

How to use makefiles in Visual Studio?

Makefiles and build files are about automating your build. If you use a script like MSBuild or NAnt, you can build your project or solution directly from command line. This in turn makes it possible to automate the build, have it run by a build server.

Besides building your solution it is typical that a build script includes task to run unit tests, report code coverage and complexity and more.

SQL Server equivalent to MySQL enum data type?

The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.

changing permission for files and folder recursively using shell command in mac

By using CHMOD yes:

For Recursive file:

chmod -R 777 foldername or pathname

For non recursive:

chmod 777 foldername or pathname

Write / add data in JSON file using Node.js

try

var fs = require("fs");
var sampleObject = { your data };

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {  console.error(err);  return; };
    console.log("File has been created");
});

Batch file include external file for variables

:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.

@ECHO OFF
SETLOCAL

REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"

REM Change variables
IF NOT DEFINED $RunCount (
    SET $RunCount=1
) ELSE SET /A $RunCount+=1

REM Display variables
SET $

REM Save variables
SET $>config.txt

ENDLOCAL
PAUSE
EXIT /B

Output:

$RunCount=1

$RunCount=2

$RunCount=3

The technique outlined above can also be used to share variables among multiple batch files.

Source: http://www.incodesystems.com/products/batchfi1.htm

Run a command over SSH with JSch

The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.

  /* 
  * SSHManager
  * 
  * @author cabbott
  * @version 1.0
  */
  package cabbott.net;

  import com.jcraft.jsch.*;
  import java.io.IOException;
  import java.io.InputStream;
  import java.util.logging.Level;
  import java.util.logging.Logger;

  public class SSHManager
  {
  private static final Logger LOGGER = 
      Logger.getLogger(SSHManager.class.getName());
  private JSch jschSSHChannel;
  private String strUserName;
  private String strConnectionIP;
  private int intConnectionPort;
  private String strPassword;
  private Session sesConnection;
  private int intTimeOut;

  private void doCommonConstructorActions(String userName, 
       String password, String connectionIP, String knownHostsFileName)
  {
     jschSSHChannel = new JSch();

     try
     {
        jschSSHChannel.setKnownHosts(knownHostsFileName);
     }
     catch(JSchException jschX)
     {
        logError(jschX.getMessage());
     }

     strUserName = userName;
     strPassword = password;
     strConnectionIP = connectionIP;
  }

  public SSHManager(String userName, String password, 
     String connectionIP, String knownHostsFileName)
  {
     doCommonConstructorActions(userName, password, 
                connectionIP, knownHostsFileName);
     intConnectionPort = 22;
     intTimeOut = 60000;
  }

  public SSHManager(String userName, String password, String connectionIP, 
     String knownHostsFileName, int connectionPort)
  {
     doCommonConstructorActions(userName, password, connectionIP, 
        knownHostsFileName);
     intConnectionPort = connectionPort;
     intTimeOut = 60000;
  }

  public SSHManager(String userName, String password, String connectionIP, 
      String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
  {
     doCommonConstructorActions(userName, password, connectionIP, 
         knownHostsFileName);
     intConnectionPort = connectionPort;
     intTimeOut = timeOutMilliseconds;
  }

  public String connect()
  {
     String errorMessage = null;

     try
     {
        sesConnection = jschSSHChannel.getSession(strUserName, 
            strConnectionIP, intConnectionPort);
        sesConnection.setPassword(strPassword);
        // UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
        // sesConnection.setConfig("StrictHostKeyChecking", "no");
        sesConnection.connect(intTimeOut);
     }
     catch(JSchException jschX)
     {
        errorMessage = jschX.getMessage();
     }

     return errorMessage;
  }

  private String logError(String errorMessage)
  {
     if(errorMessage != null)
     {
        LOGGER.log(Level.SEVERE, "{0}:{1} - {2}", 
            new Object[]{strConnectionIP, intConnectionPort, errorMessage});
     }

     return errorMessage;
  }

  private String logWarning(String warnMessage)
  {
     if(warnMessage != null)
     {
        LOGGER.log(Level.WARNING, "{0}:{1} - {2}", 
           new Object[]{strConnectionIP, intConnectionPort, warnMessage});
     }

     return warnMessage;
  }

  public String sendCommand(String command)
  {
     StringBuilder outputBuffer = new StringBuilder();

     try
     {
        Channel channel = sesConnection.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        InputStream commandOutput = channel.getInputStream();
        channel.connect();
        int readByte = commandOutput.read();

        while(readByte != 0xffffffff)
        {
           outputBuffer.append((char)readByte);
           readByte = commandOutput.read();
        }

        channel.disconnect();
     }
     catch(IOException ioX)
     {
        logWarning(ioX.getMessage());
        return null;
     }
     catch(JSchException jschX)
     {
        logWarning(jschX.getMessage());
        return null;
     }

     return outputBuffer.toString();
  }

  public void close()
  {
     sesConnection.disconnect();
  }

  }

For testing.

  /**
     * Test of sendCommand method, of class SSHManager.
     */
  @Test
  public void testSendCommand()
  {
     System.out.println("sendCommand");

     /**
      * YOU MUST CHANGE THE FOLLOWING
      * FILE_NAME: A FILE IN THE DIRECTORY
      * USER: LOGIN USER NAME
      * PASSWORD: PASSWORD FOR THAT USER
      * HOST: IP ADDRESS OF THE SSH SERVER
     **/
     String command = "ls FILE_NAME";
     String userName = "USER";
     String password = "PASSWORD";
     String connectionIP = "HOST";
     SSHManager instance = new SSHManager(userName, password, connectionIP, "");
     String errorMessage = instance.connect();

     if(errorMessage != null)
     {
        System.out.println(errorMessage);
        fail();
     }

     String expResult = "FILE_NAME\n";
     // call sendCommand for each command and the output 
     //(without prompts) is returned
     String result = instance.sendCommand(command);
     // close only after all commands are sent
     instance.close();
     assertEquals(expResult, result);
  }

How to draw a graph in LaTeX?

In my experience, I always just use an external program to generate the graph (mathematica, gnuplot, matlab, etc.) and export the graph as a pdf or eps file. Then I include it into the document with includegraphics.

How to pass a PHP variable using the URL

In your link.php your echo statement must be like this:

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

How to get a resource id with a known resource name?

// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The difference is the amount of memory allocated to each integer, and how large a number they each can store.

Setting up maven dependency for SQL Server

Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.

https://stackoverflow.com/a/30111956/3368958

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to do this in Laravel, subquery where in

You can use variable by using keyword "use ($category_id)"

$category_id = array('223','15');
Products::whereIn('id', function($query) use ($category_id){
   $query->select('paper_type_id')
     ->from(with(new ProductCategory)->getTable())
     ->whereIn('category_id', $category_id )
     ->where('active', 1);
})->get();