Programs & Examples On #Control theory

Anything related to control theory, i.e. the branch of systems engineering studying the mathematical techniques used to make a dynamic system behave in some desirable way.

Why would you use Expression<Func<T>> rather than Func<T>?

LINQ is the canonical example (for example, talking to a database), but in truth, any time you care more about expressing what to do, rather than actually doing it. For example, I use this approach in the RPC stack of protobuf-net (to avoid code-generation etc) - so you call a method with:

string result = client.Invoke(svc => svc.SomeMethod(arg1, arg2, ...));

This deconstructs the expression tree to resolve SomeMethod (and the value of each argument), performs the RPC call, updates any ref/out args, and returns the result from the remote call. This is only possible via the expression tree. I cover this more here.

Another example is when you are building the expression trees manually for the purpose of compiling to a lambda, as done by the generic operators code.

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

How does the above for-each loop work?

Like many other array features, the JSL mentions arrays explicitly and gives them magical properties. JLS 7 14.14.2:

EnhancedForStatement:

    for ( FormalParameter : Expression ) Statement

[...]

If the type of Expression is a subtype of Iterable, then the translation is as follows

[...]

Otherwise, the Expression necessarily has an array type, T[]. [[ MAGIC! ]]

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    VariableModifiersopt TargetType Identifier = #a[#i];
    Statement
}

#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

Is the array converted to a list to get the iterator?

Let's javap it up:

public class ArrayForLoop {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        for (int i : arr)
            System.out.println(i);
    }
}

then:

javac ArrayForLoop.java
javap -v ArrayForLoop

main method with a bit of editing to make it easier to read:

 0: iconst_3
 1: newarray       int
 3: dup
 4: iconst_0
 5: iconst_1
 6: iastore
 7: dup
 8: iconst_1
 9: iconst_2
10: iastore
11: dup
12: iconst_2
13: iconst_3
14: iastore

15: astore_1
16: aload_1
17: astore_2
18: aload_2
19: arraylength
20: istore_3
21: iconst_0
22: istore        4

24: iload         4
26: iload_3
27: if_icmpge     50
30: aload_2
31: iload         4
33: iaload
34: istore        5
36: getstatic     #2    // Field java/lang/System.out:Ljava/io/PrintStream;
39: iload         5
41: invokevirtual #3    // Method java/io/PrintStream.println:(I)V
44: iinc          4, 1
47: goto          24
50: return

Breakdown:

  • 0 to 14: create the array
  • 15 to 22: prepare for the for loop. At 22, store integer 0 from stack into local position 4. THAT is the loop variable.
  • 24 to 47: the loop. The loop variable is retrieved at 31, and incremented at 44. When it equals the array length which is stored in local variable 3 on the check at 27, the loop ends.

Conclusion: it is the same as doing an explicit for loop with an index variable, no itereators involved.

Creating a simple login form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>Login Page</title>
      <style>
         /* Basics */
         html, body {
         width: 100%;
         height: 100%;
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         color: #444;
         -webkit-font-smoothing: antialiased;
         background: #f0f0f0;
         }
         #container {
         position: fixed;
         width: 340px;
         height: 280px;
         top: 50%;
         left: 50%;
         margin-top: -140px;
         margin-left: -170px;
         background: #fff;
         border-radius: 3px;
         border: 1px solid #ccc;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
         }
         form {
         margin: 0 auto;
         margin-top: 20px;
         }
         label {
         color: #555;
         display: inline-block;
         margin-left: 18px;
         padding-top: 10px;
         font-size: 14px;
         }
         p a {
         font-size: 11px;
         color: #aaa;
         float: right;
         margin-top: -13px;
         margin-right: 20px;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         p a:hover {
         color: #555;
         }
         input {
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         font-size: 12px;
         outline: none;
         }
         input[type=text],
         input[type=password] ,input[type=time]{
         color: #777;
         padding-left: 10px;
         margin: 10px;
         margin-top: 12px;
         margin-left: 18px;
         width: 290px;
         height: 35px;
         border: 1px solid #c7d0d2;
         border-radius: 2px;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         input[type=text]:hover,
         input[type=password]:hover,input[type=time]:hover {
         border: 1px solid #b6bfc0;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
         }
         input[type=text]:focus,
         input[type=password]:focus,input[type=time]:focus {
         border: 1px solid #a8c9e4;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
         }
         #lower {
         background: #ecf2f5;
         width: 100%;
         height: 69px;
         margin-top: 20px;
         box-shadow: inset 0 1px 1px #fff;
         border-top: 1px solid #ccc;
         border-bottom-right-radius: 3px;
         border-bottom-left-radius: 3px;
         }
         input[type=checkbox] {
         margin-left: 20px;
         margin-top: 30px;
         }
         .check {
         margin-left: 3px;
         font-size: 11px;
         color: #444;
         text-shadow: 0 1px 0 #fff;
         }
         input[type=submit] {
         float: right;
         margin-right: 20px;
         margin-top: 20px;
         width: 80px;
         height: 30px;
         font-size: 14px;
         font-weight: bold;
         color: #fff;
         background-color: #acd6ef; /*IE fallback*/
         background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         border-radius: 30px;
         border: 1px solid #66add6;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
         cursor: pointer;
         }
         input[type=submit]:hover {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         }
         input[type=submit]:active {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
         background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         }
      </style>
   </head>
   <body>
      <!-- Begin Page Content -->
      <div id="container">
         <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
               <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
               <input type="submit" value="Login">
            </div>
            <!--/ lower-->
         </form>
      </div>
      <!--/ container-->
      <!-- End Page Content -->
   </body>
</html>

Appending to 2D lists in Python

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)]

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]

What does the Java assert keyword do, and when should it be used?

Here's the most common use case. Suppose you're switching on an enum value:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
}

As long as you handle every case, you're fine. But someday, somebody will add fig to your enum and forget to add it to your switch statement. This produces a bug that may get tricky to catch, because the effects won't be felt until after you've left the switch statement. But if you write your switch like this, you can catch it immediately:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
  default:
    assert false : "Missing enum value: " + fruit;
}

How to select into a variable in PL/SQL when the result might be null?

I use this syntax for flexibility and speed -

    begin
    --
    with KLUJ as
    ( select 0 ROES from dual
       union 
      select count(*) from MY_TABLE where rownum = 1
    ) select max(ROES) into has_rows from KLUJ;
    --
    end;

Dual returns 1 row, rownum adds 0 or 1 rows, and max() groups to exactly 1. This gives 0 for no rows in a table and 1 for any other number of rows.

I extend the where clause to count rows by condition, remove rownum to count rows meeting a condition, and increase rownum to count rows meeting the condition up to a limit.

How to simulate "Press any key to continue?"

You can use the getchar routine.

From the above link:

/* getchar example : typewriter */
#include <stdio.h>

int main ()
{
  char c;
  puts ("Enter text. Include a dot ('.') in a sentence to exit:");
  do {
    c=getchar();
    putchar (c);
  } while (c != '.');
  return 0;
}

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

I experienced this while trying to clone from an enterprise repository, and simply restarting the terminal solved it for me.

Compare dates with javascript

you can done this way also.

if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {
        console.log("done");
}

OR

if (dateFormat(first, "mm-dd-yyyy") >  dateFormat(second, "mm-dd-yyyy")) {
        console.log("done");
}

i use following plugin for dateFormat()

        var dateFormat = function () {
        var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
            timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
            timezoneClip = /[^-+\dA-Z]/g,
            pad = function (val, len) {
                val = String(val);
                len = len || 2;
                while (val.length < len) val = "0" + val;
                return val;
            };

        // Regexes and supporting functions are cached through closure
        return function (date, mask, utc) {
            var dF = dateFormat;

            // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
            if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                mask = date;
                date = undefined;
            }

            // Passing date through Date applies Date.parse, if necessary
            date = date ? new Date(date) : new Date;
            if (isNaN(date)) throw SyntaxError("invalid date");

            mask = String(dF.masks[mask] || mask || dF.masks["default"]);

            // Allow setting the utc argument via the mask
            if (mask.slice(0, 4) == "UTC:") {
                mask = mask.slice(4);
                utc = true;
            }

            var _ = utc ? "getUTC" : "get",
                d = date[_ + "Date"](),
                D = date[_ + "Day"](),
                m = date[_ + "Month"](),
                y = date[_ + "FullYear"](),
                H = date[_ + "Hours"](),
                M = date[_ + "Minutes"](),
                s = date[_ + "Seconds"](),
                L = date[_ + "Milliseconds"](),
                o = utc ? 0 : date.getTimezoneOffset(),
                flags = {
                    d:    d,
                    dd:   pad(d),
                    ddd:  dF.i18n.dayNames[D],
                    dddd: dF.i18n.dayNames[D + 7],
                    m:    m + 1,
                    mm:   pad(m + 1),
                    mmm:  dF.i18n.monthNames[m],
                    mmmm: dF.i18n.monthNames[m + 12],
                    yy:   String(y).slice(2),
                    yyyy: y,
                    h:    H % 12 || 12,
                    hh:   pad(H % 12 || 12),
                    H:    H,
                    HH:   pad(H),
                    M:    M,
                    MM:   pad(M),
                    s:    s,
                    ss:   pad(s),
                    l:    pad(L, 3),
                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                    t:    H < 12 ? "a"  : "p",
                    tt:   H < 12 ? "am" : "pm",
                    T:    H < 12 ? "A"  : "P",
                    TT:   H < 12 ? "AM" : "PM",
                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                };

            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
            });
        };
    }();

    // Some common format strings
    dateFormat.masks = {
        "default":      "ddd mmm dd yyyy HH:MM:ss",
        shortDate:      "m/d/yy",
        mediumDate:     "mmm d, yyyy",
        longDate:       "mmmm d, yyyy",
        fullDate:       "dddd, mmmm d, yyyy",
        shortTime:      "h:MM TT",
        mediumTime:     "h:MM:ss TT",
        longTime:       "h:MM:ss TT Z",
        isoDate:        "yyyy-mm-dd",
        isoTime:        "HH:MM:ss",
        isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
        isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
    };

    // Internationalization strings
    dateFormat.i18n = {
        dayNames: [
            "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        ],
        monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
        ]
    };

    // For convenience...
    Date.prototype.format = function (mask, utc) {
        return dateFormat(this, mask, utc);
    };

Clear all fields in a form upon going back with browser back button

Another way without JavaScript is to use <form autocomplete="off"> to prevent the browser from re-filling the form with the last values.

See also this question

Tested this only with a single <input type="text"> inside the form, but works fine in current Chrome and Firefox, unfortunately not in IE10.

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

How to get only numeric column values?

Use This [Tested]

To get numeric

SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values

To get non-numeric

SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values

Using a custom typeface in Android

I like pospi's suggestion. Why not go all-out any use the 'tag' property of a view (which you can specify in XML - 'android:tag') to specify any additional styling that you can't do in XML. I like JSON so I'd use a JSON string to specify a key/value set. This class does the work - just call Style.setContentView(this, [resource id]) in your activity.

public class Style {

  /**
   * Style a single view.
   */
  public static void apply(View v) {
    if (v.getTag() != null) {
      try {
        JSONObject json = new JSONObject((String)v.getTag());
        if (json.has("typeface") && v instanceof TextView) {
          ((TextView)v).setTypeface(Typeface.createFromAsset(v.getContext().getAssets(),
                                                             json.getString("typeface")));
        }
      }
      catch (JSONException e) {
        // Some views have a tag without it being explicitly set!
      }
    }
  }

  /**
   * Style the passed view hierarchy.
   */
  public static View applyTree(View v) {
    apply(v);
    if (v instanceof ViewGroup) {
      ViewGroup g = (ViewGroup)v;
      for (int i = 0; i < g.getChildCount(); i++) {
        applyTree(g.getChildAt(i));
      }
    }
    return v;
  }

  /**
   * Inflate, style, and set the content view for the passed activity.
   */
  public static void setContentView(Activity activity, int resource) {
    activity.setContentView(applyTree(activity.getLayoutInflater().inflate(resource, null)));
  }
}

Obviously you'd want to handle more than just the typeface to make using JSON worthwhile.

A benefit of the 'tag' property is that you can set it on a base style which you use as a theme and thus have it apply to all of your views automatically. EDIT: Doing this results in a crash during inflation on Android 4.0.3. You can still use a style and apply it to text views individually.

One thing you'll see in the code - some views have a tag without one being explicitly set - bizarrely it's the string '?p???p?' - which is 'cut' in greek, according to google translate! What the hell...?

Converting pixels to dp

PX and DP are different but similar.

DP is the resolution when you only factor the physical size of the screen. When you use DP it will scale your layout to other similar sized screens with different pixel densities.

Occasionally you actually want pixels though, and when you deal with dimensions in code you are always dealing with real pixels, unless you convert them.

So on a android device, normal sized hdpi screen, 800x480 is 533x320 in DP (I believe). To convert DP into pixels /1.5, to convert back *1.5. This is only for the one screen size and dpi, it would change depending on design. Our artists give me pixels though and I convert to DP with the above 1.5 equation.

Expand/collapse section in UITableView in iOS

This is the best way i found to create expandable table view cells

.h file

  NSMutableIndexSet *expandedSections;

.m file

if (!expandedSections)
    {
        expandedSections = [[NSMutableIndexSet alloc] init];
    }
   UITableView *masterTable = [[UITableView alloc] initWithFrame:CGRectMake(0,100,1024,648) style:UITableViewStyleGrouped];
    masterTable.delegate = self;
    masterTable.dataSource = self;
    [self.view addSubview:masterTable];

Table view delegate methods

- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
    // if (section>0) return YES;

    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self tableView:tableView canCollapseSection:section])
    {
        if ([expandedSections containsIndex:section])
        {
            return 5; // return rows when expanded
        }

        return 1; // only top row showing
    }

    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }

    // Configure the cell...

    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // first row
            cell.textLabel.text = @"Expandable"; // only top row showing

            if ([expandedSections containsIndex:indexPath.section])
            {

                UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableContract"]];
                cell.accessoryView = imView;
            }
            else
            {

                UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableExpand"]];
                cell.accessoryView = imView;
            }
        }
        else
        {
            // all other rows
            if (indexPath.section == 0) {
                cell.textLabel.text = @"section one";
            }else if (indexPath.section == 1) {
                cell.textLabel.text = @"section 2";
            }else if (indexPath.section == 2) {
                cell.textLabel.text = @"3";
            }else {
                cell.textLabel.text = @"some other sections";
            }

            cell.accessoryView = nil;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    else
    {
        cell.accessoryView = nil;
        cell.textLabel.text = @"Normal Cell";

    }

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self tableView:tableView canCollapseSection:indexPath.section])
    {
        if (!indexPath.row)
        {
            // only first row toggles exapand/collapse
            [tableView deselectRowAtIndexPath:indexPath animated:YES];

            NSInteger section = indexPath.section;
            BOOL currentlyExpanded = [expandedSections containsIndex:section];
            NSInteger rows;


            NSMutableArray *tmpArray = [NSMutableArray array];

            if (currentlyExpanded)
            {
                rows = [self tableView:tableView numberOfRowsInSection:section];
                [expandedSections removeIndex:section];

            }
            else
            {
                [expandedSections addIndex:section];
                rows = [self tableView:tableView numberOfRowsInSection:section];
            }


            for (int i=1; i<rows; i++)
            {
                NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                                                               inSection:section];
                [tmpArray addObject:tmpIndexPath];
            }

            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (currentlyExpanded)
            {
                [tableView deleteRowsAtIndexPaths:tmpArray 
                                 withRowAnimation:UITableViewRowAnimationTop];

                UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableExpand"]];
                cell.accessoryView = imView;
            }
            else
            {
                [tableView insertRowsAtIndexPaths:tmpArray 
                                 withRowAnimation:UITableViewRowAnimationTop];

                UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableContract"]];
                cell.accessoryView = imView;
            }
        }
    }

    NSLog(@"section :%d,row:%d",indexPath.section,indexPath.row);

}

Convert datetime object to a String of date only in Python

If you looking for a simple way of datetime to string conversion and can omit the format. You can convert datetime object to str and then use array slicing.

In [1]: from datetime import datetime

In [2]: now = datetime.now()

In [3]: str(now)
Out[3]: '2019-04-26 18:03:50.941332'

In [5]: str(now)[:10]
Out[5]: '2019-04-26'

In [6]: str(now)[:19]
Out[6]: '2019-04-26 18:03:50'

But note the following thing. If other solutions will rise an AttributeError when the variable is None in this case you will receive a 'None' string.

In [9]: str(None)[:19]
Out[9]: 'None'

How to get the exact local time of client?

Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.

I first wrote a php function to return the required dates/times to my HTML template

 /**
 * Gets the current location time based on timezone
 * @return string
 */


function get_the_local_time($timezone) {

    //$timezone ='Europe/London';

    $date = new DateTime('now', new DateTimeZone($timezone));

    return array(
        'local-machine-time' => $date->format('Y-m-d\TH:i:s+0000'),
        'local-time' => $date->format('h:i a')
    );

}

This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.

        <span class="box--location__time" data-time="<?php echo $time['local-machine-time']; ?>">
            <?php  echo $time['local-time']; ?>
        </span>

I then used the getUTCHours on my date object to return the time irrespective of the users timezone

The getUTCHours() method returns the hour (from 0 to 23) of the specified date and time, according to universal time.

var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};

I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML

Is there any kind of hash code function in JavaScript?

In addition to eyelidlessness's answer, here is a function that returns a reproducible, unique ID for any object:

var uniqueIdList = [];
function getConstantUniqueIdFor(element) {
    // HACK, using a list results in O(n), but how do we hash e.g. a DOM node?
    if (uniqueIdList.indexOf(element) < 0) {
        uniqueIdList.push(element);
    }
    return uniqueIdList.indexOf(element);
}

As you can see it uses a list for look-up which is very inefficient, however that's the best I could find for now.

XPath: select text node

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

Use:

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

/node/text()[position() = someInteger]

What is the difference between %g and %f in C?

%f and %g does the same thing. Only difference is that %g is the shorter form of %f. That is the precision after decimal point is larger in %f compared to %g

Laravel eloquent update record without loading from database

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

If you are extending from an AppCompatActivity and are trying to get the ActionBar from the Fragment, you can do this:

ActionBar mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();

How to append strings using sprintf?

I think you are looking for fmemopen(3):

#include <assert.h>
#include <stdio.h>

int main(void)
{
    char buf[128] = { 0 };
    FILE *fp = fmemopen(buf, sizeof(buf), "w");

    assert(fp);

    fprintf(fp, "Hello World!\n");
    fprintf(fp, "%s also work, of course.\n", "Format specifiers");
    fclose(fp);

    puts(buf);
    return 0;
}

If dynamic storage is more suitable for you use-case you could follow Liam's excellent suggestion about using open_memstream(3):

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *buf;
    size_t size;
    FILE *fp = open_memstream(&buf, &size);

    assert(fp);

    fprintf(fp, "Hello World!\n");
    fprintf(fp, "%s also work, of course.\n", "Format specifiers");
    fclose(fp);

    puts(buf);
    free(buf);
    return 0;
}

How to install latest version of Node using Brew

Run commands below, in this order:

brew update
brew doctor
brew upgrade node

Now you have installed updated version of node, and it's probably not linked. If it's not, then just type: brew link node or brew link --overwrite node

How to specify function types for void (not Void) methods in Java8?

You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)

The Function type is declared as

interface Function<T,R> {
  R apply(T t);
}

However, the Consumer type is compatible with that you are looking for:

interface Consumer<T> {
   void accept(T t);
}

As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.

For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:

List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );

You can see above that in this case, the lambda expression receives a parameter and has no return value.

Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.

I could use different types of method references, but in this case let's take advantage of an object method reference by using the println method in the System.out object, like this:

Consumer<String> block = System.out::println

Or I could simply do

allJedi.forEach(System.out::println);

The println method is appropriate because it receives a value and has a return type void, just like the accept method in Consumer.

So, in your code, you need to change your method signature to somewhat like:

public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
   list.forEach(myBlock);
}

And then you should be able to create a consumer, using a static method reference, in your case by doing:

myForEach(theList, Test::displayInt);

Ultimately, you could even get rid of your myForEach method altogether and simply do:

theList.forEach(Test::displayInt);

About Functions as First Class Citizens

All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.

jQuery Event : Detect changes to the html/text of a div

You can try this

$('.myDiv').bind('DOMNodeInserted DOMNodeRemoved', function() {

});

but this might not work in internet explorer, haven't tested it

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

This is a really unclear and unhelpful error message. After much trial and error I found that LocalDateTime will give the above error if you do not attempt to parse a time. By using LocalDate instead, it works without erroring.

This is poorly documented and the related exception is very unhelpful.

SQL Query - Concatenating Results into One String

from msdn Do not use a variable in a SELECT statement to concatenate values (that is, to compute aggregate values). Unexpected query results may occur. This is because all expressions in the SELECT list (including assignments) are not guaranteed to be executed exactly once for each output row

The above seems to say that concatenation as done above is not valid as the assignment might be done more times than there are rows returned by the select

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I face the same problem and changing

 $cfg['Servers'][$i]['host'] = 'localhost';

to

 $cfg['Servers'][$i]['host'] = '127.0.0.1';

Solved this issue.

How can I access my localhost from my Android device?

This is what worked for me, I added another line after the 127.0.0.1 ip to specify the exact local network ip address (not the public ip address) of the device I wanted to use. In my case my Samsung Galaxy S3

As suggested by Bangptit edit the httpd.conf file (x being the version numbers): C:\wamp\bin\apache\Apache2.x.x\conf\httpd.conf

Search for the onlineoffline tag and add the ip of your phone (I found my phones ip address in my routers configuration pages):

onlineoffline tag - don't remove

 Order Deny,Allow
 Deny from all
 Allow from 127.0.0.1

my phones ip in the line below

 Allow from 192.168.1.65 
 Allow from ::1
 Allow from localhost

One could extend this to include an entire sub domain too for e.g. 192.168.1.0/24 etc

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

In some references, use the second instead of the first:

soup_object= BeautifulSoup(markup,'html-parser')
soup_object= BeautifulSoup(markup,'html.parser')

Change onclick action with a Javascript function

What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.

So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

Adding an identity to an existing column

If the original poster was actually wanting to set an existing column to be a PRIMARY KEY for the table and actually did not need the column to be an IDENTITY column (two different things) then this can be done via t-SQL with:

ALTER TABLE [YourTableName]
ADD CONSTRAINT [ColumnToSetAsPrimaryKey] PRIMARY KEY ([ColumnToSetAsPrimaryKey])

Note the parenthesis around the column name after the PRIMARY KEY option.

Although this post is old and I am making an assumption about the requestors need, I felt this additional information could be helpful to users encountering this thread as I believe the conversation could lead one to believe that an existing column can not be set to be a primary key without adding it as a new column first which would be incorrect.

How to get exit code when using Python subprocess communicate method?

exitcode = data.wait(). The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.

How to dynamically remove items from ListView on a button click?

<ImageView
    android:id="@+id/btnDelete"
    android:layout_width="35dp"
    android:layout_height="match_parent"
    android:layout_alignBottom="@+id/editTipo"
    android:layout_alignParentRight="true"
    android:background="@drawable/abc_ic_clear"
    android:onClick="item_delete_handler"/>

And create Event item_delete_handler,

Escape quote in web.config connection string

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

Since the web.config is XML, you need to escape the five special characters:

&amp; -> & ampersand, U+0026
&lt; -> < left angle bracket, less-than sign, U+003C
&gt; -> > right angle bracket, greater-than sign, U+003E
&quot; -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027

+ is not a problem, I suppose.


Duc Filan adds: You should also wrap your password with single quote ':

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

Get Row Index on Asp.net Rowcommand event

Or, you can use a control class instead of their types:

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

int RowIndex = row.RowIndex; 

Change string color with NSAttributedString?

There is no need for using NSAttributedString. All you need is a simple label with the proper textColor. Plus this simple solution will work with all versions of iOS, not just iOS 6.

But if you needlessly wish to use NSAttributedString, you can do something like this:

UIColor *color = [UIColor redColor]; // select needed color
NSString *string = ... // the string to colorize
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:string attributes:attrs];
self.scanLabel.attributedText = attrStr;

How to use global variables in React Native?

You can use the global keyword to solve this.

Assume that you want to declare a variable called isFromManageUserAccount as a global variable you can use the following code.

global.isFromManageUserAccount=false;

After declaring like this you can use this variable anywhere in the application.

Java string split with "." (dot)

I believe you should escape the dot. Try:

String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];

Otherwise dot is interpreted as any character in regular expressions.

How to cancel an $http request in AngularJS?

This enhances the accepted answer by decorating the $http service with an abort method as follows ...

'use strict';
angular.module('admin')
  .config(["$provide", function ($provide) {

$provide.decorator('$http', ["$delegate", "$q", function ($delegate, $q) {
  var getFn = $delegate.get;
  var cancelerMap = {};

  function getCancelerKey(method, url) {
    var formattedMethod = method.toLowerCase();
    var formattedUrl = encodeURI(url).toLowerCase().split("?")[0];
    return formattedMethod + "~" + formattedUrl;
  }

  $delegate.get = function () {
    var cancelerKey, canceler, method;
    var args = [].slice.call(arguments);
    var url = args[0];
    var config = args[1] || {};
    if (config.timeout == null) {
      method = "GET";
      cancelerKey = getCancelerKey(method, url);
      canceler = $q.defer();
      cancelerMap[cancelerKey] = canceler;
      config.timeout = canceler.promise;
      args[1] = config;
    }
    return getFn.apply(null, args);
  };

  $delegate.abort = function (request) {
    console.log("aborting");
    var cancelerKey, canceler;
    cancelerKey = getCancelerKey(request.method, request.url);
    canceler = cancelerMap[cancelerKey];

    if (canceler != null) {
      console.log("aborting", cancelerKey);

      if (request.timeout != null && typeof request.timeout !== "number") {

        canceler.resolve();
        delete cancelerMap[cancelerKey];
      }
    }
  };

  return $delegate;
}]);
  }]);

WHAT IS THIS CODE DOING?

To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).

However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.

Hope this helps someone.

LIMITATIONS

Currently this only works for $http.get but you can add code for $http.post and so on

HOW TO USE ...

You can then use it, for example, on state change, as follows ...

rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
  angular.forEach($http.pendingRequests, function (request) {
        $http.abort(request);
    });
  });

Java 8 Stream and operation on arrays

You can turn an array into a stream by using Arrays.stream():

int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);

Once you've got your stream, you can use any of the methods described in the documentation, like sum() or whatever. You can map or filter like in Python by calling the relevant stream methods with a Lambda function:

Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);

Once you're done modifying your stream, you then call toArray() to convert it back into an array to use elsewhere:

int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();

What is the meaning of prepended double colon "::"?

:: is the scope resolution operator. It's used to specify the scope of something.

For example, :: alone is the global scope, outside all other namespaces.

some::thing can be interpreted in any of the following ways:

  • some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
  • some is a class available in the current scope and thing is a member object, function or type of the some class;
  • in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.

You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.

So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.

The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.

I hope this answer is complete and correct enough to help you understand scope resolution.

MySQL error 1449: The user specified as a definer does not exist

In my case, deleting all the views solved the issue.

DROP VIEW view_name;

How to update value of a key in dictionary in c#?

Have you tried just

dictionary["cat"] = 5;

:)

Update

dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;

Beware of non-existing keys :)

How to Serialize a list in java?

All standard implementations of java.util.List already implement java.io.Serializable.

So even though java.util.List itself is not a subtype of java.io.Serializable, it should be safe to cast the list to Serializable, as long as you know it's one of the standard implementations like ArrayList or LinkedList.

If you're not sure, then copy the list first (using something like new ArrayList(myList)), then you know it's serializable.

Get the current file name in gulp.src()

For my case gulp-ignore was perfect. As option you may pass a function there:

function condition(file) {
 // do whatever with file.path
 // return boolean true if needed to exclude file 
}

And the task would look like this:

var gulpIgnore = require('gulp-ignore');

gulp.task('task', function() {
  gulp.src('./**/*.js')
    .pipe(gulpIgnore.exclude(condition))
    .pipe(gulp.dest('./dist/'));
});

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

How to use a DataAdapter with stored procedure and parameter

Maybe your code is missing this line from the Microsoft example:

MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

using namespaces and subqueries You can do it:

declare @data table (RequestID varchar(20), CreatedDate datetime, HistoryStatus varchar(20))
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','For Review');
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','Completed');  
insert into @data values ('CF-0000112','8/26/2009 1:07:01 PM','For Review');   
insert into @data values ('CF-0000113','8/26/2009 1:07:01 PM','For Review');  
insert into @data values ('CF-0000114','8/26/2009 1:07:01 PM','Completed');  
insert into @data values ('CF-0000115','8/26/2009 1:07:01 PM','Completed');

select d1.RequestID,d1.CreatedDate,d1.HistoryStatus 
from @data d1 
where d1.HistoryStatus = 'Completed'
union all 
select d2.RequestID,d2.CreatedDate,d2.HistoryStatus 
from @data d2 
where d2.HistoryStatus = 'For Review' 
    and d2.RequestID not in (
        select RequestID 
        from @data 
        where HistoryStatus = 'Completed' 
            and CreatedDate = d2.CreatedDate
    )

Above query returns

CF-0000001, 2009-08-26 13:07:01.000,    Completed
CF-0000114, 2009-08-26 13:07:01.000,    Completed
CF-0000115, 2009-08-26 13:07:01.000,    Completed
CF-0000112, 2009-08-26 13:07:01.000,    For Review
CF-0000113, 2009-08-26 13:07:01.000,    For Review

Finding the index of an item in a list

If you want all indexes, then you can use NumPy:

import numpy as np

array = [1, 2, 1, 3, 4, 5, 1]
item = 1
np_array = np.array(array)
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)

It is clear, readable solution.

Convert text into number in MySQL query

You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS INTEGER);

Define constant variables in C++ header

It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.

In foo.cc:

#include <cstdio>               // for puts

#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"

int main(int argc, const char* argv[])
{
  puts("Hello!");
  bar();
  zoo();
  puts(Message::third);
  return 0;
}

In messages.hh:

#ifndef MESSAGES_HH
#define MESSAGES_HH

namespace Message {
  char const * const first = "Yes, this is the first message!";
  char const * const second = "This is the second message.";
  char const * const third = "Message #3.";
};

#endif

In bar.cc:

#include "messages.hh"
#include <cstdio>

void bar(void)
{
  puts("Wow!");
  printf("bar: %s\n", Message::first);
}

In zoo.cc:

#include <cstdio>
#include "messages.hh"

void zoo(void)
{
  printf("zoo: %s\n", Message::second);
}

In bar.hh:

#ifndef BAR_HH
#define BAR_HH

#include "messages.hh"

void bar(void);

#endif

In zoo.hh:

#ifndef ZOO_HH
#define ZOO_HH

#include "messages.hh"

void zoo(void);

#endif

This yields the following output:

Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.

The data type char const * const means a constant pointer to an array of constant characters. The first const is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the consts, but then the source code is less portable.

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

How to change or add theme to Android Studio?

You can try this Making Android Studio pretty to change the android studio look and feel different.

How to convert a string from uppercase to lowercase in Bash?

If you are using bash 4 you can use the following approach:

x="HELLO"
echo $x  # HELLO

y=${x,,}
echo $y  # hello

z=${y^^}
echo $z  # HELLO

Use only one , or ^ to make the first letter lowercase or uppercase.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

I find it useful when including or requiring _dbconnection.php_ and _functions.php in files that are actually processed, rather than including in the header. Which is included in itself.

So if your header and footer is included, simply include all your functional files before the header is included.

Auto Generate Database Diagram MySQL

I've recently started using http://schemaspy.sourceforge.net/ . It uses GraphViz, and it strikes me as having a good balance between usability and simplicity.

difference between throw and throw new Exception()

Throwing a new Exception blows away the current stack trace.

throw; will retain the original stack trace and is almost always more useful. The exception to that rule is when you want to wrap the Exception in a custom Exception of your own. You should then do:

catch(Exception e)
{
    throw new CustomException(customMessage, e);
}

initializing strings as null vs. empty string

There's a function empty() ready for you in std::string:

std::string a;
if(a.empty())
{
    //do stuff. You will enter this block if the string is declared like this
}

or

std::string a;
if(!a.empty())
{
    //You will not enter this block now
}
a = "42";
if(!a.empty())
{
    //And now you will enter this block.
}

Test class with a new() call in it with Mockito

You can use a factory to create the login context. Then you can mock the factory and return whatever you want for your test.

public class TestedClass {
  private final LoginContextFactory loginContextFactory;

  public TestedClass(final LoginContextFactory loginContextFactory) {
    this.loginContextFactory = loginContextFactory;
  }

  public LoginContext login(String user, String password) {
    LoginContext lc = loginContextFactory.createLoginContext();
  }
}

public interface LoginContextFactory {
  public LoginContext createLoginContext();
}

How can I assign an ID to a view programmatically?

Yes, you can call setId(value) in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value). Note that it is valid to call setId() with the same value for different sibling views, but findViewById() will return only the first one.

What is the meaning of "__attribute__((packed, aligned(4))) "

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

gem install: Failed to build gem native extension (can't find header files)

My initial solution was to resolve the above errors by installing ruby-devel, patch and rubygems.

My issue was a bit different as bcrypt 3.1.11 still had issues compiling and installing on Fedora 23. I needed additional packages. So after ensuring I had the above installed, I was still having issues:

gcc: error: conftest.c: No such file or directory

gcc: error: /usr/lib/rpm/redhat/redhat-hardened-cc1: No such file or directory

From here I had to do the following:

  • I ensured that I wasn't lacking any C compiler tools sudo dnf group install "C Development Tools and Libraries"

  • Then I ran sudo dnf install redhat-rpm-config to resolve the gcc issue listed above.

You can find a write up here on Fedore Project. You may also find answers to other needs as well.

How to add a Hint in spinner in XML

I've managed to add a 'hint' that is omitted from the drop down list. If my code looks a bit weird it's because I'm using Xamarin.Android so it's in C# but for all intents (heh) and purposes the Java equivalent should have the same effect.

The gist is that I've created a custom ArrayAdapter that will detect if it is the hint in the GetDropDownView method. If so then it will inflate an empty XML to hide the hint from the drop down.

My spinnerItem.xml is ...

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinnerText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/text_left_padding"
    android:textAppearance="?android:attr/textAppearanceLarge"/>

My 'empty' hintSpinnerDropdownItem.xml which will hide the hint.

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

I pass in an array of CustomObj without the hint. That's why I have the additional AddPrompt method to insert the hint at the beginning before it's passed to the parent constructor.

public class CustomArrayAdapter: ArrayAdapter<CustomObj>
{

    private const int HintPosition = 0;
    private const CustomObj HintValue = null;
    private const string Hint = "Hint";

    public CustomArrayAdapter(Context context, int textViewResourceId, CustomObj[] customObjs) : base(context, textViewResourceId, AddPrompt(customObjs))
    {


    private static CustomObj[] AddPrompt(CustomObj[] customObjs)
    {
        CustomObj[] customObjsWithHint = new CustomObj[customObjs.Length + 1];
        CustomObj[] hintPlaceholder = { HintValue };
        Array.Copy(hintPlaceholder , customObjsWithHint , 1);
        Array.Copy(customObjs, 0, customObjsWithHint , 1, customObjs.Length);
        return customObjsWithHint ;
    }

    public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
    {
        CustomObj customObj = GetItem(position);
        bool isHint = customObj == HintValue;

        if (convertView == null)
        {
            convertView = LayoutInflater.From(base.Context).Inflate(Resource.Layout.spinnerItem, parent, false);
        }

        TextView textView = convertView.FindViewById<TextView>(Resource.Id.spinnerText);
        textView.Text = isHint ? Hint : customObj.Value;
        textView.SetTextColor(isHint ? Color.Gray : Color.Black);

        return convertView;

    public override Android.Views.View GetDropDownView(int position, Android.Views.View convertView, ViewGroup parent)
    {
        CustomObj customObj = GetItem(position);

        if (position == HintPosition)
        {
            convertView = LayoutInflater.From(base.Context).Inflate(Resource.Layout.hintSpinnerDropdownItem, parent, false);
        }
        else
        {
            convertView = LayoutInflater.From(base.Context).Inflate(Resource.Layout.spinnerItem, parent, false);
            TextView textView = convertView.FindViewById<TextView>(Resource.Id.spinnerText);
            textView.Text = customObj.Value;
        }

        return convertView;
    }
}

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

Reset Excel to default borders

I was having the same trouble with importing from Excel 2010 to Access, appending an "identical" table. Early on in the wizard it said not all my column names were valid, even though I checked them. It turns out that it saw an "empty" column with no column name. When I tried using the import wizard to create a new table instead, it worked. However, I noticed that it had added a blank column to the right of my data and called it "Field30". So I went back to the spreadsheet I was trying to import, selected the columns to the right of the data that I wanted, right-clicked and chose "clear contents." That did the trick and I was able to import the spreadsheet, appending it to my table.

Pan & Zoom Image

@ Merk

For ur solution insted of lambda expression you can use following code:

//var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
        TranslateTransform tt = null;
        TransformGroup transformGroup = (TransformGroup)grid.RenderTransform;
        for (int i = 0; i < transformGroup.Children.Count; i++)
        {
            if (transformGroup.Children[i] is TranslateTransform)
                tt = (TranslateTransform)transformGroup.Children[i];
        }

this code can be use as is for .Net Frame work 3.0 or 2.0

Hope It helps you :-)

Recursive sub folder search and return files in a list python

If you don't mind installing an additional light library, you can do this:

pip install plazy

Usage:

import plazy

txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)

The result should look something like this:

['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']

It works on both Python 2.7 and Python 3.

Github: https://github.com/kyzas/plazy#list-files

Disclaimer: I'm an author of plazy.

Is there any way to change input type="date" format?

I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.

How to sort strings in JavaScript

Use sort() straight forward without any - or <

_x000D_
_x000D_
const areas = ['hill', 'beach', 'desert', 'mountain']
console.log(areas.sort())

// To print in descending way
console.log(areas.sort().reverse())
_x000D_
_x000D_
_x000D_

How can I discover the "path" of an embedded resource?

I use the following method to grab embedded resources:

    protected static Stream GetResourceStream(string resourcePath)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());

        resourcePath = resourcePath.Replace(@"/", ".");
        resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));

        if (resourcePath == null)
            throw new FileNotFoundException("Resource not found");

        return assembly.GetManifestResourceStream(resourcePath);
    }

I then call this with the path in the project:

GetResourceStream(@"DirectoryPathInLibrary/Filename")

Android: Getting a file URI from a content URI?

Trying to handle the URI with content:// scheme by calling ContentResolver.query()is not a good solution. On HTC Desire running 4.2.2 you could get NULL as a query result.

Why not to use ContentResolver instead? https://stackoverflow.com/a/29141800/3205334

How to force a html5 form validation without submitting it via jQuery

To check whether a certain field is valid, use:

$('#myField')[0].checkValidity(); // returns true/false

To check if the form is valid, use:

$('#myForm')[0].checkValidity(); // returns true/false

If you want to display the native error messages that some browsers have (such as Chrome), unfortunately the only way to do that is by submitting the form, like this:

var $myForm = $('#myForm');

if(! $myForm[0].checkValidity()) {
  // If the form is invalid, submit it. The form won't actually submit;
  // this will just cause the browser to display the native HTML5 error messages.
  $myForm.find(':submit').click();
}

Hope this helps. Keep in mind that HTML5 validation is not supported in all browsers.

Leave only two decimal places after the dot

double doublVal = 123.45678;

There are two ways.

  1. for display in string:

    String.Format("{0:0.00}", doublVal );
    
  2. for geting again Double

    doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
    

How to get second-highest salary employees in a table

try this simple way

select name,salary from employee where salary =
(select max(salary) from employee where salary < (select max(salary) from employee ))

How do you get the logical xor of two variables in Python?

How about this?

(not b and a) or (not a and b)

will give a if b is false
will give b if a is false
will give False otherwise

Or with the Python 2.5+ ternary expression:

(False if a else b) if b else a

Angular ui-grid dynamically calculate height of the grid

I use ui-grid - v3.0.0-rc.20 because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if is optional to wait until your data is set before rendering.

_x000D_
_x000D_
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
    ..._x000D_
    _x000D_
    $scope.gridData = {_x000D_
      rowHeight: 30, // set row height, this is default size_x000D_
      ..._x000D_
    };_x000D_
  _x000D_
    ..._x000D_
_x000D_
    $scope.getTableHeight = function() {_x000D_
       var rowHeight = 30; // your row height_x000D_
       var headerHeight = 30; // your header height_x000D_
       return {_x000D_
          height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
       };_x000D_
    };_x000D_
      _x000D_
    ...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
_x000D_
_x000D_

Random number generator only generating one random number

I solved the problem by using the Rnd() function:

Function RollD6() As UInteger
        RollD6 = (Math.Floor(6 * Rnd())) + 1
        Return RollD6
End Function

When the form loads, I use the Randomize() method to make sure I don't always get the same sequence of random numbers from run to run.

Import Excel spreadsheet columns into SQL Server database

If you would like a visual tool with Desktop interface including validation .. you may well like this Excel tool. You can also use the tool to create multi user data-edit tasks, or even paste data to SQL server from any source..

How to Validate and Import Excel spreadsheet to SQL Server database:

http://leansoftware.net/en-us/help/excel-database-tasks/worked-examples/how-to-import-excel-spreadsheet-to-sql-server-data.aspx

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

How can I switch my signed in user in Visual Studio 2013?

If the Command prompt don't work for you, try logging in with your account that is working then log out and then try again with your other account.

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

UINavigationBar custom back button without title

If you set the tintColor Of NavigationBar,add a custom back button image without title that tint color will reflect the image color. Please follow this apple documentaion link.

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/UIKitUICatalog/index.html#//apple_ref/doc/uid/TP40012857-UIView-SW7

UINavigationItem *navItem = [[UINavigationItem alloc] init];
   navBar.tintColor = self.tintColor;

   UIImage *myImage = [UIImage imageNamed:@"left_arrow.png"];
     myImage = [myImage              imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

     UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:myImage style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonFunction:)];
     navItem.leftBarButtonItem = leftButton;

    navBar.items = @[ navItem ];

Change connection string & reload app.config at run time

You can also refresh the configuration in it's entirety:

ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName];

if (importToConnectionString == null)
{
    importToConnectionString = new ConnectionStringSettings();
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
    importToConnectionString.Name = newName;
    currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString);
}
else
{
    importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
    importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
}

Properties.Settings.Default.Reload();

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

SQL Server IN vs. EXISTS Performance

So, IN is not the same as EXISTS nor it will produce the same execution plan.

Usually EXISTS is used in a correlated subquery, that means you will JOIN the EXISTS inner query with your outer query. That will add more steps to produce a result as you need to solve the outer query joins and the inner query joins then match their where clauses to join both.

Usually IN is used without correlating the inner query with the outer query, and that can be solved in only one step (in the best case scenario).

Consider this:

  1. If you use IN and the inner query result is millions of rows of distinct values, it will probably perform SLOWER than EXISTS given that the EXISTS query is performant (has the right indexes to join with the outer query).

  2. If you use EXISTS and the join with your outer query is complex (takes more time to perform, no suitable indexes) it will slow the query by the number of rows in the outer table, sometimes the estimated time to complete can be in days. If the number of rows is acceptable for your given hardware, or the cardinality of data is correct (for example fewer DISTINCT values in a large data set) IN can perform faster than EXISTS.

  3. All of the above will be noted when you have a fair amount of rows on each table (by fair I mean something that exceeds your CPU processing and/or ram thresholds for caching).

So the ANSWER is it DEPENDS. You can write a complex query inside IN or EXISTS, but as a rule of thumb, you should try to use IN with a limited set of distinct values and EXISTS when you have a lot of rows with a lot of distinct values.

The trick is to limit the number of rows to be scanned.

Regards,

MarianoC

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

A Generic error occurred in GDI+ in Bitmap.Save method

Check your folder's permission where the image is saved Right cLick on folder then go :

Properties > Security > Edit > Add-- select "everyone" and check Allow "Full Control"

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

Full-screen iframe with a height of 100%

You can can call a function which will calculate the iframe's body hieght when the iframe is loaded:

<script type="text/javascript">
    function iframeloaded(){
       var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
       curHeight = $frame.contents().find('body').height();
       if ( curHeight != lastHeight ) {
           $frame.css('height', (lastHeight = curHeight) + 'px' );
       }
    }
</script>

<iframe onload="iframeloaded()" src=...>

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

The canvas element provides a toDataURL method which returns a data: URL that includes the base64-encoded image data in a given format. For example:

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.

The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.

For more information see the MDN docs on the canvas API, which includes details on toDataURL, and the Wikipedia article on the data: URI scheme, which includes details on the format of the URI you'll receive from this call.

How can I capture packets in Android?

It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

How to frame two for loops in list comprehension python

This should do it:

[entry for tag in tags for entry in entries if tag in entry]

How can I get Docker Linux container information from within the container itself?

Use docker inspect.

$ docker ps # get conteiner id
$ docker inspect 4abbef615af7
[{
    "ID": "4abbef615af780f24991ccdca946cd50d2422e75f53fb15f578e14167c365989",
    "Created": "2014-01-08T07:13:32.765612597Z",
    "Path": "/bin/bash",
    "Args": [
        "-c",
        "/start web"
    ],
    "Config": {
        "Hostname": "4abbef615af7",
...

Can get ip as follows.

$ docker inspect -format="{{ .NetworkSettings.IPAddress }}" 2a5624c52119
172.17.0.24

How do I clear the std::queue efficiently?

You could create a class that inherits from queue and clear the underlying container directly. This is very efficient.

template<class T>
class queue_clearable : public std::queue<T>
{
public:
    void clear()
    {
        c.clear();
    }
};

Maybe your a implementation also allows your Queue object (here JobQueue) to inherit std::queue<Job> instead of having the queue as a member variable. This way you would have direct access to c.clear() in your member functions.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

Usage of MySQL's "IF EXISTS"

SELECT IF((
     SELECT count(*) FROM gdata_calendars 
     WHERE `group` =  ? AND id = ?)
,1,0);

For Detail explanation you can visit here

How to remove trailing whitespace in code, using another script?

It's a bit surprising seeing multiple answers suggesting to use python for this task, as there's no need to write a multi-line program for this.

Standard Unix tools like sed, awk or perl can achieve this easily straight from the command-line.

e.g anywhere you have perl (Windows, Mac, Linux) the following should achieve what the OP asked:

perl -i -pe 's/[ \t]+$//;' files...

Explanation of the arguments to perl:

-i   # run the edit "in place" (modify the original file)
-p   # implies a loop with a final print over every input line
-e   # next arg is the perl expression to apply (to every line)

s/[ \t]$// is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.

Advantages:

  • One liner, no programming needed
  • Works on multiple (any number) of files
  • Works correctly on standard-input (no file arguments given)

Edit:

Newer versions of perl support \h (any horizontal-space character), so the solution becomes even shorter:

perl -i -pe 's/\h+$//;' files...

More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO with BAR, you may always use this generic template:

perl -i -pe 's/FOO/BAR/' files...

How to add a Try/Catch to SQL Stored Procedure

Error-Handling with SQL Stored Procedures

TRY/CATCH error handling can take place either within or outside of a procedure (or both). The examples below demonstrate error handling in both cases.

If you want to experiment further, you can fork the query on Stack Exchange Data Explorer.

(This uses a temporary stored procedure... we can't create regular SP's on SEDE, but the functionality is the same.)

--our Stored Procedure
create procedure #myProc as --we can only create #temporary stored procedures on SEDE. 
  begin
    BEGIN TRY
      print 'This is our Stored Procedure.'
      print 1/0                          --<-- generate a "Divide By Zero" error.
      print 'We are not going to make it to this line.'
    END TRY

    BEGIN CATCH
      print 'This is the CATCH block within our Stored Procedure:'
          + ' Error Line #'+convert(varchar,ERROR_LINE())
          + ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
      --print 1/0                        --<-- generate another "Divide By Zero" error.
        -- uncomment the line above to cause error within the CATCH ¹ 
    END CATCH
  end
go

--our MAIN code block:
BEGIN TRY
  print 'This is our MAIN Procedure.'
  execute #myProc  --execute the Stored Procedure
      --print 1/0                        --<-- generate another "Divide By Zero" error.
        -- uncomment the line above to cause error within the MAIN Procedure ²
  print 'Now our MAIN sql code block continues.'
END TRY

BEGIN CATCH
  print 'This is the CATCH block for our MAIN sql code block:'
          + ' Error Line #'+convert(varchar,ERROR_LINE())
          + ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
END CATCH

Here's the result of running the above sql as-is:

This is our MAIN Procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
Now our MAIN sql code block continues.

¹ Uncommenting the "additional error line" from the Stored Procedure's CATCH block will produce:

This is our MAIN procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #13 of procedure #myProc

² Uncommenting the "additional error line" from the MAIN procedure will produce:

This is our MAIN Procedure.
This is our Stored Pprocedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #4 of procedure (Main)

Use a single procedure for error handling

On topic of stored procedures and error handling, it can be helpful (and tidier) to use a single, dynamic, stored procedure to handle errors for multiple other procedures or code sections.

Here's an example:

--our error handling procedure
create procedure #myErrorHandling as
  begin
    print ' Error #'+convert(varchar,ERROR_NUMBER())+': '+ERROR_MESSAGE()  
    print ' occurred on line #'+convert(varchar,ERROR_LINE())
         +' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
    if ERROR_PROCEDURE() is null       --check if error was in MAIN Procedure
      print '*Execution cannot continue after an error in the MAIN Procedure.'
  end
go

create procedure #myProc as     --our test Stored Procedure
  begin
    BEGIN TRY
      print 'This is our Stored Procedure.'
      print 1/0                       --generate a "Divide By Zero" error.
      print 'We will not make it to this line.'
    END TRY
    BEGIN CATCH
     execute #myErrorHandling
    END CATCH
  end
go

BEGIN TRY                       --our MAIN Procedure
  print 'This is our MAIN Procedure.'
  execute #myProc                     --execute the Stored Procedure
  print '*The error halted the procedure, but our MAIN code can continue.'
  print 1/0                           --generate another "Divide By Zero" error.
  print 'We will not make it to this line.'
END TRY
BEGIN CATCH
  execute #myErrorHandling
END CATCH

Example Output: (This query can be forked on SEDE here.)

This is our MAIN procedure.
This is our stored procedure.
 Error #8134: Divide by zero error encountered.
 occurred on line #5 of procedure #myProc
*The error halted the procedure, but our MAIN code can continue.
 Error #8134: Divide by zero error encountered.
 occurred on line #5 of procedure (Main)
*Execution cannot continue after an error in the MAIN procedure.

Documentation:

In the scope of a TRY/CATCH block, the following system functions can be used to obtain information about the error that caused the CATCH block to be executed:

  • ERROR_NUMBER() returns the number of the error.
  • ERROR_SEVERITY() returns the severity.
  • ERROR_STATE() returns the error state number.
  • ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
  • ERROR_LINE() returns the line number inside the routine that caused the error.
  • ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.

(Source)

Note that there are two types of SQL errors: Terminal and Catchable. TRY/CATCH will [obviously] only catch the "Catchable" errors. This is one of a number of ways of learning more about your SQL errors, but it probably the most useful.

It's "better to fail now" (during development) compared to later because, as Homer says . . .

How to disable spring security for particular url

I faced the same problem here's the solution:(Explained)

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers(HttpMethod.POST,"/form").hasRole("ADMIN")  // Specific api method request based on role.
            .antMatchers("/home","/basic").permitAll()  // permited urls to guest users(without login).
            .anyRequest().authenticated()
            .and()
        .formLogin()       // not specified form page to use default login page of spring security.
            .permitAll()
             .and()
        .logout().deleteCookies("JSESSIONID")  // delete memory of browser after logout.

        .and()
        .rememberMe().key("uniqueAndSecret"); // remember me check box enabled.

    http.csrf().disable();  **// ADD THIS CODE TO DISABLE CSRF IN PROJECT.**
}

How do I get JSON data from RESTful service using Python?

If you desire to use Python 3, you can use the following:

import json
import urllib.request
req = urllib.request.Request('url')
with urllib.request.urlopen(req) as response:
    result = json.loads(response.readall().decode('utf-8'))

How can I use iptables on centos 7?

Try the following command iptables-save.

split string only on first instance of specified character

I need the two parts of string, so, regex lookbehind help me with this.

_x000D_
_x000D_
const full_name = 'Maria do Bairro';_x000D_
const [first_name, last_name] = full_name.split(/(?<=^[^ ]+) /);_x000D_
console.log(first_name);_x000D_
console.log(last_name);
_x000D_
_x000D_
_x000D_

Renaming branches remotely in Git

If you really just want to rename branches remotely, without renaming any local branches at the same time, you can do this with a single command:

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

I wrote this script (git-rename-remote-branch) which provides a handy shortcut to do the above easily.

As a bash function:

git-rename-remote-branch(){
  if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : ${FUNCNAME[0]} <remote> <old name> <new name>"
    echo "Example   : ${FUNCNAME[0]} origin master release"
    return 1 
  fi

  git push $1 $1/$2\:refs/heads/$3 :$2
}

To integrate @ksrb's comment: What this basically does is two pushes in a single command, first git push <remote> <remote>/<old_name>:refs/heads/<new_name> to push a new remote branch based on the old remote tracking branch and then git push <remote> :<old_name> to delete the old remote branch.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

 Use the below code to solve the CertPathValidatorException issue.


 Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_BASE_URL)
        .client(getUnsafeOkHttpClient().build())
        .build();


  public static OkHttpClient.Builder getUnsafeOkHttpClient() {

    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

For more details visit https://mobikul.com/android-retrofit-handling-sslhandshakeexception/

How to change the name of a Django app?

Follow these steps to change an app's name in Django:

  1. Rename the folder which is in your project root
  2. Change any references to your app in their dependencies, i.e. the app's views.py, urls.py , 'manage.py' , and settings.py files.
  3. Edit the database table django_content_type with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
  4. Also if you have models, you will have to rename the model tables. For postgres use ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName. For mysql too I think it is the same (as mentioned by @null_radix)
  5. (For Django >= 1.7) Update the django_migrations table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.
  6. If your models.py 's Meta Class has app_name listed, make sure to rename that too (mentioned by @will).
  7. If you've namespaced your static or templates folders inside your app, you'll also need to rename those. For example, rename old_app/static/old_app to new_app/static/new_app.
  8. For renaming django models, you'll need to change django_content_type.name entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'

Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ... this might be the culprit. (thanks to @danyamachine for providing this).

Other references: you might also want to refer the below links for a more complete picture

  1. Renaming an app with Django and South
  2. How do I migrate a model out of one django app and into a new one?
  3. How to change the name of a Django app?
  4. Backwards migration with Django South
  5. Easiest way to rename a model using Django/South?
  6. Python code (thanks to A.Raouf) to automate the above steps (Untested code. You have been warned!)
  7. Python code (thanks to rafaponieman) to automate the above steps (Untested code. You have been warned!)

Spaces cause split in path with PowerShell

For any file path with space, simply put them in double quotations will work in Windows Powershell. For example, if you want to go to Program Files directory, instead of use

PS C:\> cd Program Files

which will induce error, simply use the following will solve the problem:

PS C:\> cd "Program Files"

How can I get input radio elements to horizontally align?

Here is updated Fiddle

Simply remove </br> between input radio's

<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>

Move existing, uncommitted work to a new branch in Git

There is actually a really easy way to do this with GitHub Desktop now that I don't believe was a feature before.

All you need to do is switch to the new branch in GitHub Desktop, and it will prompt you to leave your changes on the current branch (which will be stashed), or to bring your changes with you to the new branch. Just choose the second option, to bring the changes to the new branch. You can then commit as usual.

GitHub Desktop

jQuery to loop through elements with the same class

I may be missing part of the question, but I believe you can simply do this:

$('.testimonial').each((index, element) => {
    if (/* Condition */) {
        // Do Something
    }
});

This uses jQuery's each method: https://learn.jquery.com/using-jquery-core/iterating/

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

HTML5 input type range show range value

I have a solution that involves (Vanilla) JavaScript, but only as a library. You habe to include it once and then all you need to do is set the appropriate source attribute of the number inputs.

The source attribute should be the querySelectorAll selector of the range input you want to listen to.

It even works with selectcs. And it works with multiple listeners. And it works in the other direction: change the number input and the range input will adjust. And it will work on elements added later onto the page (check https://codepen.io/HerrSerker/pen/JzaVQg for that)

Tested in Chrome, Firefox, Edge and IE11

_x000D_
_x000D_
;(function(){_x000D_
  _x000D_
  function emit(target, name) {_x000D_
    var event_x000D_
    if (document.createEvent) {_x000D_
      event = document.createEvent("HTMLEvents");_x000D_
      event.initEvent(name, true, true);_x000D_
    } else {_x000D_
      event = document.createEventObject();_x000D_
      event.eventType = name;_x000D_
    }_x000D_
_x000D_
    event.eventName = name;_x000D_
_x000D_
    if (document.createEvent) {_x000D_
      target.dispatchEvent(event);_x000D_
    } else {_x000D_
      target.fireEvent("on" + event.eventType, event);_x000D_
    }    _x000D_
  }_x000D_
_x000D_
  var outputsSelector = "input[type=number][source],select[source]";_x000D_
  _x000D_
  function onChange(e) {_x000D_
    var outputs = document.querySelectorAll(outputsSelector)_x000D_
    for (var index = 0; index < outputs.length; index++) {_x000D_
      var item = outputs[index]_x000D_
      var source = document.querySelector(item.getAttribute('source'));_x000D_
      if (source) {_x000D_
        if (item === e.target) {_x000D_
          source.value = item.value_x000D_
          emit(source, 'input')_x000D_
          emit(source, 'change')_x000D_
        }_x000D_
_x000D_
        if (source === e.target) {_x000D_
          item.value = source.value_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  document.addEventListener('change', onChange)_x000D_
  document.addEventListener('input', onChange)_x000D_
}());
_x000D_
<div id="div">_x000D_
  <input name="example" type="range" max="2250000" min="-200000" value="0" step="50000">_x000D_
  <input id="example-value" type="number" max="2250000" min="-200000" value="0" step="50000" source="[name=example]">_x000D_
  <br>_x000D_
_x000D_
  <input name="example2" type="range" max="2240000" min="-160000" value="0" step="50000">_x000D_
  <input type="number" max="2240000" min="-160000" value="0" step="50000" source="[name=example2]">_x000D_
  <input type="number" max="2240000" min="-160000" value="0" step="50000" source="[name=example2]">_x000D_
  <br>_x000D_
  _x000D_
  <input name="example3" type="range" max="20" min="0" value="10" step="1">_x000D_
  <select source="[name=example3]">_x000D_
    <option value="0">0</option>_x000D_
    <option value="1">1</option>_x000D_
    <option value="2">2</option>_x000D_
    <option value="3">3</option>_x000D_
    <option value="4">4</option>_x000D_
    <option value="5">5</option>_x000D_
    <option value="6">6</option>_x000D_
    <option value="7">7</option>_x000D_
    <option value="8">8</option>_x000D_
    <option value="9">9</option>_x000D_
    <option value="10">10</option>_x000D_
    <option value="11">11</option>_x000D_
    <option value="12">12</option>_x000D_
    <option value="13">13</option>_x000D_
    <option value="14">14</option>_x000D_
    <option value="15">15</option>_x000D_
    <option value="16">16</option>_x000D_
    <option value="17">17</option>_x000D_
    <option value="18">18</option>_x000D_
    <option value="19">19</option>_x000D_
    <option value="20">20</option>_x000D_
  </select>_x000D_
  <br>_x000D_
  _x000D_
</div>_x000D_
<br>
_x000D_
_x000D_
_x000D_

Android Studio: Plugin with id 'android-library' not found

Use

apply plugin: 'com.android.library'

to convert an app module to a library module. More info here: https://developer.android.com/studio/projects/android-library.html

What's the difference between %s and %d in Python string formatting?

%d and %s are placeholders, they work as a replaceable variable. For example, if you create 2 variables

variable_one = "Stackoverflow"
variable_two = 45

you can assign those variables to a sentence in a string using a tuple of the variables.

variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"

Note that %s works for String and %d work for numerical or decimal variables.

if you print variable_3 it would look like this

print(variable_3 % (variable_one, variable_two))

I was searching for an answer in StackOverflow and found more than 45 answers to my question.

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

How do I ignore all files in a folder with a Git repository in Sourcetree?

  • Ignore all files in folder with Git in Sourcetree:

Ignore all files in folder with Git in Sourcetree

What is code coverage and how do YOU measure it?

Just remember, having "100% code-coverage" doesn't mean everything is tested completely - while it means every line of code is tested, it doesn't mean they are tested under every (common) situation..

I would use code-coverage to highlight bits of code that I should probably write tests for. For example, if whatever code-coverage tool shows myImportantFunction() isn't executed while running my current unit-tests, they should probably be improved.

Basically, 100% code-coverage doesn't mean your code is perfect. Use it as a guide to write more comprehensive (unit-)tests.

Get values from label using jQuery

Use .attr

$("current_month").attr("month")
$("current_month").attr("year")

And change the labels id to

<label year="2010" month="6" id="current_month"> June &nbsp;2010</label>

How to set background color in jquery

How about this:

$(this).css('background-color', '#FFFFFF');

Related post: Add background color and border to table row on hover using jquery

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

How do I get first element rather than using [0] in jQuery?

With the assumption that there's only one element:

 $("#grid_GridHeader")[0]
 $("#grid_GridHeader").get(0)
 $("#grid_GridHeader").get()

...are all equivalent, returning the single underlying element.

From the jQuery source code, you can see that get(0), under the covers, essentially does the same thing as the [0] approach:

 // Return just the object
 ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );

A method to count occurrences in a list

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

SOAP vs REST (differences)

Although SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are relevant because we can’t achieve any degree of standardization without them. REST needs no processing as an architecture style and is inherently more versatile. In the spirit of information exchange, both SOAP and REST depend on well-established laws that everybody has decided to abide by. The choice of SOAP vs. REST is dependent on the programming language you are using the environment you are using and the specifications.

Difference between HttpModule and HttpClientModule

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

It's an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects
  • Progress events for both request upload and response download

You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.

  • Typed, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsed
  • Post-request verification & flush based testing framework

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.

Also pay attention that old http was injected using Http class token instead of the new HttpClient:

import { HttpModule } from '@angular/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you're using SystemJS:

map: {
     ...
    'tslib': 'npm:tslib/tslib.js',

And you need to add another mapping if you use SystemJS:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

Use of 'const' for function parameters

I tend to use const wherever possible. (Or other appropriate keyword for the target language.) I do this purely because it allows the compiler to make extra optimizations that it would not be able to make otherwise. Since I have no idea what these optimizations may be, I always do it, even where it seems silly.

For all I know, the compiler might very well see a const value parameter, and say, "Hey, this function isn't modifying it anyway, so I can pass by reference and save some clock cycles." I don't think it ever would do such a thing, since it changes the function signature, but it makes the point. Maybe it does some different stack manipulation or something... The point is, I don't know, but I do know trying to be smarter than the compiler only leads to me being shamed.

C++ has some extra baggage, with the idea of const-correctness, so it becomes even more important.

Exception.Message vs Exception.ToString()

Converting the WHOLE Exception To a String

Calling Exception.ToString() gives you more information than just using the Exception.Message property. However, even this still leaves out lots of information, including:

  1. The Data collection property found on all exceptions.
  2. Any other custom properties added to the exception.

There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.

public static class ExceptionExtensions
{
    public static string ToDetailedString(this Exception exception) =>
        ToDetailedString(exception, ExceptionOptions.Default);

    public static string ToDetailedString(this Exception exception, ExceptionOptions options)
    {
        if (exception == null)
        {
            throw new ArgumentNullException(nameof(exception));
        } 

        var stringBuilder = new StringBuilder();

        AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);

        foreach (PropertyInfo property in exception
            .GetType()
            .GetProperties()
            .OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
            .ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
        {
            var value = property.GetValue(exception, null);
            if (value == null && options.OmitNullProperties)
            {
                if (options.OmitNullProperties)
                {
                    continue;
                }
                else
                {
                    value = string.Empty;
                }
            }

            AppendValue(stringBuilder, property.Name, value, options);
        }

        return stringBuilder.ToString().TrimEnd('\r', '\n');
    }

    private static void AppendCollection(
        StringBuilder stringBuilder,
        string propertyName,
        IEnumerable collection,
        ExceptionOptions options)
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} =");

            var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);

            var i = 0;
            foreach (var item in collection)
            {
                var innerPropertyName = $"[{i}]";

                if (item is Exception)
                {
                    var innerException = (Exception)item;
                    AppendException(
                        stringBuilder,
                        innerPropertyName,
                        innerException,
                        innerOptions);
                }
                else
                {
                    AppendValue(
                        stringBuilder,
                        innerPropertyName,
                        item,
                        innerOptions);
                }

                ++i;
            }
        }

    private static void AppendException(
        StringBuilder stringBuilder,
        string propertyName,
        Exception exception,
        ExceptionOptions options)
    {
        var innerExceptionString = ToDetailedString(
            exception, 
            new ExceptionOptions(options, options.CurrentIndentLevel + 1));

        stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
        stringBuilder.AppendLine(innerExceptionString);
    }

    private static string IndentString(string value, ExceptionOptions options)
    {
        return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
    }

    private static void AppendValue(
        StringBuilder stringBuilder,
        string propertyName,
        object value,
        ExceptionOptions options)
    {
        if (value is DictionaryEntry)
        {
            DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
        }
        else if (value is Exception)
        {
            var innerException = (Exception)value;
            AppendException(
                stringBuilder,
                propertyName,
                innerException,
                options);
        }
        else if (value is IEnumerable && !(value is string))
        {
            var collection = (IEnumerable)value;
            if (collection.GetEnumerator().MoveNext())
            {
                AppendCollection(
                    stringBuilder,
                    propertyName,
                    collection,
                    options);
            }
        }
        else
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
        }
    }
}

public struct ExceptionOptions
{
    public static readonly ExceptionOptions Default = new ExceptionOptions()
    {
        CurrentIndentLevel = 0,
        IndentSpaces = 4,
        OmitNullProperties = true
    };

    internal ExceptionOptions(ExceptionOptions options, int currentIndent)
    {
        this.CurrentIndentLevel = currentIndent;
        this.IndentSpaces = options.IndentSpaces;
        this.OmitNullProperties = options.OmitNullProperties;
    }

    internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }

    internal int CurrentIndentLevel { get; set; }

    public int IndentSpaces { get; set; }

    public bool OmitNullProperties { get; set; }
}

Top Tip - Logging Exceptions

Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.

Top Tip - Human Readable Stack Traces

You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

The issue of erroneous leftover entries in the .csproj file still occurs with VS2015update3 and can also occur if you try to change the signing certificate for a different one (even if that is one generated using the 'new' option in the certificate selection dropdown). The advice in the accepted answer (mark as not signed, save, unload project, edit .csproj, remove the properties relating to the old certificates/thumbprints/keys & reload project, set certificate) is reliable.

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

How to include js and CSS in JSP with spring MVC

Put your style.css directly into the webapp/css folder, not into the WEB-INF folder.

Then add the following code into your spring-dispatcher-servlet.xml

<mvc:resources mapping="/css/**" location="/css/" />

and then add following code into your jsp page

<link rel="stylesheet" type="text/css" href="css/style.css"/>

I hope it will work.

Which ChromeDriver version is compatible with which Chrome Browser version?

In case of mine, I solved it just by npm install protractor@latest -g and npm install webdriver-manager@latest. I am using chrome 80.x version. It worked for me in both Angular 4 & 6

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}

Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:

flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only

Then you can fix it by running the following commands:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Creating an empty Pandas DataFrame, then filling it?

Here's a couple of suggestions:

Use date_range for the index:

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')

columns = ['A','B', 'C']

Note: we could create an empty DataFrame (with NaNs) simply by writing:

df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs

To do these type of calculations for the data, use a numpy array:

data = np.array([np.arange(10)]*3).T

Hence we can create the DataFrame:

In [10]: df = pd.DataFrame(data, index=index, columns=columns)

In [11]: df
Out[11]: 
            A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

Can you split a stream into two streams?

How about:

Supplier<Stream<Integer>> randomIntsStreamSupplier =
    () -> (new Random()).ints(0, 2).boxed();

Stream<Integer> tails =
    randomIntsStreamSupplier.get().filter(x->x.equals(0));
Stream<Integer> heads =
    randomIntsStreamSupplier.get().filter(x->x.equals(1));

Get the previous month's first and last day dates in c#

using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

        var lastMonth = 1.Months().Ago().Date;
        var firstDayOfMonth = lastMonth.FirstDayOfMonth();
        var lastDayOfMonth = lastMonth.LastDayOfMonth();

What is Type-safe?

An explanation from a liberal arts major, not a comp sci major:

When people say that a language or language feature is type safe, they mean that the language will help prevent you from, for example, passing something that isn't an integer to some logic that expects an integer.

For example, in C#, I define a function as:

 void foo(int arg)

The compiler will then stop me from doing this:

  // call foo
  foo("hello world")

In other languages, the compiler would not stop me (or there is no compiler...), so the string would be passed to the logic and then probably something bad will happen.

Type safe languages try to catch more at "compile time".

On the down side, with type safe languages, when you have a string like "123" and you want to operate on it like an int, you have to write more code to convert the string to an int, or when you have an int like 123 and want to use it in a message like, "The answer is 123", you have to write more code to convert/cast it to a string.

No Network Security Config specified, using platform default - Android Log

I have a same problem, with volley, but this is my solution:

  1. In Android Manifiest, in tag application add:

    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
    
  2. create in folder xml this file network_security_config.xml and write this:

    <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
      </network-security-config>
    
  3. inside tag application add this tag:

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    

Get value when selected ng-option changes

I may be late for this but I had somewhat the same problem.

I needed to pass both the id and the name into my model but all the orthodox solutions had me make code on the controller to handle the change.

I macgyvered my way out of it using a filter.

<select 
        ng-model="selected_id" 
        ng-options="o.id as o.name for o in options" 
        ng-change="selected_name=(options|filter:{id:selected_id})[0].name">
</select>
<script>
  angular.module("app",[])
  .controller("ctrl",['$scope',function($scope){
    $scope.options = [
      {id:1, name:'Starbuck'},
      {id:2, name:'Appolo'},
      {id:3, name:'Saul Tigh'},
      {id:4, name:'Adama'}
    ]
  }])
</script>

The "trick" is here:

ng-change="selected_name=(options|filter:{id:selected_id})[0].name"

I'm using the built-in filter to retrieve the correct name for the id

Here's a plunkr with a working demo.

Regular expression matching a multiline block of text

The following is a regular expression matching a multiline block of text:

import re
result = re.findall('(startText)(.+)((?:\n.+)+)(endText)',input)

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

Add below code in your client code :

static {
    Security.insertProviderAt(new BouncyCastleProvider(),1);
 }

with this there is no need to add any entry in java.security file.

How to get datetime in JavaScript?

@Shadow Wizard's code should return 02:45 PM instead of 14:45 PM. So I modified his code a bit:

function getNowDateTimeStr(){
 var now = new Date();
 var hour = now.getHours() - (now.getHours() >= 12 ? 12 : 0);
return [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(hour), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
}

//Pad given value to the left with "0"
function AddZero(num) {
    return (num >= 0 && num < 10) ? "0" + num : num + "";
}

TypeError: 'undefined' is not an object

try out this if you want to assign value to object and it is showing this error in angular..

crate object in construtor

this.modelObj = new Model(); //<---------- after declaring object above

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}

How do I view the SSIS packages in SQL Server Management Studio?

  1. you could find it under intergration services option in object explorer.
  2. you could find the packages under integration services catalog where all packages are deployed.

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

Why is MySQL InnoDB insert so slow?

This is an old topic but frequently searched. So long as you are aware of risks (as stated by @philip Koshy above) of losing committed transactions in the last one second or so, before massive updates, you may set these global parameters

innodb_flush_log_at_trx_commit=0
sync_binlog=0

then turn then back on (if so desired) after update is complete.

innodb_flush_log_at_trx_commit=1
sync_binlog=1

for full ACID compliance.

There is a huge difference in write/update performance when both of these are turned off and on. In my experience, other stuff discussed above makes some difference but only marginal.

One other thing that impacts update/insert greatly is full text index. In one case, a table with two text fields having full text index, inserting 2mil rows took 6 hours and the same took only 10 min after full text index was removed. More indexes, more time. So search indexes other than unique and primary key may be removed prior to massive inserts/updates.

Bitwise operation and usage

the following bitwise operators: &, |, ^, and ~ return values (based on their input) in the same way logic gates affect signals. You could use them to emulate circuits.

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

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

Uncheck

"Work Offline"

in Settings -> Maven ! It worked for me ! :D

CSS Box Shadow - Top and Bottom Only

So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.

HTML

<div class="shadow-block">
    <div class="shadow"></div>
    <div class="overlay">
        <div class="overlay-inner">
            content here
        </div>
    </div>
</div>

CSS

.overlay {
    background: #f7f7f4;
    height: 185px;
    overflow: hidden;
    position: relative;
    width: 100%; 
}

.overlay:before {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
    content: " ";
    display: block;
    margin: 0 auto;
    width: 80%;
}

.overlay:after {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
    content: "-";
    display: block;
    margin: 0 auto;
    position: absolute;
    bottom: -65px;
    left: -50%;
    right: -50%;
    width: 80%;
}

.shadow {
    position: relative;
    width:100%;
    height:8px;
    margin: 0 0 -22px 0;
    -webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    border-radius: 50%;
}

Making a Bootstrap table column fit to content

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<h5>Left</h5>_x000D_
<table class="table table-responsive">_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th>Action</th>        _x000D_
            <th>Name</th>_x000D_
            <th>Payment Method</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td  style="width:1px; white-space:nowrap;">_x000D_
                <a role="button" class="btn btn-default btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">View</a>_x000D_
                <a role="button" class="btn btn-primary btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Edit</a>_x000D_
                <a role="button" class="btn btn-danger btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Delete</a>                _x000D_
            </td>        _x000D_
            <td>Bart Foo</td>_x000D_
            <td>Visa</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>_x000D_
_x000D_
<h5>Right</h5>_x000D_
_x000D_
<table class="table table-responsive">_x000D_
    <tbody>_x000D_
        <tr>                    _x000D_
            <th>Name</th>_x000D_
            <th>Payment Method</th>_x000D_
            <th>Action</th>            _x000D_
        </tr>_x000D_
        <tr>_x000D_
_x000D_
            <td>Bart Foo</td>_x000D_
            <td>Visa</td>_x000D_
            <td  style="width:1px; white-space:nowrap;">_x000D_
                <a role="button" class="btn btn-default btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">View</a>_x000D_
                <a role="button" class="btn btn-primary btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Edit</a>_x000D_
                <a role="button" class="btn btn-danger btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Delete</a>                _x000D_
            </td>            _x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Better way to find control in ASP.NET

I decided to just build controls dictionaries. Harder to maintain, might run faster than the recursive FindControl().

protected void Page_Load(object sender, EventArgs e)
{
  this.BuildControlDics();
}

private void BuildControlDics()
{
  _Divs = new Dictionary<MyEnum, HtmlContainerControl>();
  _Divs.Add(MyEnum.One, this.divOne);
  _Divs.Add(MyEnum.Two, this.divTwo);
  _Divs.Add(MyEnum.Three, this.divThree);

}

And before I get down-thumbs for not answering the OP's question...

Q: Now, my question is that is there any other way/solution to find the nested control in ASP.NET? A: Yes, avoid the need to search for them in the first place. Why search for things you already know are there? Better to build a system allowing reference of known objects.

filtering NSArray into a new NSArray in Objective-C

Assuming that your objects are all of a similar type you could add a method as a category of their base class that calls the function you're using for your criteria. Then create an NSPredicate object that refers to that method.

In some category define your method that uses your function

@implementation BaseClass (SomeCategory)
- (BOOL)myMethod {
    return someComparisonFunction(self, whatever);
}
@end

Then wherever you'll be filtering:

- (NSArray *)myFilteredObjects {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"myMethod = TRUE"];
    return [myArray filteredArrayUsingPredicate:pred];
}

Of course, if your function only compares against properties reachable from within your class it may just be easier to convert the function's conditions to a predicate string.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

Regex for allowing alphanumeric,-,_ and space

Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:

  • You can match alphanumeric with a \w, which is the same as [A-Za-z0-9_] in JavaScript (other languages can differ).
  • That leaves - and spaces, which can be combined into a matching set such as [\w\- ]. However, you may want to consider using \s instead of just the space character (\s also matches tabs, and other forms of whitespace)
    • Note that I'm escaping - as \- so that the regex engine doesn't confuse it with a character range like A-Z
  • Last up, you probably want to ensure that the entire string matches by anchoring the start and end via ^ and $

The full regex you're probably looking for is:

/^[\w\-\s]+$/

(Note that the + indicates that there must be at least one character for it to match; use a * instead, if a zero-length string is also ok)

Finally, http://www.regular-expressions.info/ is an awesome reference


Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.

For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/

How the int.TryParse actually works

Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788

How is Pythons glob.glob ordered?

I had a similar issue, glob was returning a list of file names in an arbitrary order but I wanted to step through them in numerical order as indicated by the file name. This is how I achieved it:

My files were returned by glob something like:

myList = ["c:\tmp\x\123.csv", "c:\tmp\x\44.csv", "c:\tmp\x\101.csv", "c:\tmp\x\102.csv", "c:\tmp\x\12.csv"]

I sorted the list in place, to do this I created a function:

def sortKeyFunc(s):
    return int(os.path.basename(s)[:-4])

This function returns the numeric part of the file name and converts to an integer.I then called the sort method on the list as such:

myList.sort(key=sortKeyFunc)

This returned a list as such:

["c:\tmp\x\12.csv", "c:\tmp\x\44.csv", "c:\tmp\x\101.csv", "c:\tmp\x\102.csv", "c:\tmp\x\123.csv"]

Axios having CORS issue

May help to someone:

I'm sending data from react application to golang server.

Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"). Error has fixed.

React form submit function:

async handleSubmit(e) {
    e.preventDefault();

    const headers = {
        'Content-Type': 'text/plain'
    };

    await axios.post(
        'http://localhost:3001/login',
        {
            user_name: this.state.user_name,
            password: this.state.password,
        },
        {headers}
        ).then(response => {
            console.log("Success ========>", response);
        })
        .catch(error => {
            console.log("Error ========>", error);
        }
    )
}

Go server got Router,

func main()  {
    router := mux.NewRouter()

    router.HandleFunc("/login", Login.Login).Methods("POST")

    log.Fatal(http.ListenAndServe(":3001", router))
}

Login.go,

func Login(w http.ResponseWriter, r *http.Request)  {

    var user = Models.User{}
    data, err := ioutil.ReadAll(r.Body)

    if err == nil {
        err := json.Unmarshal(data, &user)
        if err == nil {
            user = Postgres.GetUser(user.UserName, user.Password)
            w.Header().Set("Access-Control-Allow-Origin", "*")
            json.NewEncoder(w).Encode(user)
        }
    }
}

SQL 'like' vs '=' performance

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='600009'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

Exclude property from type

I've found solution with declaring some variables and using spread operator to infer type:

interface XYZ {
  x: number;
  y: number;
  z: number;
}

declare var { z, ...xy }: XYZ;

type XY = typeof xy; // { x: number; y: number; }

It works, but I would be glad to see a better solution.

What are the differences between NP, NP-Complete and NP-Hard?

In addition to the other great answers, here is the typical schema people use to show the difference between NP, NP-Complete, and NP-Hard:

enter image description here

Drop default constraint on a column in TSQL

I would like to refer a previous question, Because I have faced same problem and solved by this solution. First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from 
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where 
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

How does ApplicationContextAware work in Spring?

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.

So, it seemed to be invoked when Spring container has started, if you want to do something at that time.

It just has one method to set the context, so you will get the context and do something to sth now already in context I think.

EPPlus - Read Excel Table

I have got an error on the first answer so I have changed some code line.

Please try my new code, it's working for me.

using OfficeOpenXml;
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public static class ImportExcelReader
{
    public static List<T> ImportExcelToList<T>(this ExcelWorksheet worksheet) where T : new()
    {
        //DateTime Conversion
        Func<double, DateTime> convertDateTime = new Func<double, DateTime>(excelDate =>
        {
            if (excelDate < 1)
            {
                throw new ArgumentException("Excel dates cannot be smaller than 0.");
            }

            DateTime dateOfReference = new DateTime(1900, 1, 1);

            if (excelDate > 60d)
            {
                excelDate = excelDate - 2;
            }
            else
            {
                excelDate = excelDate - 1;
            }

            return dateOfReference.AddDays(excelDate);
        });

        ExcelTable table = null;

        if (worksheet.Tables.Any())
        {
            table = worksheet.Tables.FirstOrDefault();
        }
        else
        {
            table = worksheet.Tables.Add(worksheet.Dimension, "tbl" + ShortGuid.NewGuid().ToString());

            ExcelAddressBase newaddy = new ExcelAddressBase(table.Address.Start.Row, table.Address.Start.Column, table.Address.End.Row + 1, table.Address.End.Column);

            //Edit the raw XML by searching for all references to the old address
            table.TableXml.InnerXml = table.TableXml.InnerXml.Replace(table.Address.ToString(), newaddy.ToString());
        }

        //Get the cells based on the table address
        List<IGrouping<int, ExcelRangeBase>> groups = table.WorkSheet.Cells[table.Address.Start.Row, table.Address.Start.Column, table.Address.End.Row, table.Address.End.Column]
            .GroupBy(cell => cell.Start.Row)
            .ToList();

        //Assume the second row represents column data types (big assumption!)
        List<Type> types = groups.Skip(1).FirstOrDefault().Select(rcell => rcell.Value.GetType()).ToList();

        //Get the properties of T
        List<PropertyInfo> modelProperties = new T().GetType().GetProperties().ToList();

        //Assume first row has the column names
        var colnames = groups.FirstOrDefault()
            .Select((hcell, idx) => new
            {
                Name = hcell.Value.ToString(),
                index = idx
            })
            .Where(o => modelProperties.Select(p => p.Name).Contains(o.Name))
            .ToList();

        //Everything after the header is data
        List<List<object>> rowvalues = groups
            .Skip(1) //Exclude header
            .Select(cg => cg.Select(c => c.Value).ToList()).ToList();

        //Create the collection container
        List<T> collection = new List<T>();
        foreach (List<object> row in rowvalues)
        {
            T tnew = new T();
            foreach (var colname in colnames)
            {
                //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                object val = row[colname.index];
                Type type = types[colname.index];
                PropertyInfo prop = modelProperties.FirstOrDefault(p => p.Name == colname.Name);

                //If it is numeric it is a double since that is how excel stores all numbers
                if (type == typeof(double))
                {
                    //Unbox it
                    double unboxedVal = (double)val;

                    //FAR FROM A COMPLETE LIST!!!
                    if (prop.PropertyType == typeof(int))
                    {
                        prop.SetValue(tnew, (int)unboxedVal);
                    }
                    else if (prop.PropertyType == typeof(double))
                    {
                        prop.SetValue(tnew, unboxedVal);
                    }
                    else if (prop.PropertyType == typeof(DateTime))
                    {
                        prop.SetValue(tnew, convertDateTime(unboxedVal));
                    }
                    else if (prop.PropertyType == typeof(string))
                    {
                        prop.SetValue(tnew, val.ToString());
                    }
                    else
                    {
                        throw new NotImplementedException(string.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                    }
                }
                else
                {
                    //Its a string
                    prop.SetValue(tnew, val);
                }
            }
            collection.Add(tnew);
        }

        return collection;
    }
}

How to call this function? please view below code;

private List<FundraiserStudentListModel> GetStudentsFromExcel(HttpPostedFileBase file)
    {
        List<FundraiserStudentListModel> list = new List<FundraiserStudentListModel>();
        if (file != null)
        {
            try
            {
                using (ExcelPackage package = new ExcelPackage(file.InputStream))
                {
                    ExcelWorkbook workbook = package.Workbook;
                    if (workbook != null)
                    {
                        ExcelWorksheet worksheet = workbook.Worksheets.FirstOrDefault();
                        if (worksheet != null)
                        {
                            list = worksheet.ImportExcelToList<FundraiserStudentListModel>();
                        }
                    }
                }
            }
            catch (Exception err)
            {
                //save error log
            }
        }
        return list;
    }

FundraiserStudentListModel here:

 public class FundraiserStudentListModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

Call a global variable inside module

For those who didn't know already, you would have to put the declare statement outside your class just like this:

declare var Chart: any;

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})

export class MyComponent {
    //you can use Chart now and compiler wont complain
    private color = Chart.color;
}

In TypeScript the declare keyword is used where you want to define a variable that may not have originated from a TypeScript file.

It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

Why would one omit the close tag?

Well, there are two ways of looking at it.

  1. PHP code is nothing more than a set of XML processing instructions, and therefore any file with a .php extension is nothing more than an XML file that just so happens to be parsed for PHP code.
  2. PHP just so happens to share the XML processing instruction format for its open and close tags. Based on that, files with .php extensions MAY be valid XML files, but they don't need to be.

If you believe the first route, then all PHP files require closing end tags. To omit them will create an invalid XML file. Then again, without having an opening <?xml version="1.0" charset="latin-1" ?> declaration, you won't have a valid XML file anyway... So it's not a major issue...

If you believe the second route, that opens the door for two types of .php files:

  • Files that contain only code (library files for example)
  • Files that contain native XML and also code (template files for example)

Based on that, code-only files are OK to end without a closing ?> tag. But the XML-code files are not OK to end without a closing ?> since it would invalidate the XML.

But I know what you're thinking. You're thinking what does it matter, you're never going to render a PHP file directly, so who cares if it's valid XML. Well, it does matter if you're designing a template. If it's valid XML/HTML, a normal browser will simply not display the PHP code (it's treated like a comment). So you can mock out the template without needing to run the PHP code within...

I'm not saying this is important. It's just a view that I don't see expressed too often, so what better place to share it...

Personally, I do not close tags in library files, but do in template files... I think it's a personal preference (and coding guideline) based more than anything hard...

SQL GROUP BY CASE statement with aggregate function

My guess is that you don't really want to GROUP BY some_product.

The answer to: "Is there a way to GROUP BY a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY a column alias.

The SELECT clause, where column aliases are assigned, is not processed until after the GROUP BY clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.

Inline view:

select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
   from ...
   group by col1, col2 ... ) T
group by some_product ...

CTE:

with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
   from ...
   group by col1, col2 ... )
select ...
from T
group by some_product ... 

How can I switch views programmatically in a view controller? (Xcode, iPhone)

Swift 3.0 Version

if you want to present new controller.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.present(viewController, animated: true, completion: nil)

and if you want to push to another controller (if it is in navigation)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.navigationController?.pushViewController(viewController, animated: true)

Comments in Markdown

The following works very well

<empty line>
[whatever comment text]::

that method takes advantage of syntax to create links via reference
since link reference created with [1]: http://example.org will not be rendered, likewise any of the following will not be rendered as well

<empty line>
[whatever]::
[whatever]:whatever
[whatever]: :
[whatever]: whatever

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

T-SQL How to select only Second row from a table?

No need of row number functions if field ID is unique.

SELECT TOP 1 *
FROM (
  SELECT TOP 2 * 
  FROM yourTable
  ORDER BY ID
) z
ORDER BY ID DESC

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('[email protected]', 'test1234');
    }
}

def  d_email = "[email protected]",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "[email protected]",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

Python - Count elements in list

just do len(MyList)

This also works for strings, tuples, dict objects.

How can I make an EXE file from a Python program?

Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

How to pass multiple values to single parameter in stored procedure

Either use a User Defined Table

Or you can use CSV by defining your own CSV function as per This Post.

I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.

Cheers!

Windows Scipy Install: No Lapack/Blas Resources Found

For python27 1?Install numpy + mkl(download link:http://www.lfd.uci.edu/~gohlke/pythonlibs/) 2?install scipy (the same site) OK!

Remove padding or margins from Google Charts

By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:

// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
               'width': 350,
               'height': 400,
               'chartArea': {'width': '100%', 'height': '80%'},
               'legend': {'position': 'bottom'}
    };

If you want to tune it more, try changing these values or using other properties from the link above.

Inserting Data into Hive Table

It's a limitation of hive.

1.You cannot update data after it is inserted

2.There is no "insert into table values ... " statement

3.You can only load data using bulk load

4.There is not "delete from " command

5.You can only do bulk delete

But you still want to insert record from hive console than you can do select from statck. refer this

Posting array from form

Why are you sending it through a post if you already have it on the server (PHP) side?

Why not just save the array to the $_SESSION variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.

It will depend upon how you really want to do.

How to construct a relative path in Java from two absolute paths (or URLs)?

private String relative(String left, String right){
    String[] lefts = left.split("/");
    String[] rights = right.split("/");
    int min = Math.min(lefts.length, rights.length);
    int commonIdx = -1;
    for(int i = 0; i < min; i++){
        if(commonIdx < 0 && !lefts[i].equals(rights[i])){
            commonIdx = i - 1;
            break;
        }
    }
    if(commonIdx < 0){
        return null;
    }
    StringBuilder sb = new StringBuilder(Math.max(left.length(), right.length()));
    sb.append(left).append("/");
    for(int i = commonIdx + 1; i < lefts.length;i++){
        sb.append("../");
    }
    for(int i = commonIdx + 1; i < rights.length;i++){
        sb.append(rights[i]).append("/");
    }

    return sb.deleteCharAt(sb.length() -1).toString();
}

Attributes / member variables in interfaces?

In Java you can't. Interface has to do with methods and signature, it does not have to do with the internal state of an object -- that is an implementation question. And this makes sense too -- I mean, simply because certain attributes exist, it does not mean that they have to be used by the implementing class. getHeight could actually point to the width variable (assuming that the implementer is a sadist).

(As a note -- this is not true of all languages, ActionScript allows for declaration of pseudo attributes, and I believe C# does too)

Converting int to string in C

itoa() function is not defined in ANSI-C, so not implemented by default for some platforms (Reference Link).

s(n)printf() functions are easiest replacement of itoa(). However itoa (integer to ascii) function can be used as a better overall solution of integer to ascii conversion problem.

itoa() is also better than s(n)printf() as performance depending on the implementation. A reduced itoa (support only 10 radix) implementation as an example: Reference Link

Another complete itoa() implementation is below (Reference Link):

#include <stdbool.h> 
#include <string.h>

// A utility function to reverse a string 
char *reverse(char *str)
{
  char *p1, *p2;

  if (! str || ! *str)
        return str;
  for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
  {
        *p1 ^= *p2;
        *p2 ^= *p1;
        *p1 ^= *p2;
  }
  return str;
}
// Implementation of itoa() 
char* itoa(int num, char* str, int base) 
{ 
    int i = 0; 
    bool isNegative = false; 
  
    /* Handle 0 explicitely, otherwise empty string is printed for 0 */
    if (num == 0) 
    { 
        str[i++] = '0'; 
        str[i] = '\0'; 
        return str; 
    } 
  
    // In standard itoa(), negative numbers are handled only with  
    // base 10. Otherwise numbers are considered unsigned. 
    if (num < 0 && base == 10) 
    { 
        isNegative = true; 
        num = -num; 
    } 
  
    // Process individual digits 
    while (num != 0) 
    { 
        int rem = num % base; 
        str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0'; 
        num = num/base; 
    } 
  
    // If number is negative, append '-' 
    if (isNegative) 
        str[i++] = '-'; 
  
    str[i] = '\0'; // Append string terminator 
  
    // Reverse the string 
    reverse(str); 
  
    return str; 
} 

Another complete itoa() implementatiton: Reference Link

An itoa() usage example below (Reference Link):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
    int a=54325;
    char buffer[20];
    itoa(a,buffer,2);   // here 2 means binary
    printf("Binary value = %s\n", buffer);
 
    itoa(a,buffer,10);   // here 10 means decimal
    printf("Decimal value = %s\n", buffer);
 
    itoa(a,buffer,16);   // here 16 means Hexadecimal
    printf("Hexadecimal value = %s\n", buffer);
    return 0;
}

Display TIFF image in all web browser

This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:

http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support

Where are you getting the tiff images from? Is it possible for them to be generated in a different format?

If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.

If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.