Programs & Examples On #Stax

StAX stands for Streaming API for XML. It's a streaming Java-based, event-driven, pull-parsing API for reading and writing XML documents.

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I zipped the xml in a Mac OS and sent it to a Windows machine, the default compression changes these files so the encoding sent this message.

Unable to use Intellij with a generated sources folder

You can just change the project structure to add that folder as a "source" directory.

Project Structure ? Modules ? Click the generated-sources folder and make it a sources folder.

Or:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <id>test</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${basedir}/target/generated-sources</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Use Font Awesome icon as CSS content

Update for FontAwesome 5 Thanks to Aurelien

You need to change the font-family to Font Awesome 5 Brands OR Font Awesome 5 Free, based on the type of icon you are trying to render. Also, do not forget to declare font-weight: 900;

a:before {
   font-family: "Font Awesome 5 Free";
   content: "\f095";
   display: inline-block;
   padding-right: 3px;
   vertical-align: middle;
   font-weight: 900;
}

Demo

You can read the rest of the answer below to understand how it works and to know some workarounds for spacing between icon and the text.


FontAwesome 4 and below

That's the wrong way to use it. Open the font awesome style sheet, go to the class of the font you want to use say fa-phone, copy the content property under that class with the entity, and use it like:

a:before {
    font-family: FontAwesome;
    content: "\f095";
}

Demo

Just make sure that if you are looking to target a specific a tag, then consider using a class instead to make it more specific like:

a.class_name:before {
    font-family: FontAwesome;
    content: "\f095";
}

Using the way above will stick the icon with the remaining text of yours, so if you want to have a bit of space between the two of them, make it display: inline-block; and use some padding-right:

a:before {
    font-family: FontAwesome;
    content: "\f095";
    display: inline-block;
    padding-right: 3px;
    vertical-align: middle;
}

Extending this answer further, since many might be having a requirement to change an icon on hover, so for that, we can write a separate selector and rules for :hover action:

a:hover:before {
    content: "\f099"; /* Code of the icon you want to change on hover */
}

Demo

Now in the above example, icon nudges because of the different size and you surely don't want that, so you can set a fixed width on the base declaration like

a:before {
    /* Other properties here, look in the above code snippets */
    width: 12px; /* add some desired width here to prevent nudge */
}

Demo

What is the "double tilde" (~~) operator in JavaScript?

That ~~ is a double NOT bitwise operator.

It is used as a faster substitute for Math.floor() for positive numbers. It does not return the same result as Math.floor() for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).

Catching multiple exception types in one catch block

As of PHP 7.1,

catch( AError | BError $e )
{
    handler1( $e )
}

interestingly, you can also:

catch( AError | BError $e )
{
    handler1( $e )
} catch (CError $e){
    handler2($e);
} catch(Exception $e){
    handler3($e);
}

and in earlier versions of PHP:

catch(Exception $ex){
    if($ex instanceof AError){
        //handle a AError
    } elseif($ex instanceof BError){
        //handle a BError
    } else {
       throw $ex;//an unknown exception occured, throw it further
    }
}

Generic htaccess redirect www to non-www

If you are forcing www. in url or forcing ssl prototcol, then try to use possible variations in htaccess file, such as:

RewriteEngine On
RewriteBase /

### Force WWW ###

RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

## Force SSL ###

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

## Block  IP's ###
Order Deny,Allow
Deny from 256.251.0.139
Deny from 199.127.0.259

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Open Terminal:

sudo gem update --system 

It works!

Artificially create a connection timeout error

  • 10.0.0.0
  • 10.255.255.255
  • 172.16.0.0
  • 172.31.255.255
  • 192.168.0.0
  • 192.168.255.255

All these are non-routable.

How to sort a list of strings?

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

AngularJS : How to watch service variables?

Building on dtheodor's answer you could use something similar to the below to ensure that you don't forget to unregister the callback... Some may object to passing the $scope to a service though.

factory('aService', function() {
  var observerCallbacks = [];

  /**
   * Registers a function that will be called when
   * any modifications are made.
   *
   * For convenience the callback is called immediately after registering
   * which can be prevented with `preventImmediate` param.
   *
   * Will also automatically unregister the callback upon scope destory.
   */
  this.registerObserver = function($scope, cb, preventImmediate){
    observerCallbacks.push(cb);

    if (preventImmediate !== true) {
      cb();
    }

    $scope.$on('$destroy', function () {
      observerCallbacks.remove(cb);
    });
  };

  function notifyObservers() {
    observerCallbacks.forEach(function (cb) {
      cb();
    });
  };

  this.foo = someNgResource.query().$then(function(){
    notifyObservers();
  });
});

Array.remove is an extension method which looks like this:

/**
 * Removes the given item the current array.
 *
 * @param  {Object}  item   The item to remove.
 * @return {Boolean}        True if the item is removed.
 */
Array.prototype.remove = function (item /*, thisp */) {
    var idx = this.indexOf(item);

    if (idx > -1) {
        this.splice(idx, 1);

        return true;
    }
    return false;
};

Edit and replay XHR chrome/firefox etc?

Chrome :

  • In the Network panel of devtools, right-click and select Copy as cURL
  • Paste / Edit the request, and then send it from a terminal, assuming you have the curl command

See capture :

enter image description here

Alternatively, and in case you need to send the request in the context of a webpage, select "Copy as fetch" and edit-send the content from the javascript console panel.


Firefox :

Firefox allows to edit and resend XHR right from the Network panel. Capture below is from Firefox 36:

enter image description here

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

As mentioned in the comments, some labels in y_test don't appear in y_pred. Specifically in this case, label '2' is never predicted:

>>> set(y_test) - set(y_pred)
{2}

This means that there is no F-score to calculate for this label, and thus the F-score for this case is considered to be 0.0. Since you requested an average of the score, you must take into account that a score of 0 was included in the calculation, and this is why scikit-learn is showing you that warning.

This brings me to you not seeing the error a second time. As I mentioned, this is a warning, which is treated differently from an error in python. The default behavior in most environments is to show a specific warning only once. This behavior can be changed:

import warnings
warnings.filterwarnings('always')  # "error", "ignore", "always", "default", "module" or "once"

If you set this before importing the other modules, you will see the warning every time you run the code.

There is no way to avoid seeing this warning the first time, aside for setting warnings.filterwarnings('ignore'). What you can do, is decide that you are not interested in the scores of labels that were not predicted, and then explicitly specify the labels you are interested in (which are labels that were predicted at least once):

>>> metrics.f1_score(y_test, y_pred, average='weighted', labels=np.unique(y_pred))
0.91076923076923078

The warning is not shown in this case.

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Limiting double to 3 decimal places

Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.

Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:

decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878

EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).

Using reCAPTCHA on localhost

Recaptcha will not work on localhost/

Use `127.0.0.1/` instead of `localhost/`

Cannot find name 'require' after upgrading to Angular4

Will work in Angular 7+


I was facing the same issue, I was adding

"types": ["node"]

to tsconfig.json of root folder.

There was one more tsconfig.app.json under src folder and I got solved this by adding

"types": ["node"]

to tsconfig.app.json file under compilerOptions

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]  ----------------------< added node to the array
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

The CLI's webpack config can now be ejected. Check Anton Nikiforov's answer.


outdated:

You can hack the config template in angular-cli/addon/ng2/models. There's no official way to modify the webpack config as of now.

There's a closed "wont-fix" issue on github about this: https://github.com/angular/angular-cli/issues/1656

password-check directive in angularjs

The following is my take on the problem. This directive would compare against a form value instead of the scope.

'use strict';
(function () {
    angular.module('....').directive('equals', function ($timeout) {
        return {
            restrict: 'A',
            require: ['^form', 'ngModel'],
            scope: false,
            link: function ($scope, elem, attrs, controllers) {
                var validationKey = 'equals';
                var form = controllers[0];
                var ngModel = controllers[1];

                if (!ngModel) {
                    return;
                }

                //run after view has rendered
                $timeout(function(){
                    $scope.$watch(attrs.ngModel, validate);

                    $scope.$watch(form[attrs.equals], validate);
                }, 0);

                var validate = function () {
                    var value1 = ngModel.$viewValue;
                    var value2 = form[attrs.equals].$viewValue;
                    var validity = !value1 || !value2 || value1 === value2;
                    ngModel.$setValidity(validationKey, validity);
                    form[attrs.equals].$setValidity(validationKey,validity);
                };
            }
        };
    });
})();

in the HTML one now refers to the actual form instead of the scoped value:

<form name="myForm">
  <input type="text" name="value1" equals="value2">
  <input type="text" name="value2" equals="value1">
  <div ng-show="myForm.$invalid">The form is invalid!</div>
</form>

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

Read entire file in Scala?

For faster overall reading / uploading a (large) file, consider increasing the size of bufferSize (Source.DefaultBufSize set to 2048), for instance as follows,

val file = new java.io.File("myFilename")
io.Source.fromFile(file, bufferSize = Source.DefaultBufSize * 2)

Note Source.scala. For further discussion see Scala fast text file read and upload to memory.

Splitting words into letters in Java

Including numbers but not whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();

=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u

Without numbers and whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()

=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u

How to overcome "datetime.datetime not JSON serializable"?

The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object.

def myconverter(o):
 if isinstance(o, datetime.datetime):
    return o.__str__()

print(json.dumps(d, default = myconverter)) 

Read from file in eclipse

Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

What does ':' (colon) do in JavaScript?

That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.

How can I load storyboard programmatically from class?

In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

Set type for function parameters?

No, JavaScript is not a statically typed language. Sometimes you may need to manually check types of parameters in your function body.

"Operation must use an updateable query" error in MS Access

I had the same error when was trying to update linked table.

The issue was that linked table had no PRIMARY KEY.

After adding primary key constraint on database side and re linking this table to access problem was solved.

Hope it will help somebody.

Constructors in JavaScript objects

I guess I'll post what I do with javascript closure since no one is using closure yet.

var user = function(id) {
  // private properties & methods goes here.
  var someValue;
  function doSomething(data) {
    someValue = data;
  };

  // constructor goes here.
  if (!id) return null;

  // public properties & methods goes here.
  return {
    id: id,
    method: function(params) {
      doSomething(params);
    }
  };
};

Comments and suggestions to this solution are welcome. :)

How to print the array?

You could try this:

#include <stdio.h>

int main() 
{  
  int i,j;
  int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
  for(i = 0; i < 3; i++) 
  {
       for(j = 0; j < 3; j++) 
       {
         printf("%d ", my_array[i][j]);
       }
    printf("\n");
  } 
  return 0;
}

Difference between agile and iterative and incremental development

  • Iterative - you don't finish a feature in one go. You are in a code >> get feedback >> code >> ... cycle. You keep iterating till done.
  • Incremental - you build as much as you need right now. You don't over-engineer or add flexibility unless the need is proven. When the need arises, you build on top of whatever already exists. (Note: differs from iterative in that you're adding new things.. vs refining something).
  • Agile - you are agile if you value the same things as listed in the agile manifesto. It also means that there is no standard template or checklist or procedure to "do agile". It doesn't overspecify.. it just states that you can use whatever practices you need to "be agile". Scrum, XP, Kanban are some of the more prescriptive 'agile' methodologies because they share the same set of values. Continuous and early feedback, frequent releases/demos, evolve design, etc.. hence they can be iterative and incremental.

Creating a search form in PHP to search a database?

Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.

BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.

How to determine when Fragment becomes visible in ViewPager

Detecting by focused view!

This works for me

public static boolean isFragmentVisible(Fragment fragment) {
    Activity activity = fragment.getActivity();
    View focusedView = fragment.getView().findFocus();
    return activity != null
            && focusedView != null
            && focusedView == activity.getWindow().getDecorView().findFocus();
}

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

What regular expression will match valid international phone numbers?

No criticism regarding those great answers I just want to present the simple solution I use for our admin content creators:

^(\+|00)[1-9][0-9 \-\(\)\.]{7,}$

Force start with a plus or two zeros and use at least a little bit of numbers, white space, braces, minus and point is optional and no other characters. You can safely remove all non-numbers and use this in a tel: input. Numbers will have a common form of representation and I do not have to worry about being to restrictive.

MySQL "Or" Condition

Your question is about the operator precedences in mysql and Alex has shown you how to "override" the precedence with parentheses.

But on a side note, if your column date is of the type Date you can use MySQL's date and time functions to fetch the records of the last seven days, like e.g.

SELECT
  *
FROM
  Drinks
WHERE
  email='$Email'
  AND date >= Now()-Interval 7 day

(or maybe Curdate() instead of Now())

Print a string as hex bytes?

Another answer in two lines that some might find easier to read, and helps with debugging line breaks or other odd characters in a string:

For Python 2.7

for character in string:
    print character, character.encode('hex')

For Python 3.7 (not tested on all releases of 3)

for character in string:
    print(character, character.encode('utf-8').hex())

Sniffing/logging your own Android Bluetooth traffic

Also, this might help finding the actual location the btsnoop_hci.log is being saved:

adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // do something with BGR values...
    }
}

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...
    }
}

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...
    }
}

Maven Jacoco Configuration - Exclude classes/packages from report not working

Here is the working sample in pom.xml file.

    <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>${jacoco.version}</version>


        <executions>
            <execution>
                <id>prepare-agent</id>
                <goals>
                    <goal>prepare-agent</goal>
                </goals>
            </execution>
            <execution>
                <id>post-unit-test</id>
                <phase>test</phase>
                <goals>
                    <goal>report</goal>
                </goals>

            </execution>

            <execution>
                <id>default-check</id>
                <goals>
                    <goal>check</goal>
                </goals>

            </execution>
        </executions>
        <configuration>
            <dataFile>target/jacoco.exec</dataFile>
            <!-- Sets the output directory for the code coverage report. -->
            <outputDirectory>target/jacoco-ut</outputDirectory>
            <rules>
                <rule implementation="org.jacoco.maven.RuleConfiguration">
                    <element>PACKAGE</element>
                    <limits>
                        <limit implementation="org.jacoco.report.check.Limit">
                            <counter>COMPLEXITY</counter>
                            <value>COVEREDRATIO</value>
                            <minimum>0.00</minimum>
                        </limit>
                    </limits>
                </rule>
            </rules>
            <excludes>
                <exclude>com/pfj/fleet/dao/model/**/*</exclude>
            </excludes>
            <systemPropertyVariables>

                <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
            </systemPropertyVariables>
        </configuration>
    </plugin>

R: Plotting a 3D surface from x, y, z

You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.

The variables "b" and "s" could be x or y.

require(lattice)

# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape


wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
    light.source = c(10,10,10), main = "Study 1",
    scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
    screen = list(z = 40, x = -75, y = 0))

Magento addFieldToFilter: Two fields, match as OR, not AND

This is the real magento way:

    $collection=Mage::getModel('sales/order')
                ->getCollection()
                ->addFieldToFilter(
                        array(
                            'customer_firstname',//attribute_1 with key 0
                            'remote_ip',//attribute_2 with key 1
                        ),
                        array(
                            array('eq'=>'gabe'),//condition for attribute_1 with key 0
                            array('eq'=>'127.0.0.1'),//condition for attribute_2
                                )
                            )
                        );

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

What is aria-label and how should I use it?

In the example you give, you're perfectly right, you have to set the title attribute.

If the aria-label is one tool used by assistive technologies (like screen readers), it is not natively supported on browsers and has no effect on them. It won't be of any help to most of the people targetted by the WCAG (except screen reader users), for instance a person with intellectal disabilities.

The "X" is not sufficient enough to give information to the action led by the button (think about someone with no computer knowledge). It might mean "close", "delete", "cancel", "reduce", a strange cross, a doodle, nothing.

Despite the fact that the W3C seems to promote the aria-label rather that the title attribute here: http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140916/ARIA14 in a similar example, you can see that the technology support does not include standard browsers : http://www.w3.org/WAI/WCAG20/Techniques/ua-notes/aria#ARIA14

In fact aria-label, in this exact situation might be used to give more context to an action:

For instance, blind people do not perceive popups like those of us with good vision, it's like a change of context. "Back to the page" will be a more convenient alternative for a screen reader, when "Close" is more significant for someone with no screen reader.

  <button
      aria-label="Back to the page"
      title="Close" onclick="myDialog.close()">X</button>

Set position / size of UI element as percentage of screen size

Use the PercentRelativeLayout or PercentFrameLayout from the Percent Supoort Library

<android.support.percent.PercentFrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
     <TextView
          android:layout_width="match_parent"
          app:layout_heightPercent="68%"/>
     <Gallery 
          android:id="@+id/gallery"
          android:layout_width="match_parent"
          app:layout_heightPercent="16%"/>
     <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_width="match_parent"/>
</android.support.percent.PercentFrameLayout>

How to cast an object in Objective-C

Remember, Objective-C is a superset of C, so typecasting works as it does in C:

myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;

Add newly created specific folder to .gitignore in Git

From "git help ignore" we learn:

If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

Therefore what you need is

public_html/stats/

How to handle authentication popup with Selenium WebDriver using Java

The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication box.

WebDriverWait wait = new WebDriverWait(driver, 10);      
Alert alert = wait.until(ExpectedConditions.alertIsPresent());     
alert.authenticateUsing(new UserAndPassword(username, password));

As of Selenium 3.4 it is still in beta

Right now implementation is only done for InternetExplorerDriver

Retrieve data from website in android app

Use this

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.someplace.com");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);

This can be used to grab the whole webpage as a string of html, i.e., "<html>...</html>"

Note You need to declare the following 'uses-permission' in the android manifest xml file... answer by @Squonk here

And also check this answer

What is the use of the %n format specifier in C?

From here we see that it stores the number of characters printed so far.

n The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of the fprintf() functions. No argument is converted.

An example usage would be:

int n_chars = 0;
printf("Hello, World%n", &n_chars);

n_chars would then have a value of 12.

AngularJS - Passing data between pages

What you should do is create a service to share data between controllers.

Nice tutorial https://www.youtube.com/watch?v=HXpHV5gWgyk

What does it mean "No Launcher activity found!"

Do you have an activity set up the be the launched activity when the application starts?

This is done in your Manifest.xml file, something like:

    <activity android:name=".Main" android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Checking during array iteration, if the current element is the last element

$arr = array(1, 'a', 3, 4 => 1, 'b' => 1);
foreach ($arr as $key => $val) {
    echo "{$key} = {$val}" . (end(array_keys($arr))===$key ? '' : ', ');
}
// output: 0 = 1, 1 = a, 2 = 3, 4 = 1, b = 1

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

How to define a two-dimensional array?

You can create an empty two dimensional list by nesting two or more square bracing or third bracket ([], separated by comma) with a square bracing, just like below:

Matrix = [[], []]

Now suppose you want to append 1 to Matrix[0][0] then you type:

Matrix[0].append(1)

Now, type Matrix and hit Enter. The output will be:

[[1], []]

If you entered the following statement instead

Matrix[1].append(1)

then the Matrix would be

[[], [1]]

Dealing with commas in a CSV file

    public static IEnumerable<string> LineSplitter(this string line, char 
         separator, char skip = '"')
    {
        var fieldStart = 0;
        for (var i = 0; i < line.Length; i++)
        {
            if (line[i] == separator)
            {
                yield return line.Substring(fieldStart, i - fieldStart);
                fieldStart = i + 1;
            }
            else if (i == line.Length - 1)
            {
                yield return line.Substring(fieldStart, i - fieldStart + 1);
                fieldStart = i + 1;
            }

            if (line[i] == '"')
                for (i++; i < line.Length && line[i] != skip; i++) { }
        }

        if (line[line.Length - 1] == separator)
        {
            yield return string.Empty;
        }
    }

How to print_r $_POST array?

Because you have nested arrays, then I actually recommend a recursive approach:

function recurse_into_array( $in, $tabs = "" )
{
    foreach( $in as $key => $item )
    {
        echo $tabs . $key . ' => ';
        if( is_array( $item ) )
        {
            recurse_into_array( $item, $tabs . "\t" );
        }
        else
        {
            echo $tabs . "\t" . $key;
        }
    }
}

recurse_into_array( $_POST );

Is there functionality to generate a random character in Java?

To generate a random char in a-z:

Random r = new Random();
char c = (char)(r.nextInt(26) + 'a');

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

MySQL Workbench Edit Table Data is read only

Hovering over the icon "read only" in mysql workbench shows a tooltip that explains why it cannot be edited. In my case it said, only tables with primary keys or unique non-nullable columns can be edited.

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

How do I use this JavaScript variable in HTML?

You can create a <p> element:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <script>_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
  p = document.createElement("p");_x000D_
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";_x000D_
  document.body.appendChild(p);_x000D_
  </script>_x000D_
  <body>_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How do I get a substring of a string in Python?

a="Helloo"
print(a[:-1])

In the above code, [:-1] declares to print from the starting till the maximum limit-1.

OUTPUT :

>>> Hello

Note: Here a [:-1] is also the same as a [0:-1] and a [0:len(a)-1]

a="I Am Siva"
print(a[2:])

OUTPUT:

>>> Am Siva

In the above code a [2:] declares to print a from index 2 till the last element.

Remember that if you set the maximum limit to print a string, as (x) then it will print the string till (x-1) and also remember that the index of a list or string will always start from 0.

Detach (move) subdirectory into separate Git repository

Put this into your gitconfig:

reduce-to-subfolder = !sh -c 'git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter cookbooks/unicorn HEAD && git reset --hard && git for-each-ref refs/original/ | cut -f 2 | xargs -n 1 git update-ref -d && git reflog expire --expire=now --all && git gc --aggressive --prune=now && git remote rm origin'

Import txt file and having each line as a list

Create a list of lists:

with open("/path/to/file") as file:
    lines = []
    for line in file:
        # The rstrip method gets rid of the "\n" at the end of each line
        lines.append(line.rstrip().split(","))

console.log showing contents of array object

there are two potential simple solutions to dumping an array as string. Depending on the environment you're using:

…with modern browsers use JSON:

JSON.stringify(filters);
// returns this
"{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"

…with something like node.js you can use console.info()

console.info(filters);
// will output:
{ dvals: 
[ { brand: '1', count: '1' },
  { brand: '2', count: '2' },
  { brand: '3', count: '3' } ] }

Edit:

JSON.stringify comes with two more optional parameters. The third "spaces" parameter enables pretty printing:

JSON.stringify(
                obj,      // the object to stringify
                replacer, // a function or array transforming the result
                spaces    // prettyprint indentation spaces
              )

example:

JSON.stringify(filters, null, "  ");
// returns this
"{
 "dvals": [
  {
   "brand": "1",
   "count": "1"
  },
  {
   "brand": "2",
   "count": "2"
  },
  {
   "brand": "3",
   "count": "3"
  }
 ]
}"

Convert blob to base64

Most easiest way in a single line of code

var base64Image = new Buffer( blob, 'binary' ).toString('base64');

How can I convert String[] to ArrayList<String>

You can loop all of the array and add into ArrayList:

ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
    files.add(file);
}

Or use Arrays.asList(T... a) to do as the comment posted.

Strange Jackson exception being thrown when serializing Hibernate object

I am New to Jackson API, when i got the "org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.company.project.yourclass" , I added the getter and setter to com.company.project.yourclass, that helped me to use the ObjectMapper's mapper object to write the java object into a flat file.

How do I format a number with commas in T-SQL?

For SQL Server before 2012 which does not include the FORMAT function, create this function:

CREATE FUNCTION FormatCurrency(@value numeric(30,2))
    RETURNS varchar(50)
    AS
    BEGIN
        DECLARE @NumAsChar VARCHAR(50)
        SET @NumAsChar = '$' + CONVERT(varchar(50), CAST(@Value AS money),1)
        RETURN @NumAsChar
    END 

select dbo.FormatCurrency(12345678) returns $12,345,678.00

Drop the $ if you just want commas.

Count work days between two dates

Using a date table:

    DECLARE 
        @StartDate date = '2014-01-01',
        @EndDate date = '2014-01-31'; 
    SELECT 
        COUNT(*) As NumberOfWeekDays
    FROM dbo.Calendar
    WHERE CalendarDate BETWEEN @StartDate AND @EndDate
      AND IsWorkDay = 1;

If you don't have that, you can use a numbers table:

    DECLARE 
    @StartDate datetime = '2014-01-01',
    @EndDate datetime = '2014-01-31'; 
    SELECT 
    SUM(CASE WHEN DATEPART(dw, DATEADD(dd, Number-1, @StartDate)) BETWEEN 2 AND 6 THEN 1 ELSE 0 END) As NumberOfWeekDays
    FROM dbo.Numbers
    WHERE Number <= DATEDIFF(dd, @StartDate, @EndDate) + 1 -- Number table starts at 1, we want a 0 base

They should both be fast and it takes out the ambiguity/complexity. The first option is the best but if you don't have a calendar table you can allways create a numbers table with a CTE.

How do I see which version of Swift I'm using?

Bonus contribution: I'm using a custom node.js script to extract a clean string for use with Jazzy documentation. You might get some use of this if you can find a place to work it into your dev process:

Invoked from a Bash script:

#!/bin/bash
swiftversion=$(node SwiftVerSlicer.js "${xcrun swift -version}");
echo $swiftversion

SwiftVerSlicer.js:

// begin script
const inputString = `${process.argv[2]}`
let searchTerm = (inputString.indexOf('(') - 1)//-1 cause whitespace
let version = inputString.slice(0,searchTerm)
console.log(version)
// end script

You can also use regex of course, but do whatever you like :]

Can I restore a single table from a full mysql mysqldump file?

Get a decent text editor like Notepad++ or Vim (if you're already proficient with it). Search for the table name and you should be able to highlight just the CREATE, ALTER, and INSERT commands for that table. It may be easier to navigate with your keyboard rather than a mouse. And I would make sure you're on a machine with plenty or RAM so that it will not have a problem loading the entire file at once. Once you've highlighted and copied the rows you need, it would be a good idea to back up just the copied part into it's own backup file and then import it into MySQL.

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

Removing empty lines in Notepad++

CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines as suggested above works.

But if lines contains some space, then move the cursor to that line and do a CTRL + H. The "Find what:" sec will show the blank space and in the "Replace with" section, leave it blank. Now all the spaces are removed and now try CTRL+A, Select the TextFX menu -> TextFX Edit -> Delete Blank Lines

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

See this answer for more info on How to access the dom element in React

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

How can I install Apache Ant on Mac OS X?

MacPorts will install ant for you in MacOSX 10.9. Just use

$ sudo port install apache-ant

and it will install.

Make REST API call in Swift

Swift 5 & 4

let params = ["username":"john", "password":"123456"] as Dictionary<String, String>

var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
    print(response!)
    do {
        let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
        print(json)
    } catch {
        print("error")
    }
})

task.resume()

How do I convert from int to Long in Java?

 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)

Conversion between UTF-8 ArrayBuffer and String

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                                   ((char2 & 0x3F) << 6) |
                                   ((char3 & 0x3F) << 0));
        break;
    }
  }    
  return out;
}

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here, here

Mysql database sync between two databases

three different approaches:

  1. Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.

  2. replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.

  3. offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.

How to replace all special character into a string using C#

Also, It can be done with LINQ

var str = "Hello@Hello&Hello(Hello)";
var characters = str.Select(c => char.IsLetter(c) ? c : ',')).ToArray();             
var output = new string(characters);
Console.WriteLine(output);

Finding element in XDocument?

The Elements() method returns an IEnumerable<XElement> containing all child elements of the current node. For an XDocument, that collection only contains the Root element. Therefore the following is required:

var query = from c in xmlFile.Root.Elements("Band")
            select c;

Lightbox to show videos from Youtube and Vimeo?

Check out this list of lightbox plugins, depending on your exact requirements you can find the plugin of your choice from there easier than asking here. If you need a specific lightbox which can do just about anything and everything, try NyroModal.

Connect Device to Mac localhost Server?

also, make sure the server is listening for ur mobile device! for example, by default jekyll only answers requests made by the host machine. this solved my problem:

Connect to a locally built Jekyll Server using mobile devices in the LAN

How can you detect the version of a browser?

For chromium browser is so simple.

Version : navigator.userAgentData.brands[0].version

Browser Name : navigator.userAgentData.brands[0].brand

How to get an HTML element's style values in javascript?

I believe you are now able to use Window.getComputedStyle()

Documentation MDN

var style = window.getComputedStyle(element[, pseudoElt]);

Example to get width of an element:

window.getComputedStyle(document.querySelector('#mainbar')).width

jQuery if Element has an ID?

You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.

See fiddle here.

$('a').each(function() {
    $(this).click(function() {
        var el= $(this).attr('id');
        if (el === 'notme') {
            // do nothing or something else
        } else {
            $('p').toggle();
        }
    });
});

How to fix the error "Windows SDK version 8.1" was not found?

Grep the folder tree's *.vcxproj files. Replace <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> with <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> or whatever SDK version you get when you update one of the projects.

Make Axios send cookies in its requests automatically

for people still not able to solve it, this answer helped me. stackoverflow answer: 34558264

TLDR; one needs to set {withCredentials: true} in both GET request as well the POST request (getting the cookie) for both axios as well as fetch.

onNewIntent() lifecycle and registered listeners

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

Is there such a thing as min-font-size and max-font-size?

Rucksack is brilliant, but you don't necessarily have to resort to build tools like Gulp or Grunt etc.

I made a demo using CSS Custom Properties (CSS Variables) to easily control the min and max font sizes.

Like so:

* {
  /* Calculation */
  --diff: calc(var(--max-size) - var(--min-size));
  --responsive: calc((var(--min-size) * 1px) + var(--diff) * ((100vw - 420px) / (1200 - 420))); /* Ranges from 421px to 1199px */
}

h1 {
  --max-size: 50;
  --min-size: 25;
  font-size: var(--responsive);
}

h2 {
  --max-size: 40;
  --min-size: 20;
  font-size: var(--responsive);
}

how to remove time from datetime

For more info refer this: SQL Server Date Formats

[MM/DD/YYYY]

SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 101) from tbl

[DD/MM/YYYY]

SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 103) from tbl

Live Demo

How to get element by class name?

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName('foo');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:

How to delete multiple values from a vector?

instead of

x <- x[! x %in% c(2,3,5)]

using the packages purrr and magrittr, you can do:

your_vector %<>% discard(~ .x %in% c(2,3,5))

this allows for subsetting using the vector name only once. And you can use it in pipes :)

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

Disabling the button after once click

jQuery now has the .one() function that limits any given event (such as "submit") to one occurrence.

Example:

$('#myForm').one('submit', function() {
    $(this).find('input[type="submit"]').attr('disabled','disabled');
});

This code will let you submit the form once, then disable the button. Change the selector in the find() function to whatever button you'd like to disable.

Note: Per Francisco Goldenstein, I've changed the selector to the form and the event type to submit. This allows you to submit the form from anywhere (places other than the button) while still disabling the button on submit.

Note 2: Per gorelog, using attr('disabled','disabled') will prevent your form from sending the value of the submit button. If you want to pass the button value, use attr('onclick','this.style.opacity = "0.6"; return false;') instead.

Check if all values in list are greater than a certain number

...any reason why you can't use min()?

def above(my_list, minimum):
    if min(my_list) >= minimum:
        print "All values are equal or above", minimum
    else:
        print "Not all values are equal or above", minimum

I don't know if this is exactly what you want, but technically, this is what you asked for...

How to generate a Makefile with source in sub-directories using just one makefile

The reason is that your rule

%.o: %.cpp
       ...

expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.

You can use VPATH to resolve this:

VPATH = src/widgets

BUILDDIR = build/widgets

$(BUILDDIR)/%.o: %.cpp
      ...

When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:

$(BUILDDIR)/%.o: %.cpp
        $(CC) $< -o $@

Where "$<" expands to the path where make located the first dependency.

Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like

build/widgets/%.o: %.cpp
        ....

build/ui/%.o: %.cpp
        ....

build/tests/%.o: %.cpp
        ....

I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:

define cc-command
$(CC) $(CFLAGS) $< -o $@
endef

You can then have multiple rules like this:

build1/foo.o build1/bar.o: %.o: %.cpp
    $(cc-command)

build2/frotz.o build2/fie.o: %.o: %.cpp
    $(cc-command)

Downloading Java JDK on Linux via wget is shown license page instead

(Irani updated to my answer, but here's to clarify it all.)

Edit: Updated for Java 11.0.1, released in 16th October, 2018

Wget

wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/11.0.1+13/90cf5d8f270a4347a95050320eef3fb7/jdk-11.0.1_linux-x64_bin.tar.gz

JRE 8u191 (no cookie flags): http://javadl.oracle.com/webapps/download/AutoDL?BundleId=235717_2787e4a523244c269598db4e85c51e0c
See the downloads in oracle.com and java.com for more.

  • -c / --continue

    Allows continuing an unfinished download.

  • --header "Cookie: oraclelicense=accept-securebackup-cookie"

    Since 15th March 2014 this cookie is provided to the user after accepting the License Agreement and is necessary for accessing the Java packages in download.oracle.com. The previous (and first) implementation in 27th March 2012 made use of the cookie gpw_e24=http%3A%2F%2Fwww.oracle.com[...]. Both cases remain unannounced to the public.

    The value doesn't have to be "accept-securebackup-cookie".

Required for Wget<1.13

  • --no-check-certificate

    Only required with wget 1.12 and earlier, which do not support Subject Alternative Name (SAN) certificates (mainly Red Hat Enterprise Linux 6.x and friends, such as CentOS). 1.13 was released in August 2011.

    To see the current version, use: wget --version | head -1

Not required

  • --no-cookies

    The combination --no-cookies --header "Cookie: name=value" is mentioned as the "official" cookie support, but not strictly required here.

cURL

curl -L -C - -b "oraclelicense=accept-securebackup-cookie" -O http://download.oracle.com/otn-pub/java/jdk/11.0.1+13/90cf5d8f270a4347a95050320eef3fb7/jdk-11.0.1_linux-x64_bin.tar.gz
  • -L / --location

    Required for cURL to redirect through all the mirrors.

  • -C / --continue-at -

    See above. cURL requires the dash (-) in the end.

  • -b / --cookie "oraclelicense=accept-securebackup-cookie"

    Same as -H / --header "Cookie: ...", but accepts files too.

  • -O

    Required for cURL to save files (see author's comparison for more differences).

How to use SqlClient in ASP.NET Core?

Try this one Open your projectname.csproj file its work for me.

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

You need to add this Reference "ItemGroup" tag inside.

How to set encoding in .getJSON jQuery

Use this function to regain the utf-8 characters

function decode_utf8(s) { 
  return decodeURIComponent(escape(s)); 
}

Example: var new_Str=decode_utf8(str);

Select max value of each group

select name, max(value)
from out_pumptable
group by name

How to recognize vehicle license / number plate (ANPR) from an image?

There is a new, open source library on GitHub that does ANPR for US and European plates. It looks pretty accurate and it should do exactly what you need (recognize the plate regions). Here is the GitHub project: https://github.com/openalpr/openalpr

Attempted to read or write protected memory

Hi There are two possible reasons.

  1. We have un-managed code and we are calling it from managed code. that is preventing to run this code. try running these commands and restart your pc

    cmd: netsh winsock reset

open cmd.exe and run command "netsh winsock reset catalog"

  1. Anti-virus is considering un-managed code as harmful and restricting to run this code disable anti-virus and then check

Failing to run jar file from command line: “no main manifest attribute”

First run your application from eclipse to create launch configuration. Then just follow the steps:

  1. From the menu bar's File menu, select Export.
  2. Expand the Java node and select Runnable JAR file. Click Next.
  3. In the Runnable JAR File Specification page, select a 'Java Application' launch configuration to use to create a runnable JAR.
  4. In the Export destination field, either type or click Browse to select a location for the JAR file.
  5. Select an appropriate library handling strategy.
  6. Optionally, you can also create an ANT script to quickly regenerate a previously created runnable JAR file.

Source: Creating a New Runnable JAR File at Eclipse.org

Regular Expression to match string starting with a specific word

Like @SharadHolani said. This won't match every word beginning with "stop"

. Only if it's at the beginning of a line like "stop going". @Waxo gave the right answer:

This one is slightly better, if you want to match any word beginning with "stop" and containing nothing but letters from A to Z.

\bstop[a-zA-Z]*\b

This would match all

stop (1)

stop random (2)

stopping (3)

want to stop (4)

please stop (5)

But

/^stop[a-zA-Z]*/

would only match (1) until (3), but not (4) & (5)

size of struct in C

As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

As of October 3, 2012, a new "Elastic Beanstalk for Java with Apache Tomcat 7" Linux x64 AMI deployed with the Sample Application has the install here:

/etc/tomcat7/

The /etc/tomcat7/tomcat7.conf file has the following settings:

# Where your java installation lives
JAVA_HOME="/usr/lib/jvm/jre"

# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat7"
CATALINA_HOME="/usr/share/tomcat7"
JASPER_HOME="/usr/share/tomcat7"
CATALINA_TMPDIR="/var/cache/tomcat7/temp"

Send multiple checkbox data to PHP via jQuery ajax()

    $.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like.

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

Convert the values in a column into row names in an existing data frame

This should do:

samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]

So in short, no there is no alternative to reassigning.

Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:

R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
   b c
a  1 A
b  2 B
c  3 C
d  4 D
e  5 E
f  6 F
g  7 G
h  8 H
i  9 I
j 10 J
R> 

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Android - save/restore fragment state

In order to save the Fragment state you need to implement onSaveInstanceState(): "Also like an activity, you can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState() callback and restore it during either onCreate(), onCreateView(), or onActivityCreated(). For more information about saving state, see the Activities document."

http://developer.android.com/guide/components/fragments.html#Lifecycle

Java 8 lambda Void argument

I think this table is short and usefull:

Supplier       ()    -> x
Consumer       x     -> ()
Callable       ()    -> x throws ex
Runnable       ()    -> ()
Function       x     -> y
BiFunction     x,y   -> z
Predicate      x     -> boolean
UnaryOperator  x1    -> x2
BinaryOperator x1,x2 -> x3

As said on the other answers, the appropriate option for this problem is a Runnable

How to prove that a problem is NP complete?

In order to prove that a problem L is NP-complete, we need to do the following steps:

  1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
  2. Select a known NP-complete problem L'
  3. Describe an algorithm f that transforms L' into L
  4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
  5. Prove that algo f runs in polynomial time

'innerText' works in IE, but not in Firefox

As in 2016 from Firefox v45, innerText works on firefox, take a look at its support: http://caniuse.com/#search=innerText

If you want it to work on previous versions of Firefox, you can use textContent, which has better support on Firefox but worse on older IE versions: http://caniuse.com/#search=textContent

Extract MSI from EXE

There is no need to use any tool !! We can follow the simple way.

I do not know which tool built your self-extracting Setup program and so, I will have to provide a general response.

Most programs of this nature extract the package file (.msi) into the TEMP directory. This behavior is the default behavior of InstallShield Developer.

Without additional information, I would recommend that you simply launch the setup and once the first MSI dialog is displayed, you can examine your TEMP directory for a newly created sub-directory or MSI file. Before cancelling/stopping an installer just copy that MSI file from TEMP folder. After that you can cancel the installation.

Swift: Reload a View Controller

Swift 5.2

The only method I found to work and refresh a view dynamically where the visibility of buttons had changed was:-

viewWillAppear(true)

This may be a bad practice but hopefully somebody will leave a comment.

How to read all rows from huge table?

Use a CURSOR in PostgreSQL or let the JDBC-driver handle this for you.

LIMIT and OFFSET will get slow when handling large datasets.

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

How do ports work with IPv6?

They work almost the same as today. However, be sure you include [] around your IP.

For example : http://[1fff:0:a88:85a3::ac1f]:8001/index.html

Wikipedia has a pretty good article about IPv6: http://en.wikipedia.org/wiki/IPv6#Addressing

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

Can't you implement your own timeout system?

Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.

That action could be closing a socket that hasn't connected yet.

Downloading MySQL dump from command line

If downloading from remote server, here is a simple example:

mysqldump -h my.address.amazonaws.com -u my_username -p db_name > /home/username/db_backup_name.sql

The -p indicates you will enter a password, it does not relate to the db_name. After entering the command you will be prompted for the password. Type it in and press enter.

What is the best way to extract the first word from a string in Java?

None of these answers appears to define what the OP might mean by a "word". As others have already said, a "word boundary" may be a comma, and certainly can't be counted on to be a space, or even "white space" (i.e. also tabs, newlines, etc.)

At the simplest, I'd say the word has to consist of any Unicode letters, and any digits. Even this may not be right: a String may not qualify as a word if it contains numbers, or starts with a number. Furthermore, what about hyphens, or apostrophes, of which there are presumably several variants in the whole of Unicode? All sorts of discussions of this kind and many others will apply not just to English but to all other languages, including non-human language, scientific notation, etc. It's a big topic.

But a start might be this (NB written in Groovy):

String givenString = "one two9 thr0ee four"
// String givenString = "onnÜÐæne;:two9===thr0eè? four!"
// String givenString = "mouse"
// String givenString = "&&^^^%"

String[] substrings = givenString.split( '[^\\p{L}^\\d]+' )

println "substrings |$substrings|"

println "first word |${substrings[0]}|"

This works OK for the first, second and third givenStrings. For "&&^^^%" it says that the first "word" is a zero-length string, and the second is "^^^". Actually a leading zero-length token is String.split's way of saying "your given String starts not with a token but a delimiter".

NB in regex \p{L} means "any Unicode letter". The parameter of String.split is of course what defines the "delimiter pattern"... i.e. a clump of characters which separates tokens.

NB2 Performance issues are irrelevant for a discussion like this, and almost certainly for all contexts.

NB3 My first port of call was Apache Commons' StringUtils package. They are likely to have the most effective and best engineered solutions for this sort of thing. But nothing jumped out... https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html ... although something of use may be lurking there.

Add new row to excel Table (VBA)

As using ListRow.Add can be a huge bottle neck, we should only use it if it can’t be avoided. If performance is important to you, use this function here to resize the table, which is quite faster than adding rows the recommended way.

Be aware that this will overwrite data below your table if there is any!

This function is based on the accepted answer of Chris Neilsen

Public Sub AddRowToTable(ByRef tableName As String, ByRef data As Variant)
    Dim tableLO As ListObject
    Dim tableRange As Range
    Dim newRow As Range

    Set tableLO = Range(tableName).ListObject
    tableLO.AutoFilter.ShowAllData

    If (tableLO.ListRows.Count = 0) Then
        Set newRow = tableLO.ListRows.Add(AlwaysInsert:=True).Range
    Else
        Set tableRange = tableLO.Range
        tableLO.Resize tableRange.Resize(tableRange.Rows.Count + 1, tableRange.Columns.Count)
        Set newRow = tableLO.ListRows(tableLO.ListRows.Count).Range
    End If

    If TypeName(data) = "Range" Then
        newRow = data.Value
    Else
        newRow = data
    End If
End Sub

The application was unable to start correctly (0xc000007b)

Also download and unzip "Dependencies" into same folder where you put the wget.exe from

http://gnuwin32.sourceforge.net/packages/wget.htm

You will then have some lib*.dll files as well as wget.exe in the same folder and it should work fine.

(I also answered here https://superuser.com/a/873531/146668 which I originally found.)

How to read from input until newline is found using scanf()?

Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().

Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

How to solve static declaration follows non-static declaration in GCC C code?

You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.

void inlet_update_my_ratio(object_t *myobject);
//some where the implementation is like this
static void inlet_update_my_ratio(object_t *myobject) {
//code
}

If you remove the static from the implementation, the error will go away as below.

 void inlet_update_my_ratio(object_t *myobject) {
    //code
    }

List of all unique characters in a string?

For completeness sake, here's another recipe that sorts the letters as a byproduct of the way it works:

>>> from itertools import groupby
>>> ''.join(k for k, g in groupby(sorted("aaabcabccd")))
'abcd'

How to call a method daily, at specific time, in C#?

As others have said you can use a console app to run when scheduled. What others haven't said is that you can this app trigger a cross process EventWaitHandle which you are waiting on in your main application.

Console App:

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle handle = 
            new EventWaitHandle(true, EventResetMode.ManualReset, "GoodMutexName");
        handle.Set();
    }
}

Main App:

private void Form1_Load(object sender, EventArgs e)
{
    // Background thread, will die with application
    ThreadPool.QueueUserWorkItem((dumby) => EmailWait());
}

private void EmailWait()
{
    EventWaitHandle handle = 
        new EventWaitHandle(false, EventResetMode.ManualReset, "GoodMutexName");

    while (true)
    {
        handle.WaitOne();

        SendEmail();

        handle.Reset();
    }
}

How to plot two histograms together in R?

That image you linked to was for density curves, not histograms.

If you've been reading on ggplot then maybe the only thing you're missing is combining your two data frames into one long one.

So, let's start with something like what you have, two separate sets of data and combine them.

carrots <- data.frame(length = rnorm(100000, 6, 2))
cukes <- data.frame(length = rnorm(50000, 7, 2.5))

# Now, combine your two dataframes into one.  
# First make a new column in each that will be 
# a variable to identify where they came from later.
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'

# and combine into your new data frame vegLengths
vegLengths <- rbind(carrots, cukes)

After that, which is unnecessary if your data is in long format already, you only need one line to make your plot.

ggplot(vegLengths, aes(length, fill = veg)) + geom_density(alpha = 0.2)

enter image description here

Now, if you really did want histograms the following will work. Note that you must change position from the default "stack" argument. You might miss that if you don't really have an idea of what your data should look like. A higher alpha looks better there. Also note that I made it density histograms. It's easy to remove the y = ..density.. to get it back to counts.

ggplot(vegLengths, aes(length, fill = veg)) + 
   geom_histogram(alpha = 0.5, aes(y = ..density..), position = 'identity')

enter image description here

How can I check if an InputStream is empty without reading from it?

I think you are looking for inputstream.available(). It does not tell you whether its empty but it can give you an indication as to whether data is there to be read or not.

Adding an onclick function to go to url in JavaScript?

Try

 window.location = url;

Also use

 window.open(url);

if you want to open in a new window.

Convert string to float?

Try this:

String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue(); 
System.out.println(a);

Is there a conditional ternary operator in VB.NET?

Depends upon the version. The If operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Example:

Dim foo as String = If(bar = buz, cat, dog)

[EDIT]

Prior to 2008 it was IIf, which worked almost identically to the If operator described Above.

Example:

Dim foo as String = IIf(bar = buz, cat, dog)

How can my iphone app detect its own version number?

You can specify the CFBundleShortVersionString string in your plist.info and read that programmatically using the provided API.

Trying to mock datetime.date.today(), but not working

For what it's worth, the Mock docs talk about datetime.date.today specifically, and it's possible to do this without having to create a dummy class:

https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking

>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...     mock_date.today.return_value = date(2010, 10, 8)
...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
...     assert mymodule.date.today() == date(2010, 10, 8)
...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
...

Escape quote in web.config connection string

Use &quot; instead of " to escape it.

web.config is an XML file so you should use XML escaping.

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

See this forum thread.

Update:

&quot; should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \" and ""?

Update 2:

Try single quotes for the connectionString:

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

Or:

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

Update 3:

From MSDN (SqlConnection.ConnectionString Property):

To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.

So:

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

The issue is not with web.config, but the format of the connection string. In a connection string, if you have a " in a value (of the key-value pair), you need to enclose the value in '. So, while Password=somepass"word does not work, Password='somepass"word' does.

Hide horizontal scrollbar on an iframe?

set scrolling="no" attribute in your iframe.

AngularJS ng-if with multiple conditions

Sure you can. Something like:

HTML

<div ng-controller="fessCntrl">    
     <label ng-repeat="(key,val) in list">
       <input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
         <div ng-if="key == 'City' || key == 'County'">
             <pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
         </div>
         <div ng-if="key == 'Town'">
             <pre>Town!!! {{$parent.localityTypeRadio}}</pre>
         </div>        
      </label>
</div>

JS

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

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

    $scope.list = {
        City: [{name: "cityA"}, {name: "cityB"}],
        County: [{ name: "countyA"}, {name: "countyB"}],
        Town: [{ name: "townA"}, {name: "townB"}]
      };

    $scope.localityTypeRadio = 'City';
});

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

Demo Fiddle

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Crop image in android

I found a really cool library, try this out. this is really smooth and easy to use.

https://github.com/TakuSemba/CropMe

Initialize/reset struct to zero/null

Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.

For example:

static const struct x EmptyStruct;

Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.

Then, each time round the loop you can write:

myStructVariable = EmptyStruct;

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

In visual Studio 2017 goto Debug->Option then check Debugging->general-> and check this option

relevant Visual Studio 2017 Options

Download a single folder or directory from a GitHub repo

You can use ghget with any URL copied from the address bar:

ghget https://github.com/fivethirtyeight/data/tree/master/airline-safety

It's a self-contained portable shell script that doesn't use SVN (which didn't work for me on a big repo). It also doesn't use the API so it doesn't require a token and isn't rate-limited.

Disclaimer: I made it.

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

What's the proper way to install pip, virtualenv, and distribute for Python?

On Ubuntu:

sudo apt-get install python-virtualenv

The package python-pip is a dependency, so it will be installed as well.

How to print strings with line breaks in java

Adding /r/n between the Strings solved the problem for me. give it a try. On pasting dont include the '//' for excluding.

Eg: Option01\r\nOption02\r\nOption03

this will give output as
Option01
Option02
Option03

How to set the JDK Netbeans runs on?

For those not using Windows the file to change is netbeans-8.0/etc/netbeans.conf

and the line(s) to change is:

netbeans_jdkhome="/usr/lib/jvm/java-8-oracle"

commenting out the old value and inserting the new value

Replacing &nbsp; from javascript dom text node

var text = "&quot;&nbsp;&amp;&lt;&gt;";
text = text.replaceHtmlEntites();

String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt"  : "<","gt"  : ">"};
return ( s.replace(translate_re, function(match, entity) {
  return translate[entity];
}) );
};

try this.....this worked for me

How to subtract/add days from/to a date?

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

How to overload __init__ method based on argument type?

OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.

class MyData:
    def __init__(self, data):
        self.myList = []
        if isinstance(data, tuple):
            for i in data:
                self.myList.append(i)
        else:
            self.myList = data

    def GetData(self):
        print self.myList

a = [1,2]

b = (2,3)

c = MyData(a)

d = MyData(b)

c.GetData()

d.GetData()

[1, 2]

[2, 3]

Scroll to bottom of Div on page load (jQuery)

I'm working in a legacy codebase trying to migrate to Vue.

In my specific situation (scrollable div wrapped in a bootstrap modal), a v-if showed new content, which I wanted the page to scroll down to. In order to get this behaviour to work, I had to wait for vue to finish re-rendering, and then use jQuery to scroll to the bottom of the modal.

So...

this.$nextTick(function() {
    $('#thing')[0].scrollTop = $('#thing')[0].scrollHeight;
})

How to determine the encoding of text?

EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative

Correctly detecting the encoding all times is impossible.

(From chardet FAQ:)

However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.

There is the chardet library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.

You can also use UnicodeDammit. It will try the following methods:

  • An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.
  • An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.
  • An encoding sniffed by the chardet library, if you have it installed.
  • UTF-8
  • Windows-1252

Removing object from array in Swift 3

This is official answer to find index of specific object, then you can easily remove any object using that index :

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
     // students[i] = "Max"
     students.remove(at: i)
}
print(students)
// Prints ["Ben", "Ivy", "Jordell"]

Here is the link: https://developer.apple.com/documentation/swift/array/2994720-firstindex

Flutter : Vertically center column

While using Column, use this inside the column widget :

mainAxisAlignment: MainAxisAlignment.center

It align its children(s) to the center of its parent Space is its main axis i.e. vertically

or, wrap the column with a Center widget:

Center(
  child: Column(
    children: <ListOfWidgets>,
  ),
)

if it doesn't resolve the issue wrap the parent container with a Expanded widget..

Expanded(
   child:Container(
     child: Column(
       mainAxisAlignment: MainAxisAlignment.center,
       children: children,
     ),
   ),
)

Get class name of object as string in Swift

Swift 3.0

String(describing: MyViewController.self)

Static link of shared library function in gcc

Refer to:

http://www.linuxquestions.org/questions/linux-newbie-8/forcing-static-linking-of-shared-libraries-696714/

http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.apps/2004-05/0436.html

You need the static version of the library to link it.

A shared library is actually an executable in a special format with entry points specified (and some sticky addressing issues included). It does not have all the information needed to link statically.

You can't statically link a shared library (or dynamically link a static one).

The flag -static will force the linker to use static libraries (.a) instead of shared (.so) ones. But static libraries aren't always installed by default, so you may have to install the static library yourself.

Another possible approach is to use statifier or Ermine. Both tools take as input a dynamically linked executable and as output create a self-contained executable with all shared libraries embedded.

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

How to force view controller orientation in iOS 8?

Orientation rotation is a little more complicated if you are inside a UINavigationController or UITabBarController. The problem is that if a view controller is embedded in one of these controllers the navigation or tab bar controller takes precedence and makes the decisions on autorotation and supported orientations.

I use the following 2 extensions on UINavigationController and UITabBarController so that view controllers that are embedded in one of these controllers get to make the decisions.

Give View Controllers the Power!

Swift 2.3

extension UINavigationController {
    public override func supportedInterfaceOrientations() -> Int {
        return visibleViewController.supportedInterfaceOrientations()
    }
    public override func shouldAutorotate() -> Bool {
        return visibleViewController.shouldAutorotate()
    }
}

extension UITabBarController {
    public override func supportedInterfaceOrientations() -> Int {
        if let selected = selectedViewController {
            return selected.supportedInterfaceOrientations()
        }
        return super.supportedInterfaceOrientations()
    }
    public override func shouldAutorotate() -> Bool {
        if let selected = selectedViewController {
            return selected.shouldAutorotate()
        }
        return super.shouldAutorotate()
    }
}

Swift 3

extension UINavigationController {
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return visibleViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations
    }

    open override var shouldAutorotate: Bool {
        return visibleViewController?.shouldAutorotate ?? super.shouldAutorotate
    }
}

extension UITabBarController {
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if let selected = selectedViewController {
            return selected.supportedInterfaceOrientations
        }
        return super.supportedInterfaceOrientations
    }

    open override var shouldAutorotate: Bool {
        if let selected = selectedViewController {
            return selected.shouldAutorotate
        }
        return super.shouldAutorotate
    }
}

Now you can override the supportedInterfaceOrientations method or you can override shouldAutoRotate in the view controller you want to lock down otherwise you can leave out the overrides in other view controllers that you want to inherit the default orientation behavior specified in your app's plist

Disable Rotation

class ViewController: UIViewController {
    override func shouldAutorotate() -> Bool {
        return false
    }
}

Lock to Specific Orientation

class ViewController: UIViewController {
    override func supportedInterfaceOrientations() -> Int {
        return Int(UIInterfaceOrientationMask.Landscape.rawValue)
    }
}

In theory this should work for all complex view controller hierarchies, but I have noticed an issue with UITabBarController. For some reason it wants to use a default orientation value. See the following blog post if you are interested in learning about how to work around some of the issues:

Lock Screen Rotation

How to get the Touch position in android?

Here is the Koltin style, I use this in my project and it works very well:

this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
        val x = event.x
        val y = event.y

        when(event.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_UP -> {
                Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
            }
        }
        return@OnTouchListener  true
    })

What do the crossed style properties in Google Chrome devtools mean?

If you want to apply the style even after getting struck-trough indication, you can use "!important" to enforce the style. It may not be a right solution but solve the problem.

python how to "negate" value : if true return false, if false return true

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

AWK to print field $2 first, then field $1

A couple of general tips (besides the DOS line ending issue):

cat is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file.

You can set the field separator with the -F option so instead of:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}' 

Try:

awk -F'|' '{print $2" "$1}' foo 

This will output:

com.emailclient.account [email protected]
com.socialsite.auth.accoun [email protected]

To get the desired output you could do a variety of things. I'd probably split() the second field:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient [email protected]
socialsite [email protected]

Finally to get the first character converted to uppercase is a bit of a pain in awk as you don't have a nice built in ucfirst() function:

awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient [email protected]
Socialsite [email protected]

If you want something more concise (although you give up a sub-process) you could do:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient [email protected]
Socialsite [email protected]

What does the 'b' character do in front of a string literal?

It turns it into a bytes literal (or str in 2.x), and is valid for 2.6+.

The r prefix causes backslashes to be "uninterpreted" (not ignored, and the difference does matter).

CSS hexadecimal RGBA?

I found the answer after posting the enhancement to the question. Sorry!

MS Excel helped!

simply add the Hex prefix to the hex colour value to add an alpha that has the equivalent opacity as the % value.

(in rbga the percentage opacity is expressed as a decimal as mentioned above)

Opacity %   255 Step        2 digit HEX prefix
0%          0.00            00
5%          12.75           0C
10%         25.50           19
15%         38.25           26
20%         51.00           33
25%         63.75           3F
30%         76.50           4C
35%         89.25           59
40%         102.00          66
45%         114.75          72
50%         127.50          7F
55%         140.25          8C
60%         153.00          99
65%         165.75          A5
70%         178.50          B2
75%         191.25          BF
80%         204.00          CC
85%         216.75          D8
90%         229.50          E5
95%         242.25          F2
100%        255.00          FF

Why can't non-default arguments follow default arguments?

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

Setting Different Bar color in matplotlib Python

I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

there is no color parameter listed where you might be able to set the colors for your bar graph.

However, the Series.plot() docs state the following at the end of the parameter list:

kwds : keywords
Options to pass to matplotlib plotting method

What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().

If you examine the docs for the matplotlib.pyplot.bar() method here:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.

Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series(
    [5, 4, 4, 1, 12],
    index = ["AK", "AX", "GA", "SQ", "WN"]
)

#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')

#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')

#Plot the data:
my_colors = 'rgbkymc'  #red, green, blue, black, etc.

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

plt.show()

enter image description here

Note that if there are more bars than colors in your sequence, the colors will repeat.

How do I mount a remote Linux folder in Windows through SSH?

Back in 2002, Novell developed some software called NetDrive that can map a WebDAV, FTP, SFTP, etc. share to a windows drive letter. It is now abandonware, so it's no longer maintained (and not available on the Novell website), but it's free to use. I found quite a few available to download by searching for "netdrive.exe" I actually downloaded a few and compared their md5sums to make sure that I was getting a common (and hopefully safe) version.

Update 10 Nov 2017 SFTPNetDrive is the current project from the original netdrive project. And they made it free for personal use:

We Made SFTP Net Drive FREE for Personal Use

They have paid options as well on the website.

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

Center image using text-align center?

If you are using a class with an image then the following will do

class {
    display: block;
    margin: 0 auto;
}

If it is only an image in a specific class that you want to center align then following will do:

class img {
    display: block;
    margin: 0 auto;
}

VBA - If a cell in column A is not blank the column B equals

Use the function IF :

=IF ( logical_test, value_if_true, value_if_false )

How to solve privileges issues when restore PostgreSQL Database

To solve the issue you must assign the proper ownership permissions. Try the below which should resolve all permission related issues for specific users but as stated in the comments this should not be used in production:

root@server:/var/log/postgresql# sudo -u postgres psql
psql (8.4.4)
Type "help" for help.

postgres=# \du
               List of roles
    Role name    | Attributes  | Member of
-----------------+-------------+-----------
 <user-name>    | Superuser   | {}
                 : Create DB
 postgres       | Superuser   | {}
                 : Create role
                 : Create DB

postgres=# alter role <user-name> superuser;
ALTER ROLE
postgres=#

So connect to the database under a Superuser account sudo -u postgres psql and execute a ALTER ROLE <user-name> Superuser; statement.

Keep in mind this is not the best solution on multi-site hosting server so take a look at assigning individual roles instead: https://www.postgresql.org/docs/current/static/sql-set-role.html and https://www.postgresql.org/docs/current/static/sql-alterrole.html.

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

How to start and stop android service from a adb shell?

am startservice <INTENT>   

or actually from the OS shell

adb shell am startservice <INTENT>

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, use the commercial but inexpensive SSMS Tools Pack addin which has a nifty "Generate Insert statements from resultsets, tables or database" feature

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

I have had the same problem with anaconda on windows. It seems that there is an issu with mcAfee antivirus. If you deactivate it while running the updates or the installs, it allows you to properly run the installation.

Char array declaration and initialization in C

Yes, this is a kind of inconsistency in the language.

The "=" in myarray = "abc"; is assignment (which won't work as the array is basically a kind of constant pointer), whereas in char myarray[4] = "abc"; it's an initialization of the array. There's no way for "late initialization".

You should just remember this rule.

fs: how do I locate a parent folder?

this will also work:

fs.readFile(`${__dirname}/../../foo.bar`);

Detect changes in the DOM

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // fired when a mutation occurs
    console.log(mutations, observer);
    // ...
});

// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
  subtree: true,
  attributes: true
  //...
});

Complete explanations: https://stackoverflow.com/a/11546242/6569224

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

multiple plot in one figure in Python

This is very simple to do:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

You can keep adding plt.plot as many times as you like. As for line type, you need to first specify the color. So for blue, it's b. And for a normal line it's -. An example would be:

plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")

Difference between exit() and sys.exit() in Python

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

How to write a switch statement in Ruby

case...when

To add more examples to Chuck's answer:

With parameter:

case a
when 1
  puts "Single value"
when 2, 3
  puts "One of comma-separated values"
when 4..6
  puts "One of 4, 5, 6"
when 7...9
  puts "One of 7, 8, but not 9"
else
  puts "Any other thing"
end

Without parameter:

case
when b < 3
  puts "Little than 3"
when b == 3
  puts "Equal to 3"
when (1..10) === b
  puts "Something in closed range of [1..10]"
end

Please, be aware of "How to write a switch statement in Ruby" that kikito warns about.

Check if string doesn't contain another string

WHERE NOT (someColumn LIKE '%Apples%')