Programs & Examples On #Census

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

Maximum and Minimum values for ints

The sys.maxint constant has been removed from Python 3.0 onward, instead use sys.maxsize.

Integers

  • PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.
  • PEP 238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)
  • The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
  • The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)
  • Octal literals are no longer of the form 0720; use 0o720 instead.

Refer : https://docs.python.org/3/whatsnew/3.0.html#integers

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

Sound effects in JavaScript / HTML5

Sounds like what you want is multi-channel sounds. Let's suppose you have 4 channels (like on really old 16-bit games), I haven't got round to playing with the HTML5 audio feature yet, but don't you just need 4 <audio> elements, and cycle which is used to play the next sound effect? Have you tried that? What happens? If it works: To play more sounds simultaneously, just add more <audio> elements.

I have done this before without the HTML5 <audio> element, using a little Flash object from http://flash-mp3-player.net/ - I wrote a music quiz (http://webdeavour.appspot.com/) and used it to play clips of music when the user clicked the button for the question. Initially I had one player per question, and it was possible to play them over the top of each other, so I changed it so there was only one player, which I pointed at different music clips.

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Callback functions in C++

The accepted answer is comprehensive but related to the question i just want to put an simple example here. I had a code that i'd written it a long time ago. i wanted to traverse a tree with in-order way (left-node then root-node then right-node) and whenever i reach to one Node i wanted to be able to call a arbitrary function so that it could do everything.

void inorder_traversal(Node *p, void *out, void (*callback)(Node *in, void *out))
{
    if (p == NULL)
        return;
    inorder_traversal(p->left, out, callback);
    callback(p, out); // call callback function like this.
    inorder_traversal(p->right, out, callback);
}


// Function like bellow can be used in callback of inorder_traversal.
void foo(Node *t, void *out = NULL)
{
    // You can just leave the out variable and working with specific node of tree. like bellow.
    // cout << t->item;
    // Or
    // You can assign value to out variable like below
    // Mention that the type of out is void * so that you must firstly cast it to your proper out.
    *((int *)out) += 1;
}
// This function use inorder_travesal function to count the number of nodes existing in the tree.
void number_nodes(Node *t)
{
    int sum = 0;
    inorder_traversal(t, &sum, foo);
    cout << sum;
}

 int main()
{

    Node *root = NULL;
    // What These functions perform is inserting an integer into a Tree data-structure.
    root = insert_tree(root, 6);
    root = insert_tree(root, 3);
    root = insert_tree(root, 8);
    root = insert_tree(root, 7);
    root = insert_tree(root, 9);
    root = insert_tree(root, 10);
    number_nodes(root);
}

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

How to fix 'Notice: Undefined index:' in PHP form action

if(!empty($_POST['filename'])){
$filename = $_POST['filename'];

echo $filename;
}

Can a Byte[] Array be written to a file in C#?

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

Bad Request, Your browser sent a request that this server could not understand

I got Bad Request, Your browser sent a request that this server could not understand when I tried to download a file to the target machine using curl.
I solved it by instead using scp to copy the file from the source machine to the target machine.

How do I get an apk file from an Android device?

As said above, you can get the apk by using the pull command in adb.

Since, you are talking about your installed applications, go ahead and look in the /data/app directory of your Android filesystem. You will find the APK's there.

Then use the adb command - adb pull /data/data/appname.apk

What is a good alternative to using an image map generator?

This service is the best in online image map editing I found so far : http://www.image-maps.com/

... but it is in fact a bit weak and I personnaly don't use it anymore. I switched to GIMP and it is indeed pretty good.

The answer from mobius is not wrong but in some cases you must use imagemaps even if it seems a bit old and rusty. For instance, in a newsletter, where you can't use HTML/CSS to do what you want.

Why doesn't TFS get latest get the latest?

TFS redefined what "Get Latest" does. In TFS terms, Get Latest means get the latest version of the files, but ignore the ones that the server thinks is already in your workspace. Which to me and just about everyone else on the planet is wrong.

See this link: http://blogs.microsoft.co.il/blogs/srlteam/archive/2009/04/13/how-get-latest-version-really-works.aspx

The only way to get it to do what you want is to Get Specific Version, then check both of the "Overwrite ..." boxes.

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Left Join With Where Clause

You might find it easier to understand by using a simple subquery

SELECT `settings`.*, (
    SELECT `value` FROM `character_settings`
    WHERE `character_settings`.`setting_id` = `settings`.`id`
      AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`

The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.

Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.

SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'

Node.js get file extension

This solution supports querystrings!

var Url = require('url');
var Path = require('path');

var url = 'http://i.imgur.com/Mvv4bx8.jpg?querystring=true';
var result = Path.extname(Url.parse(url).pathname); // '.jpg'

What is the curl error 52 "empty reply from server"?

this error also can happen if the server is processing the data. It usually happens to me when I do post some files to REST API websites that have many entries and take long for the records creation and return

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

How to write both h1 and h2 in the same line?

Keyword float:

<h1 style="text-align:left;float:left;">Title</h1> 
<h2 style="text-align:right;float:right;">Context</h2> 
<hr style="clear:both;"/>

PHP output showing little black diamonds with a question mark

I chose to strip these characters out of the string by doing this -

ini_set('mbstring.substitute_character', "none"); 
$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');

C# DataRow Empty-check

I know this has been answered already and it's an old question, but here's an extension method to do the same:

public static class DataExtensions
{
    public static bool AreAllCellsEmpty(this DataRow row)
    {
        var itemArray = row.ItemArray;
        if(itemArray==null)
            return true;
        return itemArray.All(x => string.IsNullOrWhiteSpace(x.ToString()));            
    }
}

And you use it like so:

if (dr.AreAllCellsEmpty())
// etc

How do you specify table padding in CSS? ( table, not cell padding )

You could set a margin for the table. Alternatively, wrap the table in a div and use the div's padding.

Android - How to achieve setOnClickListener in Kotlin?

**i have use kotlin-extension so i can access directly by button id:**


btnSignIN.setOnClickListener {
            if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
                if (checkValidation()) {

                    hitApiLogin()
                }
            }
        }

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use this to force IE to hide that annoying browser compatibility button in the address bar:

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

How to get WooCommerce order details

Accessing direct properties and related are explained

// Get an instance of the WC_Order object
            $order = wc_get_order($order_id);
            $order_data = array(
                    'order_id' => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
                    'status' => $order->get_status(),
                    'shipping_total' => $order->get_total_shipping(),
                    'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
                    'fee_total' => wc_format_decimal($fee_total, 2),
                    'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
                    'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
                    'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
                    'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
                    'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
                    'order_total' => wc_format_decimal($order->get_total(), 2),
                    'order_currency' => $order->get_currency(),
                    'payment_method' => $order->get_payment_method(),
                    'shipping_method' => $order->get_shipping_method(),
                    'customer_id' => $order->get_user_id(),
                    'customer_user' => $order->get_user_id(),
                    'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
                    'billing_first_name' => $order->get_billing_first_name(),
                    'billing_last_name' => $order->get_billing_last_name(),
                    'billing_company' => $order->get_billing_company(),
                    'billing_email' => $order->get_billing_email(),
                    'billing_phone' => $order->get_billing_phone(),
                    'billing_address_1' => $order->get_billing_address_1(),
                    'billing_address_2' => $order->get_billing_address_2(),
                    'billing_postcode' => $order->get_billing_postcode(),
                    'billing_city' => $order->get_billing_city(),
                    'billing_state' => $order->get_billing_state(),
                    'billing_country' => $order->get_billing_country(),
                    'shipping_first_name' => $order->get_shipping_first_name(),
                    'shipping_last_name' => $order->get_shipping_last_name(),
                    'shipping_company' => $order->get_shipping_company(),
                    'shipping_address_1' => $order->get_shipping_address_1(),
                    'shipping_address_2' => $order->get_shipping_address_2(),
                    'shipping_postcode' => $order->get_shipping_postcode(),
                    'shipping_city' => $order->get_shipping_city(),
                    'shipping_state' => $order->get_shipping_state(),
                    'shipping_country' => $order->get_shipping_country(),
                    'customer_note' => $order->get_customer_note(),
                    'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
            );

Additional details

  $line_items_shipping = $order->get_items('shipping');
            foreach ($line_items_shipping as $item_id => $item) {
                if (is_object($item)) {
                    if ($meta_data = $item->get_formatted_meta_data('')) :
                        foreach ($meta_data as $meta_id => $meta) :
                            if (in_array($meta->key, $line_items_shipping)) {
                                continue;
                            }
                            // html entity decode is not working preoperly
                            $shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('&times;', 'X', strip_tags($meta->display_value))));
                        endforeach;
                    endif;
                }
            }

            //get fee and total
            $fee_total = 0;
            $fee_tax_total = 0;

            foreach ($order->get_fees() as $fee_id => $fee) {

                $fee_items[] = implode('|', array(
                        'name:' .  html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
                        'total:' . wc_format_decimal($fee['line_total'], 2),
                        'tax:' . wc_format_decimal($fee['line_tax'], 2),
                ));

                $fee_total += $fee['line_total'];
                $fee_tax_total += $fee['line_tax'];
            }

            // get tax items
            foreach ($order->get_tax_totals() as $tax_code => $tax) {            
                $tax_items[] = implode('|', array(
                    'rate_id:'.$tax->id,
                    'code:' . $tax_code,
                    'total:' . wc_format_decimal($tax->amount, 2),
                    'label:'.$tax->label,                
                    'tax_rate_compound:'.$tax->is_compound,
                ));
            }

            // add coupons
            foreach ($order->get_items('coupon') as $_ => $coupon_item) {

                $coupon = new WC_Coupon($coupon_item['name']);

                $coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
                $discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
                $coupon_items[] = implode('|', array(
                        'code:' . $coupon_item['name'],
                        'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
                        'amount:' . wc_format_decimal($discount_amount, 2),
                ));
            }

            foreach ($order->get_refunds() as $refunded_items){
                $refund_items[] = implode('|', array(
                    'amount:' . $refunded_items->get_amount(),
            'reason:' . $refunded_items->get_reason(),
                    'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
                ));
            }

How to install SimpleJson Package for Python

Really simple way is:

pip install simplejson

How to display request headers with command line curl

The verbose option is handy, but if you want to see everything that curl does (including the HTTP body that is transmitted, and not just the headers), I suggest using one of the below options:

  • --trace-ascii - # stdout
  • --trace-ascii output_file.txt # file

PHP substring extraction. Get the string before the first '/' or the whole string

Using current on explode would ease the process.

 $str = current(explode("/", $str, 2));

What is the difference between dynamic and static polymorphism in Java?

  • Method overloading would be an example of static polymorphism

  • whereas overriding would be an example of dynamic polymorphism.

    Because, in case of overloading, at compile time the compiler knows which method to link to the call. However, it is determined at runtime for dynamic polymorphism

Can't append <script> element

You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:

const script = "console.log('Did it work?')"
new Promise((resolve, reject) => {
  (function(i,s,o,g,r,a,m){
      a=s.createElement(o),m=s.getElementsByTagName(o)[0];
      a.innerText=g;
      a.onload=r;m.parentNode.insertBefore(a,m)}
  )(window,document,'script',script, resolve())
}).then(() => console.log('Sure did!'))

It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

We can also try this solution

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");

in this the spring automatically finds the class in the class path itself

Current timestamp as filename in Java

try this one

String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

How to make a script wait for a pressed key?

I am new to python and I was already thinking I am too stupid to reproduce the simplest suggestions made here. It turns out, there's a pitfall one should know:

When a python-script is executed from IDLE, some IO-commands seem to behave completely different (as there is actually no terminal window).

Eg. msvcrt.getch is non-blocking and always returns $ff. This has already been reported long ago (see e.g. https://bugs.python.org/issue9290 ) - and it's marked as fixed, somehow the problem seems to persist in current versions of python/IDLE.

So if any of the code posted above doesn't work for you, try running the script manually, and NOT from IDLE.

Is there a way I can capture my iPhone screen as a video?

Just for anyone who is still looking for solutions:

The RecordMyScreen jailbreak app is opensourced and works fine even on non-jailbreak devices if we have the developer license. You can have a look at the source: https://github.com/coolstar/RecordMyScreen

Alternative to mysql_real_escape_string without connecting to DB

It is impossible to safely escape a string without a DB connection. mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.

If you are only testing, then you may as well use mysql_escape_string(), it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.

Import and Export Excel - What is the best library?

I've worked with excel jetcell for a long time and can really recommend it. http://www.devtriogroup.com/exceljetcell

  • Commercial product
  • Excel files XLS & XLSX
  • Based on own engine in pure net.

How can I parse a String to BigDecimal?

Try this

// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);

// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);

If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)

Also keep in mind that decimalFormat.parse can throw a ParseException so you need to handle it (with try/catch) or throw it and let another part of your program handle it

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

How to get row number from selected rows in Oracle

I think using

select rownum st.Branch 
  from student st 
 where st.name like '%ram%'

is a simple way; you should add single quotes in the LIKE statement. If you use row_number(), you should add over (order by 'sort column' 'asc/desc'), for instance:

select st.branch, row_number() over (order by 'sort column' 'asc/desc')  
  from student st 
 where st.name like '%ram%'

Configuring user and password with Git Bash

If your repo is of HTTPS repo, git config -e give this command in the git bash. Update the username and password by opening in insert mode, change the password or username give :x and Cntrl+z keys it will save and exit

So, From then while you pull / push the code to the repository it will not ask for password.

wkhtmltopdf: cannot connect to X server

Just tell the Qt backend to not use X:

QT_QPA_PLATFORM=offscreen wkhtmltopdf <input> <outfile.pdf>

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Select multiple columns from a table, but group by one

I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

Example:

We have following table structure:

CREATE TABLE tablename(
    [msgid] [int] NOT NULL,
    [userid] [int] NOT NULL,
    [username] [varchar](70) NOT NULL,
    [message] [varchar](5000) NOT NULL
) 

Now there are at least two datasets in the table:

+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
|     1 |      1 | userA    | hello   |
|     2 |      1 | userB    | world   |
+-------+--------+----------+---------+

Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

SELECT m.userid, 
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
Out[222]: 
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
Out[224]: 
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
Out[227]: 
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

Ruby: How to turn a hash into HTTP parameters?

Here's a short and sweet one liner if you only need to support simple ASCII key/value query strings:

hash = {"foo" => "bar", "fooz" => 123}
# => {"foo"=>"bar", "fooz"=>123}
query_string = hash.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
# => "foo=bar&fooz=123"

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

If you don't want to change your table structure, you can run the following query:

ALTER TABLE [UserStore] 
NOCHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT  FK_UserIdentity_User_UserId

BEGIN TRAN

UPDATE  [user] 
SET Id = 10
WHERE Id = 9

UPDATE  [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9

UPDATE  [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9

COMMIT TRAN

ALTER TABLE [UserStore] 
CHECK CONSTRAINT FK_UserStore_User_UserId

ALTER TABLE UserIdentity 
CHECK CONSTRAINT FK_UserIdentity_User_UserId

c++ string array initialization

In C++11 you can. A note beforehand: Don't new the array, there's no need for that.

First, string[] strArray is a syntax error, that should either be string* strArray or string strArray[]. And I assume that it's just for the sake of the example that you don't pass any size parameter.

#include <string>

void foo(std::string* strArray, unsigned size){
  // do stuff...
}

template<class T>
using alias = T;

int main(){
  foo(alias<std::string[]>{"hi", "there"}, 2);
}

Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!

template<unsigned N>
void foo(int const (&arr)[N]){
  // ...
}

Note that this will only match stack arrays, like int x[5] = .... Or temporary ones, created by the use of alias above.

int main(){
  foo(alias<int[]>{1, 2, 3});
}

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

I had a special case of this: I had a file with --assume-unchanged on it. It was hard to locate, as the git status command was not showing any changes

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL is a query language to operate on sets.

    It is more or less standardized, and used by almost all relational database management systems: SQL Server, Oracle, MySQL, PostgreSQL, DB2, Informix, etc.

  • PL/SQL is a proprietary procedural language used by Oracle

  • PL/pgSQL is a procedural language used by PostgreSQL

  • TSQL is a proprietary procedural language used by Microsoft in SQL Server.

Procedural languages are designed to extend SQL's abilities while being able to integrate well with SQL. Several features such as local variables and string/data processing are added. These features make the language Turing-complete.

They are also used to write stored procedures: pieces of code residing on the server to manage complex business rules that are hard or impossible to manage with pure set-based operations.

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

How do I convert a TimeSpan to a formatted string?

According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:

dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"

How to Define Callbacks in Android?

to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback):

Handler can be used to execute callbacks in the current or another thread, by passing it Messages. the Message holds data to be used from the callback. a Handler.Callback can be passed to the constructor of Handler in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:

Message message = new Message();
<set data to be passed to callback - eg message.obj, message.arg1 etc - here>

Callback callback = new Callback() {
    public boolean handleMessage(Message msg) {
        <code to be executed during callback>
    }
};

Handler handler = new Handler(callback);
handler.sendMessage(message);

EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):

post(new Runnable() {
    @Override
    public void run() {
        <code to be executed during callback>
    }
});

How to get complete month name from DateTime

You can use Culture to get month name for your country like:

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);

Simplest way to throw an error/exception with a custom message in Swift 2?

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

struct RuntimeError: LocalizedError
{
    let message: String

    init(_ message: String)
    {
        self.message = message
    }

    public var errorDescription: String?
    {
        return message
    }
}

See this answer for more details.

How do I make a WinForms app go Full Screen

You can use the following code to fit your system screen and task bar is visible.

    private void Form1_Load(object sender, EventArgs e)
    {   
        // hide max,min and close button at top right of Window
        this.FormBorderStyle = FormBorderStyle.None;
        // fill the screen
        this.Bounds = Screen.PrimaryScreen.Bounds;
    }

No need to use:

    this.TopMost = true;

That line interferes with alt+tab to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)

How to display raw JSON data on a HTML page

Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.

You have to decide if:

  1. You want to show the raw JSON (not an HTML page), as in your example
  2. Show an HTML page with formatted JSON

If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)

If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:

  • server-side, depending on your stack. There are solutions for almost every language
  • client-side with Javascript highlight libraries.

If you give more details about your stack, it's easier to provide examples or resources.

EDIT: For client side JS highlighting you can try higlight.js, for instance.

Job for mysqld.service failed See "systemctl status mysqld.service"

In my particular case, the error was appearing due to missing /var/log/mysql with mysql-server package 5.7.21-1 on Debian-based Linux distro. Having ran strace and sudo /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid ( which is what the systemd service actually runs), it became apparent that the issue was due to this:

2019-01-01T09:09:22.102568Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory

I've recently removed contents of several directories in /var/log so it was no surprise. The solution was to create the directory and make it owned by mysql user as in

$ sudo mkdir /var/log/mysql
$ sudo chown -R mysql:mysql /var/log/mysql

Having done that I've happily logged in via sudo mysql -u root and greeted with the old and familiar mysql> prompt

Video 100% width and height

_x000D_
_x000D_
<style>_x000D_
    .video{position:absolute;top:0;left:0;height:100%;width:100%;object-fit:cover}_x000D_
  }_x000D_
</style>_x000D_
<video class= "video""_x000D_
  disableremoteplayback=""_x000D_
  mqn-lazyimage-video-no-play=""_x000D_
  mqn-video-css-triggers="[{&quot;fire_once&quot;: true, &quot;classes&quot;: [&quot;.mqn2-ciu&quot;], &quot;from&quot;: 1, &quot;class&quot;: &quot;mqn2-grid-1--hero-intro-video-meta-visible&quot;}]"_x000D_
  mqn-video-inview-no-reset="" mqn-video-inview-play="" muted="" playsinline="" autoplay>_x000D_
_x000D_
<source src="https://github.com/Slender1808/Web-Adobe-XD/raw/master/Home/0013-0140.mp4" type="video/mp4">_x000D_
_x000D_
</video>
_x000D_
_x000D_
_x000D_

LINQ Where with AND OR condition

Linq With Or Condition by using Lambda expression you can do as below

DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));

dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);


var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
            == 1 || emp.Field<int>("EmpID") == 2);

foreach (DataRow row in res2)
{
    Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
}

Adding click event for a button created dynamically using jQuery

Just create a button element with jQuery, and add the event handler when you create it :

var div = $('<div />', {'data-role' : 'fieldcontain'}),
    btn = $('<input />', {
              type  : 'button',
              value : 'Dynamic Button',
              id    : 'btn_a',
              on    : {
                 click: function() {
                     alert ( this.value );
                 }
              }
          });

div.append(btn).appendTo( $('#pg_menu_content').empty() );

FIDDLE

Generate random number between two numbers in JavaScript

Try using:

_x000D_
_x000D_
function random(min, max) {_x000D_
   return Math.round((Math.random() *( Math.abs(max - min))) + min);_x000D_
}_x000D_
console.log(random(1, 6));
_x000D_
_x000D_
_x000D_

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

What is a JavaBean exactly?

A Java Bean is a component or the basic building block in the JavaBeans architecture. The JavaBeans architecture is a component architecture that benefits from reusability and interoperability of a component-based approach.

A valid component architecture should allow programs to be assembled from software building blocks (Beans in this case), perhaps provided by different vendors and also make it possible for an architect / developer to select a component (Bean), understand its capabilities, and incorporate it into an application.

Since classes/objects are the basic building blocks of an OOP language like Java, they are the natural contenders for being the Bean in the JavaBeans architecture.

The process of converting a plain Java class to a Java bean is actually nothing more than making it a reusable and interoperable component. This would translate into a Java class having abilities like:

  1. controlling the properties, events, and methods of a class that are exposed to another application. (You can have a BeanInfo class that reports only those properties, events and methods that the external application needs.)
  2. persistence (being serialisable or externizable - this would also imply having no-argument constructors, using transient for fields)
  3. ability to register for events and also to generate events (e.g., making use of bound and constraint properties)
  4. customizers (to customise the Bean via GUIs or by providing documentation)

In order for a Java class to be termed a Java bean it is not necessary that they need to possess all the above abilities. Instead, it implies to implement a subset of the above relevant to the context (e.g., a bean in a certain framework may not need customizers, some other bean may not need bound and constrained properties, etc.)

Almost all leading frameworks and libraries in Java adhere to the JavaBeans architecture implicitly, in order to reap the above benefits.

How to pass password automatically for rsync SSH command?

You should use a keyfile without passphrase for scripted ssh logins. This is obviously a security risk, take care that the keyfile itself is adequately secured.

Instructions for setting up passwordless ssh access

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

Find the number of downloads for a particular app in apple appstore

I think developers can do this for their own apps via iTunes Connect but this doesn't help you if you are looking for stats on other peoples apps.

148Apps also have some aggregate AppStore metrics on their web site that could be useful to you but, again, doesn't really give a low-level breakdown of numbers.

You could also scrape some stats from the RSS feeds generated by the iTunes Store RSS Generator but, again, this just gets currently popular apps rather than actual download numbers.

How to create a sticky footer that plays well with Bootstrap 3

   <style type="text/css">

     /* Sticky footer styles
     -------------------------------------------------- */

     html,
     body {
       height: 100%;
       /* The html and body elements cannot have any padding or margin. */
     }

     /* Wrapper for page content to push down footer */
     #wrap {
       min-height: 100%;
       height: auto !important;
       height: 100%;
       /* Negative indent footer by it's height */
       margin: 0 auto -60px;
     }

     /* Set the fixed height of the footer here */
     #push,
     #footer {
       height: 60px;
     }
     #footer {
       background-color: #f5f5f5;
     }

     /* Lastly, apply responsive CSS fixes as necessary */
     @media (max-width: 767px) {
       #footer {
         margin-left: -20px;
         margin-right: -20px;
         padding-left: 20px;
         padding-right: 20px;
       }
     }



     /* Custom page CSS
     -------------------------------------------------- */
     /* Not required for template or sticky footer method. */

     .container {
       width: auto;
       max-width: 680px;
     }
     .container .credit {
       margin: 20px 0;
     }

   </style>


<div id="wrap">

  <!-- Begin page content -->
  <div class="container">
    <div class="page-header">
      <h1>Sticky footer</h1>
    </div>
    <p class="lead">Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS.</p>
    <p>Use <a href="./sticky-footer-navbar.html">the sticky footer</a> with a fixed navbar if need be, too.</p>
  </div>

  <div id="push"></div>
</div>

<div id="footer">
  <div class="container">
    <p class="muted credit">Example courtesy <a href="http://martinbean.co.uk">Martin Bean</a> and <a href="http://ryanfait.com/sticky-footer/">Ryan Fait</a>.</p>
  </div>
</div>

Should ol/ul be inside <p> or outside?

<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>

Because both <p> and <ol> are element rendered as block.

Swift: Testing optionals for nil

One of the most direct ways to use optionals is the following:

Assuming xyz is of optional type, like Int? for example.

if let possXYZ = xyz {
    // do something with possXYZ (the unwrapped value of xyz)
} else {
    // do something now that we know xyz is .None
}

This way you can both test if xyz contains a value and if so, immediately work with that value.

With regards to your compiler error, the type UInt8 is not optional (note no '?') and therefore cannot be converted to nil. Make sure the variable you're working with is an optional before you treat it like one.

Android, getting resource ID from string?

You can use this function to get resource ID.

public static int getResourceId(String pVariableName, String pResourcename, String pPackageName) 
{
    try {
        return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

So if you want to get for drawable call function like this

getResourceId("myIcon", "drawable", getPackageName());

and for string you can call it like this

getResourceId("myAppName", "string", getPackageName());

Read this

What is 'Currying'?

Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.

The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.

The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly.

For example:

function curryMinus(x) 
{
  return function(y) 
  {
    return x - y;
  }
}

var minus5 = curryMinus(1);
minus5(3);
minus5(5);

I can also do...

var minus7 = curryMinus(7);
minus7(3);
minus7(5);

This is very great for making complex code neat and handling of unsynchronized methods etc.

How to find the length of a string in R

See ?nchar. For example:

> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10

PHP sessions default timeout

http://php.net/session.gc-maxlifetime

session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)

Matching an optional substring in a regex

You can do this:

([0-9]+) (\([^)]+\))? Z

This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).

show/hide a div on hover and hover out

Here are different method of doing this. And i found your code is even working fine.

Your code: http://jsfiddle.net/NKC2j/

Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/

Jquery fade toggle: http://jsfiddle.net/NKC2j/3/

Jquery slide toggle: http://jsfiddle.net/NKC2j/4/

And you can do this with CSS as answered by Sandeep

How to export data to CSV in PowerShell?

You can always use the

echo "Column1`tColumn2`tColumn3..." >> results.csv

You will need to put "`t" between the columns to separates the variables into their own column. Here is the way I wrote my script:

echo "Host`tState" >> results.csv
$names = Get-Content "hostlist.txt"
foreach ($name in $names) {
    $count = 0
    $count2 = 13490

    if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) {
        echo "$name`tUp" >> results.csv
    }
    else {
        echo "$name`tDown" >> results.csv
    }

    $count++
    Write-Progress -Activity "Gathering Information" -status "Pinging Hosts..." -percentComplete ($count / $count2 *100)

}

This is the easiest way to me. The output I get is :

Host|State
----------
H1  |Up
H2  |UP
H3  |Down

You can play around with the look, but that's the basic idea. The $count is just a progress bar if you want to spice up the look

MS-access reports - The search key was not found in any record - on save

I also got the message "The search key was not found in any record". When I moved my database from the network drive to my desktop, everything ran smoothly and faster. I didn't get the same error again.

Resize an Array while keeping current elements in Java?

Not nice, but works:

    int[] a = {1, 2, 3};
    // make a one bigger
    a = Arrays.copyOf(a, a.length + 1);
    for (int i : a)
        System.out.println(i);

as stated before, go with ArrayList

How to detect the swipe left or Right in Android?

Left to Right and Right to Left Swipe Detector

Firstly, declare two variable of float datatype.

private float x1, x2;

Secondly, wireup your xml view in java. Like I have ImageView

ImageView img = (ImageView) findViewById(R.id.imageView);

Thirdly, setOnTouchListener on your ImageView.

img.setOnTouchListener(
                    new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // TODO Auto-generated method stub
                        switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            x1 = event.getX();
                            break;
                        case MotionEvent.ACTION_UP:
                            x2 = event.getX();
                            float deltaX = x2 - x1;
                            if (deltaX < 0) {
                                Toast.makeText(MainActivity.this,
                                        "Right to Left swipe",
                                        Toast.LENGTH_SHORT).show();
                            }else if(deltaX >0){
                                Toast.makeText(MainActivity.this,
                                        "Left to Right swipe",
                                        Toast.LENGTH_SHORT).show();
                            }
                            break;
                        }

                        return false;
                    }
                });

How can I set a DateTimePicker control to a specific date?

This oughta do it.

DateTimePicker1.Value = DateTime.Now.AddDays(-1).Date;

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Converting XDocument to XmlDocument and vice versa

If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:

using System.Xml; 
using System.Xml.Linq;

namespace www.dimaka.com
{ 
    internal static class LinqHelper 
    { 
        public static XmlDocument ToXmlDocument(this XDocument xDocument) 
        { 
            var xmlDocument = new XmlDocument(); 
            using (var reader = xDocument.CreateReader()) 
            { 
                xmlDocument.Load(reader); 
            }

            var xDeclaration = xDocument.Declaration; 
            if (xDeclaration != null) 
            { 
                var xmlDeclaration = xmlDocument.CreateXmlDeclaration( 
                    xDeclaration.Version, 
                    xDeclaration.Encoding, 
                    xDeclaration.Standalone);

                xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild); 
            }

            return xmlDocument; 
        } 
    } 
}

Hope that helps!

How do I multiply each element in a list by a number?

Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.

using for loop

lst = [5, 20 ,15]
product = []
for i in lst:
    product.append(i*5)
print product

using list comprehension, this is also same as using for-loop but more 'pythonic'

lst = [5, 20 ,15]

prod = [i * 5 for i in lst]
print prod

php codeigniter count rows

Try This :) I created my on model of count all results

in library_model

function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
        $this->db->select($column_name);
        // If Where is not NULL
        if(!empty($where) && count($where) > 0 )
        {
            $this->db->where($where);
        }
        // Return Count Column
        return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}

Your Controller will look like this

public function my_method()
{
  $data = array(
     $countall = $this->model->your_method_model()
  );
   $this->load->view('page',$data);
}

Then Simple Call The Library Model In Your Model

function your_method_model()
{
        return $this->library_model->count_all_results(
               ['id'],
               ['where],
               ['table name']
           );
}

Specify JDK for Maven to use

I had build problem with maven within Eclipse on Windows 7.

Though I observed mvn build was running just fine from command line.

mvn -T 5 -B -e -X -U -P test clean install -Dmaven.surefire.debug  --settings ..\..\infra-scripts\maven-conf\settings.xml   > output.log

Eclipse was considering as default JVM a JRE installation instead of JDK so it was failing on compilation.

I added to eclipse.ini following line:

-vm
C:\Program Files (x86)\Java\jdk1.8.0_25\bin

Also when starting from eclipse I used in "Goals" section following list:

-T 5 -B -e -X -U -P test clean install -Dmaven.surefire.debug  --settings ..\..\infra-scripts\maven-conf\settings.xml

Compilation error got solved.

Java Does Not Equal (!=) Not Working?

Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:

if ("success" != statusCheck.intern())

intern method is part of standard Java String API.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If you are fine with truncating the table of the model in question, you can specify a one-off default value of None in the prompt. The migration will have superfluous default=None while your code has no default. It can be applied just fine because there's no data in the table anymore which would require a default.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Using the :not() pseudo class:

For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class. The :not() pseudo class requires a CSS selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.

Examples:

_x000D_
_x000D_
/* This query selects All div elements except for   */_x000D_
div:not(.foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
   for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
  color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
  <nav id="foo">test</nav>_x000D_
  <nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:

_x000D_
_x000D_
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
  color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
_x000D_
_x000D_

Permissions error when connecting to EC2 via SSH on Mac OSx

+1

I noticed that for some AMIs like Amazon Linux, [email protected] would work. But for an ubuntu image, I had to use ubuntu@ instead. It was never a problem with the .pem, just with the user name.

JPA: unidirectional many-to-one and cascading delete

@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Given annotation worked for me. Can have a try

For Example :-

     public class Parent{
            @Id
            @GeneratedValue(strategy=GenerationType.AUTO)
            @Column(name="cct_id")
            private Integer cct_id;
            @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
            @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
            private List<Child> childs;
        }
            public class Child{
            @ManyToOne(fetch=FetchType.EAGER)
            @JoinColumn(name="cct_id")
            private Parent parent;
    }

load csv into 2D matrix with numpy for plotting

I think using dtype where there is a name row is confusing the routine. Try

>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111196e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111311e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29112065e+12]])
>>> r[:,0]    # Slice 0'th column
array([ 611.88243,  611.88243,  611.88243])

cast a List to a Collection

There have multiple solusions to convert list to a collection

Solution 1

List<Contact> CONTACTS = new ArrayList<String>();
// fill CONTACTS
Collection<Contact> c = CONTACTS;

Solution 2

private static final Collection<String> c = new ArrayList<String>(
                                                Arrays.asList("a", "b", "c"));

Solution 3

private static final Collection<Contact> = new ArrayList<Contact>(
                       Arrays.asList(new Contact("text1", "name1")
                                     new Contact("text2", "name2")));

Solution 4

List<? extends Contact> col = new ArrayList<Contact>(CONTACTS);

Creating a singleton in Python

Using a function attribute is also very simple

def f():
    if not hasattr(f, 'value'):
        setattr(f, 'value', singletonvalue)
    return f.value

Why does using an Underscore character in a LIKE filter give me all the results?

Underscore is a wildcard for something. for example 'A_%' will look for all match that Start whit 'A' and have minimum 1 extra character after that

SVN - Checksum mismatch while updating

I found very nice solution, that SOLVED my problem. The trick is to edit the svn DB (wc.db).

The solution is described on this page : http://www.exchangeconcept.com/2015/01/svn-e155037-previous-operation-has-not-finished-run-cleanup-if-it-was-interrupted/

If link is down, just look and follow this instructions: enter image description here

I used sqlite tool from http://sqlitebrowser.org/.

Replace string within file contents

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)

How can bcrypt have built-in salts?

This is bcrypt:

Generate a random salt. A "cost" factor has been pre-configured. Collect a password.

Derive an encryption key from the password using the salt and cost factor. Use it to encrypt a well-known string. Store the cost, salt, and cipher text. Because these three elements have a known length, it's easy to concatenate them and store them in a single field, yet be able to split them apart later.

When someone tries to authenticate, retrieve the stored cost and salt. Derive a key from the input password, cost and salt. Encrypt the same well-known string. If the generated cipher text matches the stored cipher text, the password is a match.

Bcrypt operates in a very similar manner to more traditional schemes based on algorithms like PBKDF2. The main difference is its use of a derived key to encrypt known plain text; other schemes (reasonably) assume the key derivation function is irreversible, and store the derived key directly.


Stored in the database, a bcrypt "hash" might look something like this:

$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa

This is actually three fields, delimited by "$":

  • 2a identifies the bcrypt algorithm version that was used.
  • 10 is the cost factor; 210 iterations of the key derivation function are used (which is not enough, by the way. I'd recommend a cost of 12 or more.)
  • vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa is the salt and the cipher text, concatenated and encoded in a modified Base-64. The first 22 characters decode to a 16-byte value for the salt. The remaining characters are cipher text to be compared for authentication.

This example is taken from the documentation for Coda Hale's ruby implementation.

Converting BigDecimal to Integer

TL;DR

Use one of these for universal conversion needs

//Java 7 or below
bigDecimal.setScale(0, RoundingMode.DOWN).intValueExact()
//Java 8    
bigDecimal.toBigInteger().intValueExact()

Reasoning

The answer depends on what the requirements are and how you answer these question.

  • Will the BigDecimal potentially have a non-zero fractional part?
  • Will the BigDecimal potentially not fit into the Integer range?
  • Would you like non-zero fractional parts rounded or truncated?
  • How would you like non-zero fractional parts rounded?

If you answered no to the first 2 questions, you could just use BigDecimal.intValueExact() as others have suggested and let it blow up when something unexpected happens.

If you are not absolutely 100% confident about question number 2, then intValue() is always the wrong answer.

Making it better

Let's use the following assumptions based on the other answers.

  • We are okay with losing precision and truncating the value because that's what intValueExact() and auto-boxing do
  • We want an exception thrown when the BigDecimal is larger than the Integer range because anything else would be crazy unless you have a very specific need for the wrap around that happens when you drop the high-order bits.

Given those params, intValueExact() throws an exception when we don't want it to if our fractional part is non-zero. On the other hand, intValue() doesn't throw an exception when it should if our BigDecimal is too large.

To get the best of both worlds, round off the BigDecimal first, then convert. This also has the benefit of giving you more control over the rounding process.

Spock Groovy Test

void 'test BigDecimal rounding'() {
    given:
    BigDecimal decimal = new BigDecimal(Integer.MAX_VALUE - 1.99)
    BigDecimal hugeDecimal = new BigDecimal(Integer.MAX_VALUE + 1.99)
    BigDecimal reallyHuge = new BigDecimal("10000000000000000000000000000000000000000000000")
    String decimalAsBigIntString = decimal.toBigInteger().toString()
    String hugeDecimalAsBigIntString = hugeDecimal.toBigInteger().toString()
    String reallyHugeAsBigIntString = reallyHuge.toBigInteger().toString()

    expect: 'decimals that can be truncated within Integer range to do so without exception'
    //GOOD: Truncates without exception
    '' + decimal.intValue() == decimalAsBigIntString
    //BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
    // decimal.intValueExact() == decimalAsBigIntString
    //GOOD: Truncates without exception
    '' + decimal.setScale(0, RoundingMode.DOWN).intValueExact() == decimalAsBigIntString

    and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
    //BAD: hugeDecimal.intValue() is -2147483648 instead of 2147483648
    //'' + hugeDecimal.intValue() == hugeDecimalAsBigIntString
    //BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
    //'' + hugeDecimal.intValueExact() == hugeDecimalAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + hugeDecimal.setScale(0, RoundingMode.DOWN).intValueExact() == hugeDecimalAsBigIntString

    and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
    //BAD: hugeDecimal.intValue() is 0
    //'' + reallyHuge.intValue() == reallyHugeAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + reallyHuge.intValueExact() == reallyHugeAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + reallyHuge.setScale(0, RoundingMode.DOWN).intValueExact() == reallyHugeAsBigIntString

    and: 'if using Java 8, BigInteger has intValueExact() just like BigDecimal'
    //decimal.toBigInteger().intValueExact() == decimal.setScale(0, RoundingMode.DOWN).intValueExact()
}

Regular Expression Validation For Indian Phone Number and Mobile number

You can use regular expression like this.

/^[(]+\ ++\d{2}[)]+[^0]+\d{9}/

How can I test a change made to Jenkinsfile locally?

In my development setup – missing a proper Groovy editor – a great deal of Jenkinsfile issues originates from simple syntax errors. To tackle this issue, you can validate the Jenkinsfile against your Jenkins instance (running at $JENKINS_HTTP_URL):

curl -X POST -H $(curl '$JENKINS_HTTP_URL/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') -F "jenkinsfile=<Jenkinsfile" $JENKINS_HTTP_URL/pipeline-model-converter/validate

The above command is a slightly modified version from https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Validating-(or-linting)-a-Declarative-Jenkinsfile-from-the-command-line

Max length for client ip address

People are talking about characters when one can compress an IP address into raw data.

So in principle, since we only use IPv4 (32bit) or IPv6 (128bit), that means you need at most 128 bits of space, or 128/8 = 16 bytes!

Which is much less than the suggested 39 bytes (assuming charset is ascii).

That said, you will have to decode and encode the IP address into/from the raw data, which in itself is a trivial thing to do (I've done it before, see PHP's ip2long() for 32-bit IPs).

Edit: inet_pton (and its opposite, inet_ntop()) does what you need, and works with both address types. But beware, on Windows it's available since PHP 5.3.

Turn off auto formatting in Visual Studio

Try disabling the extension Bundler & Minifier

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

How to embed a .mov file in HTML?

<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
    <param name="src" value="sample.mov">
    <param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
    <param name="autoplay" value="true">
    <param name="loop" value="false">
    <param name="controller" value="true">
    <embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>

source is the first search result of the Google

How to 'grep' a continuous stream?

Turn on grep's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)

tail -f file | grep --line-buffered my_pattern

It looks like a while ago --line-buffered didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).

Run a single test method with maven

There is an issue with surefire 2.12. This is what happen to me changing maven-surefire-plugin from 2.12 to 2.11:

  1. mvn test -Dtest=DesignRulesTest

    Result:
    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project pmd: No tests were executed!

  2. mvn test -Dtest=DesignRulesTest

    Result: [INFO] --- maven-surefire-plugin:2.11:test (default-test) @ pmd --- ... Running net.sourceforge.pmd.lang.java.rule.design.DesignRulesTest Tests run: 5, Failures: 0, Errors: 0, Skipped: 4, Time elapsed: 4.009 sec

"Port 4200 is already in use" when running the ng serve command

We can forcefully kill the port by following command.

kill -2 $(lsof -t -i:4200)

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

HTTPS using Jersey Client

Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :

System.setProperty("jsse.enableSNIExtension", "false");

(Courtesy to many stackoverflow answers combined together to figure this out)

The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
    public static ClientConfig configureClient()
    {
        System.setProperty("jsse.enableSNIExtension", "false");
        TrustManager[] certs = new TrustManager[]
        {
            new X509TrustManager()
            {
                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }

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

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException
                {
                }
            }
        };
        SSLContext ctx = null;
        try
        {
            ctx = SSLContext.getInstance("SSL");
            ctx.init(null, certs, new SecureRandom());
        }
        catch (java.security.GeneralSecurityException ex)
        {
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        ClientConfig config = new DefaultClientConfig();
        try
        {
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
                    new HostnameVerifier()
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            },
                    ctx));
        }
        catch (Exception e)
        {
        }
        return config;
    }

    public static Client createClient()
    {
        return Client.create(ClientHelper.configureClient());
    }

git stash apply version

To apply a stash and remove it from the stash list, run:

git stash pop stash@{n}

To apply a stash and keep it in the stash cache, run:

git stash apply stash@{n}

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

How to do a join in linq to sql with method syntax?

To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:

public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
    using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
    {
        var result = entityFrameworkObjectContext.SomeClass
            .Join(entityFrameworkObjectContext.SomeOtherClass,
                sc => sc.property1,
                soc => soc.property2,
                (sc, soc) => new {sc, soc})
            .Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
            .Select(s => new ThirdNonEntityClass 
            {
                dataValue1 = s.sc.dataValueA,
                dataValue2 = s.soc.dataValueB
            })
            .ToList();
    }

    return result;

}    

Pay special attention to the intermediate object that is created in the Where and Select clauses.

Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.

I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

How do I find the date a video (.AVI .MP4) was actually recorded?

I used the following online tool: https://www.get-metadata.com It allows to upload a file and analyze it and then shows all its metadata.

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

ggplot combining two plots from different data.frames

You can take this trick to use only qplot. Use inner variable $mapping. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.

cpu_metric2 <- qplot(y=Y2,x=X1) 

cpu_metric1 <- qplot(y=Y1, 
                    x=X1, 
                    xlab="Time", ylab="%") 

combined_cpu_plot <- cpu_metric1 + 
  geom_line() +
  geom_point(mapping=cpu_metric2$mapping)+
  geom_line(mapping=cpu_metric2$mapping)

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

How do you run a SQL Server query from PowerShell?

There isn't a built-in "PowerShell" way of running a SQL query. If you have the SQL Server tools installed, you'll get an Invoke-SqlCmd cmdlet.

Because PowerShell is built on .NET, you can use the ADO.NET API to run your queries.

How to include (source) R script in other scripts

You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source to source the file if not.

Here's a quick and untested function (improvements welcome!):

include <- function(file, env) {
  # ensure file and env are provided
  if(missing(file) || missing(env))
    stop("'file' and 'env' must be provided")
  # ensure env is character
  if(!is.character(file) || !is.character(env))
    stop("'file' and 'env' must be a character")

  # see if env is attached to the search path
  if(env %in% search()) {
    ENV <- get(env)
    files <- get(".files",ENV)
    # if the file hasn't been loaded
    if(!(file %in% files)) {
      sys.source(file, ENV)                        # load the file
      assign(".files", c(file, files), envir=ENV)  # set the flag
    }
  } else {
    ENV <- attach(NULL, name=env)      # create/attach new environment
    sys.source(file, ENV)              # load the file
    assign(".files", file, envir=ENV)  # set the flag
  }
}

eslint: error Parsing error: The keyword 'const' is reserved

I had this same problem with this part of my code:

const newComment = {
    dishId: dishId,
    rating: rating,
    author: author,
    comment: comment
};
newComment.date = new Date().toISOString();

Same error, const is a reserved word.

The thing is, I made the .eslintrc.js from the link you gave in the update and still got the same error. Also, I get an parsing error in the .eslintrc.js: Unexpected token ':'.

Right in this part:

"env": {
"browser": true,
"node": true,
"es6": true
},

...

Save and load MemoryStream to/from a file

I use a Panel Control to add a image or even stream video, but you can save the image on SQL Server as Image or MySQL as largeblob. This code works for me a lot. Check it out.

Here you save the image

MemoryStream ms = new MemoryStream();
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, panel1.Bounds);
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // here you can change the Image format
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
ms.Close();

And here you can load, but I used a PictureBox Control.

MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
fotos.pictureBox1.Image = System.Drawing.Image.FromStream(ms);

Hope helps.

How to commit my current changes to a different branch in Git

You can just create a new branch and switch onto it. Commit your changes then:

git branch dirty
git checkout dirty
// And your commit follows ...

Alternatively, you can also checkout an existing branch (just git checkout <name>). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.

Difference between .dll and .exe?

I don't know why everybody is answering this question in context of .NET. The question was a general one and didn't mention .NET anywhere.

Well, the major differences are:

EXE

  1. An exe always runs in its own address space i.e., It is a separate process.
  2. The purpose of an EXE is to launch a separate application of its own.

DLL

  1. A dll always needs a host exe to run. i.e., it can never run in its own address space.
  2. The purpose of a DLL is to have a collection of methods/classes which can be re-used from some other application.
  3. DLL is Microsoft's implementation of a shared library.

The file format of DLL and exe is essentially the same. Windows recognizes the difference between DLL and EXE through PE Header in the file. For details of PE Header, You can have a look at this Article on MSDN

flow 2 columns of text automatically with CSS

Below I have created both a static and dynamic approach at columnizing paragraphs. The code is pretty much self-documented.

Foreward

Below, you will find the following methods for creating columns:

  1. Static (2-columns)
  2. Dynamic w/ JavaScript + CSS (n-columns)
  3. Dynamic w/ JavaScript + CSS3 (n-columns)

Static (2-columns)

This is a simple 2 column layout. Based on Glennular's 1st answer.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    var columns = 2;_x000D_
    var size = $("#data > p").size();_x000D_
    var half = size / columns;_x000D_
    $(".col50 > p").each(function (index) {_x000D_
        if (index >= half) {_x000D_
            $(this).appendTo(".col50:eq(1)");_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
.col50 {_x000D_
    display: inline-block;_x000D_
    vertical-align: top;_x000D_
    width: 48.2%;_x000D_
    margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="data" class="col50">_x000D_
    <!-- data Start -->_x000D_
    <p>This is paragraph 1. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 2. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 3. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 4. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 5. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 6. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 7. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 8. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 9. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 10. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 11. Lorem ipsum ...</p>_x000D_
    <!-- data End-->_x000D_
</div>_x000D_
<div class="col50"></div>
_x000D_
_x000D_
_x000D_

Dynamic w/ JavaScript + CSS (n-columns)

With this approach, I essentially detect if the block needs to be converted to columns. The format is col-{n}. n is the number of columns you want to create.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    splitByColumns('col-', 4);_x000D_
});_x000D_
_x000D_
function splitByColumns(prefix, gap) {_x000D_
    $('[class^="' + prefix + '"]').each(function(index, el) {_x000D_
        var me = $(this);_x000D_
        var count = me.attr("class").split(' ').filter(function(className) {_x000D_
            return className.indexOf(prefix) === 0;_x000D_
        }).reduce(function(result, value) {_x000D_
            return Math.max(parseInt(value.replace(prefix, '')), result);_x000D_
        }, 0);_x000D_
        var paragraphs = me.find('p').get();_x000D_
        me.empty(); // We now have a copy of the children, we can clear the element._x000D_
        var size = paragraphs.length;_x000D_
        var percent = 1 / count;_x000D_
        var width = (percent * 100 - (gap / count || percent)).toFixed(2) + '%';_x000D_
        var limit = Math.round(size / count);_x000D_
        var incr = 0;_x000D_
        var gutter = gap / 2 + 'px';_x000D_
        for (var col = 0; col < count; col++) {_x000D_
            var colDiv = $('<div>').addClass('col').css({ width: width });_x000D_
            var css = {};_x000D_
            if (col > -1 && col < count -1) css['margin-right'] = gutter;_x000D_
            if (col > 0 && col < count)     css['margin-left'] = gutter;_x000D_
            colDiv.css(css);_x000D_
            for (var line = 0; line < limit && incr < size; line++) {_x000D_
                colDiv.append(paragraphs[incr++]);_x000D_
            }_x000D_
            me.append(colDiv);_x000D_
        }_x000D_
    });_x000D_
}
_x000D_
.col {_x000D_
    display: inline-block;_x000D_
    vertical-align: top;_x000D_
    margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="data" class="col-6">_x000D_
    <!-- data Start -->_x000D_
    <p>This is paragraph 1. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 2. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 3. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 4. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 5. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 6. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 7. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 8. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 9. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 10. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 11. Lorem ipsum ...</p>_x000D_
    <!-- data End-->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dynamic w/ JavaScript + CSS3 (n-columns)

This has been derived from on Glennular's 2nd answer. It uses the column-count and column-gap CSS3 rules.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    splitByColumns('col-', '4px');_x000D_
});_x000D_
_x000D_
function splitByColumns(prefix, gap) {_x000D_
    var vendors = [ '', '-moz', '-webkit-' ];_x000D_
    var getColumnCount = function(el) {_x000D_
        return el.attr("class").split(' ').filter(function(className) {_x000D_
            return className.indexOf(prefix) === 0;_x000D_
        }).reduce(function(result, value) {_x000D_
            return Math.max(parseInt(value.replace(prefix, '')), result);_x000D_
        }, 0);_x000D_
    }_x000D_
    $('[class^="' + prefix + '"]').each(function(index, el) {_x000D_
        var me = $(this);_x000D_
        var count = getColumnCount(me);_x000D_
        var css = {};_x000D_
        $.each(vendors, function(idx, vendor) {_x000D_
            css[vendor + 'column-count'] = count;_x000D_
            css[vendor + 'column-gap'] = gap;_x000D_
        });_x000D_
        me.css(css);_x000D_
    });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="data" class="col-3">_x000D_
    <!-- data Start -->_x000D_
    <p>This is paragraph 1. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 2. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 3. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 4. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 5. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 6. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 7. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 8. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 9. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 10. Lorem ipsum ...</p>_x000D_
    <p>This is paragraph 11. Lorem ipsum ...</p>_x000D_
    <!-- data End-->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Automatically create an Enum based on values in a database lookup table?

Does it have to be an actual enum? How about using a Dictionary<string,int> instead?

for example

Dictionary<string, int> MyEnum = new Dictionary(){{"One", 1}, {"Two", 2}};
Console.WriteLine(MyEnum["One"]);

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Save child objects automatically using JPA Hibernate

In short set cascade type to all , will do a job; For an example in your model. Add Code like this . @OneToMany(mappedBy = "receipt", cascade=CascadeType.ALL) private List saleSet;

WPF global exception handler

You can trap unhandled exceptions at different levels:

  1. AppDomain.CurrentDomain.UnhandledException From all threads in the AppDomain.
  2. Dispatcher.UnhandledException From a single specific UI dispatcher thread.
  3. Application.Current.DispatcherUnhandledException From the main UI dispatcher thread in your WPF application.
  4. TaskScheduler.UnobservedTaskException from within each AppDomain that uses a task scheduler for asynchronous operations.

You should consider what level you need to trap unhandled exceptions at.

Deciding between #2 and #3 depends upon whether you're using more than one WPF thread. This is quite an exotic situation and if you're unsure whether you are or not, then it's most likely that you're not.

Programmatically shut down Spring Boot application

The simplest way would be to inject the following object where you need to initiate the shutdown

ShutdownManager.java

import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;

@Component
class ShutdownManager {

    @Autowired
    private ApplicationContext appContext;

    /*
     * Invoke with `0` to indicate no error or different code to indicate
     * abnormal exit. es: shutdownManager.initiateShutdown(0);
     **/
    public void initiateShutdown(int returnCode){
        SpringApplication.exit(appContext, () -> returnCode);
    }
}

JavaScript math, round to two decimal places

The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.

You can use following to solve this issue:

Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');

Add .toFixed(2) to get the two decimal places you wanted.

Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);

You could make a function that will handle the rounding for you:

function round(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

Example: https://jsfiddle.net/k5tpq3pd/36/

Alternativ

You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.

Number.prototype.round = function(decimals) {
    return Number((Math.round(this + "e" + decimals)  + "e-" + decimals));
}

and use it like this:

var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals

Example https://jsfiddle.net/k5tpq3pd/35/

Source: http://www.jacklmoore.com/notes/rounding-in-javascript/

Android: How to handle right to left swipe gestures

This question was asked many years ago. Now, there is a better solution: SmartSwipe: https://github.com/luckybilly/SmartSwipe

code looks like this:

SmartSwipe.wrap(contentView)
        .addConsumer(new StayConsumer()) //contentView stay while swiping with StayConsumer
        .enableAllDirections() //enable directions as needed
        .addListener(new SimpleSwipeListener() {
            @Override
            public void onSwipeOpened(SmartSwipeWrapper wrapper, SwipeConsumer consumer, int direction) {
                //direction: 
                //  1: left
                //  2: right
                //  4: top
                //  8: bottom
            }
        })
;

How to load html string in a webview?

read from assets html file

ViewGroup webGroup;
  String content = readContent("content/ganji.html");

        final WebView webView = new WebView(this);
        webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

        webGroup.addView(webView);

How to create a floating action button (FAB) in android, using AppCompat v21?

Try this library, it supports shadow, there is minSdkVersion=7 and also supports android:elevation attribute for API-21 implicitly.

Original post is here.

How do I check to see if my array includes an object?

#include? should work, it works for general objects, not only strings. Your problem in example code is this test:

unless @suggested_horses.exists?(horse.id)
  @suggested_horses<< horse
end

(even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

unless @suggested_horses.include?(horse)
  @suggested_horses << horse
end

ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

How to split a string in shell and get the last field

$ echo "a b c d e" | tr ' ' '\n' | tail -1
e

Simply translate the delimiter into a newline and choose the last entry with tail -1.

React JS onClick event handler

If you're using ES6, here's some simple example code:

import React from 'wherever_react_is';

class TestApp extends React.Component {

  getComponent(event) {
      console.log('li item clicked!');
      event.currentTarget.style.backgroundColor = '#ccc';
  }

  render() {
    return(
       <div>
         <ul>
            <li onClick={this.getComponent.bind(this)}>Component 1</li>
         </ul>
       </div>
    );
  }
}

export default TestApp;

In ES6 class bodies, functions no longer require the 'function' keyword and they don't need to be separated by commas. You can also use the => syntax as well if you wish.

Here's an example with dynamically created elements:

import React from 'wherever_react_is';

class TestApp extends React.Component {

constructor(props) {
  super(props);

  this.state = {
    data: [
      {name: 'Name 1', id: 123},
      {name: 'Name 2', id: 456}
    ]
  }
}

  getComponent(event) {
      console.log('li item clicked!');
      event.currentTarget.style.backgroundColor = '#ccc';
  }

  render() {        
       <div>
         <ul>
         {this.state.data.map(d => {
           return(
              <li key={d.id} onClick={this.getComponent.bind(this)}>{d.name}</li>
           )}
         )}
         </ul>
       </div>
    );
  }
}

export default TestApp;

Note that each dynamically created element should have a unique reference 'key'.

Furthermore, if you would like to pass the actual data object (rather than the event) into your onClick function, you will need to pass that into your bind. For example:

New onClick function:

getComponent(object) {
    console.log(object.name);
}

Passing in the data object:

{this.state.data.map(d => {
    return(
      <li key={d.id} onClick={this.getComponent.bind(this, d)}>{d.name}</li>
    )}
)}

how to know status of currently running jobs

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

check field execution_status

0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.

If you need the result of execution, check the field last_run_outcome

0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown

https://msdn.microsoft.com/en-us/library/ms186722.aspx

How to retrieve the hash for the current commit in Git?

If you only want the shortened commit hash:

git log --pretty=format:'%h' -n 1

Furthermore, using %H is another way to get the long commit hash, and simply -1 can be used in place of -n 1.

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

If you're using mariadb, you have to modify the mariadb.cnf file located in /etc/mysql/conf.d/.

I supposed the stuff is the same for any other my-sql based solutions.

Returning boolean if set is empty

Not as clean as bool(c) but it was an excuse to use ternary.

def myfunc(a,b):
    return True if a.intersection(b) else False

Also using a bit of the same logic there is no need to assign to c unless you are using it for something else.

def myfunc(a,b):
    return bool(a.intersection(b))

Finally, I would assume you want a True / False value because you are going to perform some sort of boolean test with it. I would recommend skipping the overhead of a function call and definition by simply testing where you need it.

Instead of:

if (myfunc(a,b)):
    # Do something

Maybe this:

if a.intersection(b):
    # Do something

Java, Check if integer is multiple of a number

Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:

if (j % 4 == 0) {
     // j is an exact multiple of 4
}

Replace transparency in PNG images with white background

this creates an image just placing the 1st with transparency on top of the 2nd

composite -gravity center ImgWithTransp.png BackgroundSameSizeOfImg.png ResultImg.png

originally found the tip on this post

Split comma-separated input box values into array in jquery, and loop through it

var array = $('#searchKeywords').val().split(",");

then

$.each(array,function(i){
   alert(array[i]);
});

OR

for (i=0;i<array.length;i++){
     alert(array[i]);
}

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to add a char/int to an char array in C?

strcat has the declaration:

char *strcat(char *dest, const char *src)

It expects 2 strings. While this compiles:

char str[1024] = "Hello World";
char tmp = '.';

strcat(str, tmp);

It will cause bad memory issues because strcat is looking for a null terminated cstring. You can do this:

char str[1024] = "Hello World";
char tmp[2] = ".";

strcat(str, tmp);

Live example.

If you really want to append a char you will need to make your own function. Something like this:

void append(char* s, char c) {
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';
}

append(str, tmp)

Of course you may also want to check your string size etc to make it memory safe.

"Unknown class <MyClass> in Interface Builder file" error at runtime

I ran into this in Swift.

Moving the .xib file into the project's Base.lproj folder got rid of this error.

How can I search for a commit message on GitHub?

Update January 2017 (two years later):

You can now search for commit messages! (still only in the master branch)

https://cloud.githubusercontent.com/assets/1387653/21622772/61a5c7a6-d1bc-11e6-809d-134936a4ac05.gif


February 2015: Not sure that could ever be possible, considering the current search infrastructure base on Elasticsearch (introduced in January 2013).

As an answer "drawing from credible and/or official sources", here is an interview done with the GitHub people in charge of introducing Elasticsearch at GitHub (August 2013)

Tim Pease: We have two document types in there: One is a source code file and the other one is a repository. The way that git works is you have commits and you have a branch for each commit. Repository documents keep track of the most recent commit for that particular repository that has been indexed. When a user pushes a new commit up to Github, we then pull that repository document from elasticsearch. We then see the most recently indexed commit and then we get a list of all the files that had been modified, or added, or deleted between this recent push and what we have previously indexed. Then we can go ahead and just update those documents which have been changed. We don’t have to re-index the entire source code tree every time someone pushes.

Andrew Cholakian: So, you guys only index, I’m assuming, the master branch.

Tim Pease: Correct. It’s only the head of the master branch that you’re going to get in there and still that’s a lot of data, two billion documents, 30 terabytes.

Andrew Cholakian: That is awesomely huge.

[...]

Tim Pease: With indexing source code on push, it’s a self-healing process.
We have that repository document which keeps track of the last indexed commit. If we missed, just happen to miss three commits where those jobs fail, the next commit that comes in, we’re still looking at the diff between the previous commit that we indexed and the one that we’re seeing with this new push.
You do a git diff and you get all the files that have been updated, deleted, or added. You can just say, “Okay, we need to remove these files. We need to add these files, and all that.” It’s self-healing and that’s the approach that we have taken with pretty much all of the architecture.

That all means not all the branches of all the repo would be indexed with that approach.
A global commit message search isn't available for now.
And Tim Pease himself confirms commit messages are not indexed.

Note that it isn't impossible to get one's own elasticsearch local indexing of a local clone: see "Searching a git repository with ElasticSearch"

But for a specific repo, the easiest remains to clone it and do a:

git log --all --grep='my search'

(More options at "How to search a Git repository by commit message?")

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Dynamically change color to lighter or darker by percentage CSS (Javascript)

At the time of writing, here's the best pure CSS implementation for color manipulation I found:

Use CSS variables to define your colors in HSL instead of HEX/RGB format, then use calc() to manipulate them.

Here's a basic example:

_x000D_
_x000D_
:root {_x000D_
  --link-color-h: 211;_x000D_
  --link-color-s: 100%;_x000D_
  --link-color-l: 50%;_x000D_
  --link-color-hsl: var(--link-color-h), var(--link-color-s), var(--link-color-l);_x000D_
_x000D_
  --link-color: hsl(var(--link-color-hsl));_x000D_
  --link-color-10: hsla(var(--link-color-hsl), .1);_x000D_
  --link-color-20: hsla(var(--link-color-hsl), .2);_x000D_
  --link-color-30: hsla(var(--link-color-hsl), .3);_x000D_
  --link-color-40: hsla(var(--link-color-hsl), .4);_x000D_
  --link-color-50: hsla(var(--link-color-hsl), .5);_x000D_
  --link-color-60: hsla(var(--link-color-hsl), .6);_x000D_
  --link-color-70: hsla(var(--link-color-hsl), .7);_x000D_
  --link-color-80: hsla(var(--link-color-hsl), .8);_x000D_
  --link-color-90: hsla(var(--link-color-hsl), .9);_x000D_
_x000D_
  --link-color-warm: hsl(calc(var(--link-color-h) + 80), var(--link-color-s), var(--link-color-l));_x000D_
  --link-color-cold: hsl(calc(var(--link-color-h) - 80), var(--link-color-s), var(--link-color-l));_x000D_
_x000D_
  --link-color-low: hsl(var(--link-color-h), calc(var(--link-color-s) / 2), var(--link-color-l));_x000D_
  --link-color-lowest: hsl(var(--link-color-h), calc(var(--link-color-s) / 4), var(--link-color-l));_x000D_
_x000D_
  --link-color-light: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) / .9));_x000D_
  --link-color-dark: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) * .9));_x000D_
}_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.flex > div {_x000D_
  flex: 1;_x000D_
  height: calc(100vw / 10);_x000D_
}
_x000D_
<h3>Color Manipulation (alpha)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color-10)"></div>_x000D_
  <div style="background-color: var(--link-color-20)"></div>_x000D_
  <div style="background-color: var(--link-color-30)"></div>_x000D_
  <div style="background-color: var(--link-color-40)"></div>_x000D_
  <div style="background-color: var(--link-color-50)"></div>_x000D_
  <div style="background-color: var(--link-color-60)"></div>_x000D_
  <div style="background-color: var(--link-color-70)"></div>_x000D_
  <div style="background-color: var(--link-color-80)"></div>_x000D_
  <div style="background-color: var(--link-color-90)"></div>_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Hue)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color-warm)"></div>_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
  <div style="background-color: var(--link-color-cold)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Saturation)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
  <div style="background-color: var(--link-color-low)"></div>_x000D_
  <div style="background-color: var(--link-color-lowest)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Lightness)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color-light)"></div>_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
  <div style="background-color: var(--link-color-dark)"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I also created a CSS framework (still in early stage) to provide basic CSS variables support called root-variables.

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):

If Double.IsNaN(MyVariableName) Then
    MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If

If you try to use a variable that has a NaN value you will get the following error:

Value was either too large or too small for a Decimal.

How to use document.getElementByName and getElementByTag?

getElementById returns either a reference to an element with an id matching the argument, or null if no such element exists in the document.

getElementsByName() (note the plural Elements) returns a (possibly empty) HTMLCollection of the elements with a name matching the argument. Note that IE treats the name and id attributes and properties as the same thing, so getElementsByName will return elements with matching id also.

getElementsByTagName is similar but returns a NodeList. It's all there in the relevant specifications.

How to find all the tables in MySQL with specific column names in them?

Use this one line query, replace desired_column_name by your column name.

SELECT TABLE_NAME FROM information_schema.columns WHERE column_name = 'desired_column_name';

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

Convert a Pandas DataFrame to a dictionary

Follow these steps:

Suppose your dataframe is as follows:

>>> df
   A  B  C ID
0  1  3  2  p
1  4  3  2  q
2  4  0  9  r

1. Use set_index to set ID columns as the dataframe index.

    df.set_index("ID", drop=True, inplace=True)

2. Use the orient=index parameter to have the index as dictionary keys.

    dictionary = df.to_dict(orient="index")

The results will be as follows:

    >>> dictionary
    {'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}

3. If you need to have each sample as a list run the following code. Determine the column order

column_order= ["A", "B", "C"] #  Determine your preferred order of columns
d = {} #  Initialize the new dictionary as an empty dictionary
for k in dictionary:
    d[k] = [dictionary[k][column_name] for column_name in column_order]

What port number does SOAP use?

SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.

How to position a div scrollbar on the left hand side?

No, you can't change scrollbars placement without any additional issues.

You can change text-direction to right-to-left ( rtl ), but it also change text position inside block.

This code can helps you, but I not sure it works in all browsers and OS.

<element style="direction: rtl; text-align: left;" />

How do you access a website running on localhost from iPhone browser

Have a look at this answer, it discusses internally routing HTTP through direct Objective-C calls to an HTTP-capable layer/embedded web server (let's assume that the HTTP server code is within the same application that wishes to display the HTML within a web widget).

This has the advantage of being slightly more secure (and possibly faster) as no port(s) should be exposed.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

How can I get the max (or min) value in a vector?

Just this:

// assuming "cloud" is:
// int cloud[10]; 
// or any other fixed size

#define countof(x) (sizeof(x)/sizeof((x)[0]))

int* pMax = std::max_element(cloud, cloud + countof(cloud));

Should I write script in the body or the head of the html?

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

Javascript Append Child AFTER Element

You can use:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
  parentGuest.parentNode.appendChild(childGuest);
}

But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

SQL Server JOIN missing NULL values

The only correct answer is not to join columns with null values. This can lead to unwanted behaviour very quickly.

e.g. isnull(b.colId,''): What happens if you have empty strings in your data? The join maybe duplicate rows which I guess is not intended in this case.

Remove Identity from a column in a table

This gets messy with foreign and primary key constraints, so here's some scripts to help you on your way:

First, create a duplicate column with a temporary name:

alter table yourTable add tempId int NOT NULL default -1;
update yourTable set tempId = id;

Next, get the name of your primary key constraint:

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'yourTable';

Now try drop the primary key constraint for your column:

ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;

If you have foreign keys, it will fail, so if so drop the foreign key constraints. KEEP TRACK OF WHICH TABLES YOU RUN THIS FOR SO YOU CAN ADD THE CONSTRAINTS BACK IN LATER!!!

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'otherTable';
alter table otherTable drop constraint fk_otherTable_yourTable;
commit;
..

Once all of your foreign key constraints have been removed, you'll be able to remove the PK constraint, drop that column, rename your temp column, and add the PK constraint to that column:

ALTER TABLE yourTable DROP CONSTRAINT PK_yourTable_id;
alter table yourTable drop column id;
EXEC sp_rename 'yourTable.tempId', 'id', 'COLUMN';
ALTER TABLE yourTable ADD CONSTRAINT PK_yourTable_id PRIMARY KEY (id) 
commit;

Finally, add the FK constraints back in:

alter table otherTable add constraint fk_otherTable_yourTable foreign key (yourTable_id) references yourTable(id);
..

El Fin!

How can I insert new line/carriage returns into an element.textContent?

I know this question posted long time ago.

I had similar problem few days ago, passing value from web service in json format and place it in table cell contentText.

Because value is passed in format, for example, "text row1\r\ntext row2" and so on.

For new line in textContent You have to use \r\n and, finally, I had to use css white-space: pre-line; (Text will wrap when necessary, and on line breaks) and everything goes fine.

Or, You can use only white-space: pre; and then text will wrap only on line breaks (in this case \r\n).

So, there is example how to solve it with wrapping text only on line breaks :

_x000D_
_x000D_
var h1 = document.createElement("h1");_x000D_
_x000D_
//setting this css style solving problem with new line in textContent_x000D_
h1.setAttribute('style', 'white-space: pre;');_x000D_
_x000D_
//add \r\n in text everywhere You want for line-break (new line)_x000D_
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";_x000D_
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";_x000D_
h1.textContent += "so this text will display in a new line";_x000D_
_x000D_
document.body.appendChild(h1);
_x000D_
_x000D_
_x000D_

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

Mocking HttpClient in unit tests

After carefully searching, I figured out the best approach to accomplish this.

    private HttpResponseMessage response;

    [SetUp]
    public void Setup()
    {
        var handlerMock = new Mock<HttpMessageHandler>();

        handlerMock
           .Protected()
           .Setup<Task<HttpResponseMessage>>(
              "SendAsync",
              ItExpr.IsAny<HttpRequestMessage>(),
              ItExpr.IsAny<CancellationToken>())
           // This line will let you to change the response in each test method
           .ReturnsAsync(() => response);

        _httpClient = new HttpClient(handlerMock.Object);

        yourClinet = new YourClient( _httpClient);
    }

As you noticed I have used Moq and Moq.Protected packages.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

Why should Java 8's Optional not be used in arguments

I believe the reson of being is you have to first check whether or not Optional is null itself and then try to evaluate value it wraps. Too many unnecessary validations.

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The JPA @Column Annotation

The nullable attribute of the @Column annotation has two purposes:

  • it's used by the schema generation tool
  • it's used by Hibernate during flushing the Persistence Context

Schema Generation Tool

The HBM2DDL schema generation tool translates the @Column(nullable = false) entity attribute to a NOT NULL constraint for the associated table column when generating the CREATE TABLE statement.

As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.

Persistence Context Flush

When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false) entity attribute:

new Nullability( session ).checkNullability( values, persister, true );

If the validation fails, Hibernate will throw a PropertyValueException, and prevents the INSERT or UPDATE statement to be executed needesly:

if ( !nullability[i] && value == null ) {
    //check basic level one nullablilty
    throw new PropertyValueException(
            "not-null property references a null or transient value",
            persister.getEntityName(),
            persister.getPropertyNames()[i]
        );    
}

The Bean Validation @NotNull Annotation

The @NotNull annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.

When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation when validating the entity.

Using lambda expressions for event handlers

No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Go through C:\apache-tomcat-7.0.47\lib path (this path may be differ based on where you installed the Tomcat server) then past ojdbc14.jar if its not contain.

Then restart the server in eclipse then run your app on server

PostgreSQL create table if not exists

I created a generic solution out of the existing answers which can be reused for any table:

CREATE OR REPLACE FUNCTION create_if_not_exists (table_name text, create_stmt text)
RETURNS text AS
$_$
BEGIN

IF EXISTS (
    SELECT *
    FROM   pg_catalog.pg_tables 
    WHERE    tablename  = table_name
    ) THEN
   RETURN 'TABLE ' || '''' || table_name || '''' || ' ALREADY EXISTS';
ELSE
   EXECUTE create_stmt;
   RETURN 'CREATED';
END IF;

END;
$_$ LANGUAGE plpgsql;

Usage:

select create_if_not_exists('my_table', 'CREATE TABLE my_table (id integer NOT NULL);');

It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas.

How do I access call log for android?

If we use Kotlin it is shorter. Example of class which responds for provide call logs:

import android.content.Context
import android.database.Cursor
import android.provider.CallLog.Calls.*

class CallsLoader {

    fun getCallLogs(context: Context): List<List<String?>> {
        val c = context.applicationContext
        val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION)

        val cursor = c.contentResolver.query(
             CONTENT_URI,
             projection,
             null,
             null,
             null,
             null
          )

         return cursorToMatrix(cursor)
     }

    private fun cursorToMatrix(cursor: Cursor?): List<List<String?>> {
        val matrix = mutableListOf<List<String?>>()
        cursor?.use {
             while (it.moveToNext()) {
                 val list = listOf(
                    it.getStringFromColumn(CACHED_NAME),
                    it.getStringFromColumn(NUMBER),
                    it.getStringFromColumn(TYPE),
                    it.getStringFromColumn(DATE),
                    it.getStringFromColumn(DURATION)
                 )

                 matrix.add(list.toList())
             }
          }

          return matrix
      }

     private fun Cursor.getStringFromColumn(columnName: String) =
        getString(getColumnIndex(columnName))
}

We can also convert cursor to map:

fun getCallLogs(context: Context): Map<String, Array<String?>> {
    val c = context.applicationContext
    val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION)

    val cursor = c.contentResolver.query(
        CONTENT_URI,
        projection,
        null,
        null,
        null,
        null
    )

    return cursorToMap(cursor)
}

private fun cursorToMap(cursor: Cursor?): Map<String, Array<String?>> {
    val arraySize = cursor?.count ?: 0
    val map = mapOf(
        CACHED_NAME to Array<String?>(arraySize) { "" },
        NUMBER to Array<String?>(arraySize) { "" },
        TYPE to Array<String?>(arraySize) { "" },
        DATE to Array<String?>(arraySize) { "" },
        DURATION to Array<String?>(arraySize) { "" }
    )

    cursor?.use {
        for (i in 0 until arraySize) {
            it.moveToNext()

            map[CACHED_NAME]?.set(i, it.getStringFromColumn(CACHED_NAME))
            map[NUMBER]?.set(i, it.getStringFromColumn(NUMBER))
            map[TYPE]?.set(i, it.getStringFromColumn(TYPE))
            map[DATE]?.set(i, it.getStringFromColumn(DATE))
            map[DURATION]?.set(i, it.getStringFromColumn(DURATION))
        }
    }

    return map
}

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

May it's late for the answer. But will be helpful for anyone.

In My case want to call activity from Fragment and setResult back from the fragment.

I have used getContext of Fragment Like.

startActivityForResult(new Intent(getContext(), NextActivity.class), 111);

And Set Result from Fragment

getActivity().setResult(Activity.RESULT_OK);
                    getActivity().finish();

Now Getting Result to Fragment with

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && requestCode == 111) {

    }
}

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

CSS to line break before/after a particular `inline-block` item

Maybe it's is completely possible with only CSS but I prefer to avoid "float" as much as I can because it interferes with it's parent's height.

If you are using jQuery, you can create a simple `wrapN` plugin that is similar to `wrapAll` except it only wraps "N" elements and then breaks and wraps the next "N" elements using a loop. Then set your wrappers class to `display: block;`.

(function ($) {
    $.fn.wrapN = function (wrapper, n, start) {
        if (wrapper === undefined || n === undefined) return false;
        if (start === undefined) start = 0;
        for (var i = start; i < $(this).size(); i += n)
           $(this).slice(i, i + n).wrapAll(wrapper);
        return this;
    };
}(jQuery));

$(document).ready(function () {
    $("li").wrapN("<span class='break' />", 3);
});

Here is a JSFiddle of the finished product:

http://jsfiddle.net/dustinpoissant/L79ahLoz/

datetimepicker is not a function jquery

It's all about the order of the scripts. Try to reorder them, place jquery.datetimepicker.js to be last of all scripts!

How to Force New Google Spreadsheets to refresh and recalculate?

Old question ... nonetheless, just add a checkbox somewhere in the sheet. Checking or unchecking it will refresh the cell formulae.

Simple Pivot Table to Count Unique Values

If you have the data sorted.. i suggest using the following formula

=IF(OR(A2<>A3,B2<>B3),1,0)

This is faster as it uses less cells to calculate.

How to use Tomcat 8 in Eclipse?

The latest version of Springsource STS (3.6) supports Tomcat 8. It is based on eclipse Luna 4.4 and supports Java 8. Have at it!

How can I convert the "arguments" object to an array in JavaScript?

Here's a clean and concise solution:

_x000D_
_x000D_
function argsToArray() {_x000D_
  return Object.values(arguments);_x000D_
}_x000D_
_x000D_
// example usage_x000D_
console.log(_x000D_
  argsToArray(1, 2, 3, 4, 5)_x000D_
  .map(arg => arg*11)_x000D_
);
_x000D_
_x000D_
_x000D_

Object.values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map, forEach, filter, etc.

Insert multiple lines into a file after specified pattern using shell script

if you want to do that with a bash script, that's useful.

echo $password | echo 'net.ipv4.ping_group_range=0 2147483647' |  sudo -S tee -a /etc/sysctl.conf

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

How to run multiple SQL commands in a single SQL connection?

Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.

// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();

// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();

How to show DatePickerDialog on Button click?

    final Calendar newCalendar = Calendar.getInstance();
    final DatePickerDialog  StartTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    Calendar newDate = Calendar.getInstance();
                    newDate.set(year, monthOfYear, dayOfMonth);
                    activitydate.setText(dateFormatter.format(newDate.getTime()));
                }
    
            }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    
      btn_checkin.setOnClickListener(new View.OnClickListener() {
@Override   public void onClick(View v) {
         StartTime.show():    
     });

the getSource() and getActionCommand()

Assuming you are talking about the ActionEvent class, then there is a big difference between the two methods.

getActionCommand() gives you a String representing the action command. The value is component specific; for a JButton you have the option to set the value with setActionCommand(String command) but for a JTextField if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField.

getSource() is specified by the EventObject class that ActionEvent is a child of (via java.awt.AWTEvent). This gives you a reference to the object that the event came from.

Edit:

Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.

public class Events implements ActionListener {

  private static JFrame frame; 

  public static void main(String[] args) {

    frame = new JFrame("JTextField events");
    frame.getContentPane().setLayout(new FlowLayout());

    JTextField field1 = new JTextField(10);
    field1.addActionListener(new Events());
    frame.getContentPane().add(new JLabel("Field with no action command set"));
    frame.getContentPane().add(field1);

    JTextField field2 = new JTextField(10);
    field2.addActionListener(new Events());
    field2.setActionCommand("my action command");
    frame.getContentPane().add(new JLabel("Field with an action command set"));
    frame.getContentPane().add(field2);


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(220, 150);
    frame.setResizable(false);
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();
    JOptionPane.showMessageDialog(frame, "Command: " + cmd);
  }

}

vim - How to delete a large block of text without counting the lines?

Alongside with other motions that are already mentioned here, there is also /{pattern}<CR> motion, so if you know that you want to delete to line that contains foo, you could do dV/foo<CR>. V is here to force motion be line-wise because by default / is characterwise.

Python ImportError: No module named wx

You may check if you have the directory where are the packages of Python (in my machine, this dir is C:\Python27\lib\site-packages) in the Path variable on Windows. If Python's path environment variable does not have this directory, you will not find the packages.

Push an associative item into an array in JavaScript

JavaScript has associative arrays.

Here is a working snippet.

_x000D_
_x000D_
<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>
_x000D_
_x000D_
_x000D_

They are simply called objects.

Blur effect on a div element

I got blur working with SVG blur filter:

CSS

-webkit-filter: url(#svg-blur);
        filter: url(#svg-blur);

SVG

<svg id="svg-filter">
    <filter id="svg-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
    </filter>
</svg>

Working example:

https://jsfiddle.net/1k5x6dgm/

Please note - this will not work in IE versions

Paritition array into N chunks with Numpy

Not quite an answer, but a long comment with nice formatting of code to the other (correct) answers. If you try the following, you will see that what you are getting are views of the original array, not copies, and that was not the case for the accepted answer in the question you link. Be aware of the possible side effects!

>>> x = np.arange(9.0)
>>> a,b,c = np.split(x, 3)
>>> a
array([ 0.,  1.,  2.])
>>> a[1] = 8
>>> a
array([ 0.,  8.,  2.])
>>> x
array([ 0.,  8.,  2.,  3.,  4.,  5.,  6.,  7.,  8.])
>>> def chunks(l, n):
...     """ Yield successive n-sized chunks from l.
...     """
...     for i in xrange(0, len(l), n):
...         yield l[i:i+n]
... 
>>> l = range(9)
>>> a,b,c = chunks(l, 3)
>>> a
[0, 1, 2]
>>> a[1] = 8
>>> a
[0, 8, 2]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8]

How to use forEach in vueJs?

You can use native javascript function

var obj = {a:1,b:2};

Object.keys(obj).forEach(function(key){
    console.log(key, obj[el])
})

or create an object prototype foreach, but it usually causes issues with other frameworks

if (!Object.prototype.forEach) {
  Object.defineProperty(Object.prototype, 'forEach', {
    value: function (callback, thisArg) {
      if (this == null) {
        throw new TypeError('Not an object');
      }
      thisArg = thisArg || window;
      for (var key in this) {
        if (this.hasOwnProperty(key)) {
          callback.call(thisArg, this[key], key, this);
        }
      }
    }
  });
}

var obj = {a:1,b:2};

obj.forEach(function(key, value){
    console.log(key, value)
})


Python Prime number checker

This would do the job:

number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
    print "number is not prime"
else:
    a=2
    check = True
    while a != number:
        if number%a == 0:
            print "Number is not prime"
            check = False
            break
        a+=1
    if check == True:
        print "Number is prime" 

How do I iterate and modify Java Sets?

You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

Set<Integer> set = new TreeSet<Integer>();
    set.add(1);
    set.add(2);
    set.add(3);

    //good way:
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()) {
        Integer setElement = iterator.next();
        if(setElement==2) {
            iterator.remove();
        }
    }

    //bad way:
    for(Integer setElement:set) {
        if(setElement==2) {
            //might work or might throw exception, Java calls it indefined behaviour:
            set.remove(setElement);
        } 
    }

As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

stipulate, amongst others, that (emphasis mine):

"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.