Programs & Examples On #Erase remove idiom

C++ Erase vector element by value rather than by position?

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

2
4
6
8
10
-----
2
4
6
10

Remove First and Last Character C++

Well, you could erase() the first character too (note that erase() modifies the string):

m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);

But in this case, a simpler way is to take a substring:

m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);

Be careful to validate that the string actually has at least two characters in it first...

Write Base64-encoded image to file

import java.util.Base64;

.... Just making it clear that this answer uses the java.util.Base64 package, without using any third-party libraries.

String crntImage=<a valid base 64 string>

byte[] data = Base64.getDecoder().decode(crntImage);

try( OutputStream stream = new FileOutputStream("d:/temp/abc.pdf") ) 
{
   stream.write(data);
}
catch (Exception e) 
{
   System.err.println("Couldn't write to file...");
}

Controlling execution order of unit tests in Visual Studio

I see that this topic is almost 6 years old, and we now have new version of Visual studio but I will reply anyway. I had that order problem in Visual Studio 19 and I figured it out by adding capital letter (you can also add small letter) in front of your method name and in alphabetical order like this:

[TestMethod]
        public void AName1()
        {}
[TestMethod]
        public void BName2()
        {}

And so on. I know that this doesn't look appealing, but it looks like Visual is sorting your tests in test explorer in alphabetical order, doesn't matter how you write it in your code. Playlist didn't work for me in this case.

Hope that this will help.

Run php function on button click

You can use isset().

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" />

</form>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}

if(isset($_POST('submit')))
{
   testfun();
}

?>

Float and double datatype in Java

The Wikipedia page on it is a good place to start.

To sum up:

  • float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).

  • double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.

By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.

There may be certain libraries that actually force your usage of float, but in general - unless you can guarantee that your result will be small enough to fit in float's prescribed range, then it's best to opt with double.

If you require accuracy - for instance, you can't have a decimal value that is inaccurate (like 1/10 + 2/10), or you're doing anything with currency (for example, representing $10.33 in the system), then use a BigDecimal, which can support an arbitrary amount of precision and handle situations like that elegantly.

Eclipse error: R cannot be resolved to a variable

I assume you have updated ADT with version 22 and R.java file is not getting generated.

If this is the case, then here is the solution:

Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.

enter image description here

How to generate gcc debug symbol outside the build target?

No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>.

  • This is provided by elfutils package.
  • The result will be that <input> file has been stripped of debug symbols which are now all in <out.debug>.

How do I install Python packages in Google's Colab?

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

How to do a deep comparison between 2 objects with lodash?

this was based on @JLavoie, using lodash

let differences = function (newObj, oldObj) {
      return _.reduce(newObj, function (result, value, key) {
        if (!_.isEqual(value, oldObj[key])) {
          if (_.isArray(value)) {
            result[key] = []
            _.forEach(value, function (innerObjFrom1, index) {
              if (_.isNil(oldObj[key][index])) {
                result[key].push(innerObjFrom1)
              } else {
                let changes = differences(innerObjFrom1, oldObj[key][index])
                if (!_.isEmpty(changes)) {
                  result[key].push(changes)
                }
              }
            })
          } else if (_.isObject(value)) {
            result[key] = differences(value, oldObj[key])
          } else {
            result[key] = value
          }
        }
        return result
      }, {})
    }

https://jsfiddle.net/EmilianoBarboza/0g0sn3b9/8/

Marquee text in Android

You can use a TextView or your custom TextView. The latter is when the textview cannot get focus all the time.

First, you can use a TextView or a custom TextView as the scrolling text view in your layout .xml file like this:

<com.example.myapplication.CustomTextView
            android:id="@+id/tvScrollingMessage"
            android:text="@string/scrolling_message_main_wish_list"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit ="marquee_forever"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:scrollHorizontally="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/black"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:freezesText="true"/>

NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.

Then in case of using CustomTextView, you should define the CustomTextView class:

public class CustomTextView extends TextView {
        public CustomTextView(Context context) {
            super(context);
        }
        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);

        }

        public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);

        }


        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            if(focused)
                super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }

        @Override
        public void onWindowFocusChanged(boolean focused) {
            if(focused)
                super.onWindowFocusChanged(focused);
        }


        @Override
        public boolean isFocused() {
            return true;
        }
    }

Hope it will be helpful to you. Cheers!

How to calculate number of days between two dates

http://momentjs.com/ or https://date-fns.org/

From Moment docs:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')   // =1

or to include the start:

a.diff(b, 'days')+1   // =2

Beats messing with timestamps and time zones manually.

Depending on your specific use case, you can either

  1. Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
  2. Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.

Separating class code into a header and cpp file

You leave the declarations in the header file:

class A2DD
{
  private:
  int gx;
  int gy;

  public:
    A2DD(int x,int y); // leave the declarations here
    int getSum();
};

And put the definitions in the implementation file.

A2DD::A2DD(int x,int y) // prefix the definitions with the class name
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

You could mix the two (leave getSum() definition in the header for instance). This is useful since it gives the compiler a better chance at inlining for example. But it also means that changing the implementation (if left in the header) could trigger a rebuild of all the other files that include the header.

Note that for templates, you need to keep it all in the headers.

Add centered text to the middle of a <hr/>-like line

Flexbox and SCSS

HTML

<div class="divider">divider</div>

SCSS

.divider {
    display: flex;
    align-items: center;
    text-align: center;
    color: #c2c2c2;

    &::before,
    &::after {
        content: "";
        flex: 1;
        border-bottom: 1px solid #c2c2c2;
    }
    &::before {
        margin-right: 0.25em;
    }
    &::after {
        margin-left: 0.25em;
    }
}

Play infinitely looping video on-load in HTML5

For iPhone it works if you add also playsinline so:

<video width="320" height="240" autoplay loop muted playsinline>
  <source src="movie.mp4" type="video/mp4" />
</video>

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

Thanks.. only one that fixed mine was the command prompt. Devenv is located under VisualStudio 12.0 Directory under common7\IDE if it helps..

image.onload event and browser cache

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

    var img = new Image();
    img.src = "img.jpg?_="+(new Date().getTime());
    img.onload = function () {
        alert("image is loaded");
    }
    

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

Convert this string to datetime

Use DateTime::createFromFormat

$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();

how to parse json using groovy

You can map JSON to specific class in Groovy using as operator:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}

Ordering by specific field value first

One way to give preference to specific rows is to add a large number to their priority. You can do this with a CASE statement:

  select id, name, priority
    from mytable
order by priority + CASE WHEN name='core' THEN 1000 ELSE 0 END desc

Demo: http://www.sqlfiddle.com/#!2/753ee/1

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

MVC4 HTTP Error 403.14 - Forbidden

In my case the issue was caused by custom ActionFilterAttribute which was a kind of global filter attribute. The attribute instantiated a service through Autofac but the service crashed in constructor:

public ActionFilterAttribute()
{
    _service = ContainerManager.Resolve<IService>();
}

public class Service: IService
{ 
    public Service()
    {
        throw new Exception('Oops!');
    }
}

How can I divide two integers stored in variables in Python?

Use this line to get the division behavior you want:

from __future__ import division

Alternatively, you could use modulus:

if (a % b) == 0: #do something

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

On Android Studio

Open the AVD Manager.

enter image description here

Click Edit Icon to edit the AVD.

enter image description here

Click Show Advanced settings.

enter image description here

Change the Internal Storage, Ram, SD Card size as necessary. Click Finish.

enter image description here

Confirm the popup by clicking yes.

enter image description here

Wipe Data on the AVD and confirm the popup by clicking yes.

enter image description here

Important: After increasing the size, if it doesn't automatically ask you to wipe data, you have to do it manually by opening the AVD's pull-down menu and choosing Wipe Data.

enter image description here

Now start and use your Emulator with increased storage.

.prop() vs .attr()

Update 1 November 2012

My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr() to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with his recommendation to prefer attr().

Original answer

If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.

I'll summarize the main issues:

  • You usually want prop() rather than attr().
  • In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work.
  • Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the size property is a number.
  • Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue / defaultChecked property).
  • This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.

If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.

As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:

<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">

So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:

  • if ( $("#cb").attr("checked") === true ) {...}
  • if ( $("#cb").attr("checked") == "checked" ) {...}
  • if ( $("#cb").is(":checked") ) {...}

This is actually the simplest thing in the world to do with the checked Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:

if (document.getElementById("cb").checked) {...}

The property also makes checking or unchecking the checkbox trivial:

document.getElementById("cb").checked = false

In jQuery 1.6, this unambiguously becomes

$("#cb").prop("checked", false)

The idea of using the checked attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.

  • It's not obvious what the correct way to check or uncheck the checkbox is using the checked attribute
  • The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See http://jsfiddle.net/VktA6/49/.

How to send email to multiple recipients using python smtplib?

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sender(recipients): 

    body = 'Your email content here'
    msg = MIMEMultipart()

    msg['Subject'] = 'Email Subject'
    msg['From'] = '[email protected]'
    msg['To'] = (', ').join(recipients.split(','))

    msg.attach(MIMEText(body,'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('[email protected]', 'yourpassword')
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    sender('[email protected],[email protected]')

It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

Calculating sum of repeated elements in AngularJS ng-repeat

Realizing this answered long ago, but wanted to post different approach not presented...

Use ng-init to tally your total. This way, you do not have to iterate in the HTML and iterate in the controller. In this scenario, I think this is a cleaner/simpler solution. (If the tallying logic was more complex, I definitely would recommend moving the logic to the controller or service as appropriate.)

    <tr>
        <th>Product</th>
        <th>Quantity</th>
        <th>Price</th>
    </tr>

    <tr ng-repeat="product in cart.products">
        <td>{{product.name}}</td>
        <td>{{product.quantity}}</td>
        <td ng-init="itemTotal = product.price * product.quantity; controller.Total = controller.Total + itemTotal">{{itemTotal}} €</td>
    </tr>

    <tr>
        <td></td>
        <td>Total :</td>
        <td>{{ controller.Total }}</td> // Here is the total value of my cart
    </tr>

Of course, in your controller, simply define/initialize your Total field:

// random controller snippet
function yourController($scope..., blah) {
    var vm = this;
    vm.Total = 0;
}

Print list without brackets in a single row

Here is a simple one.

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")

the star unpacks the list and return every element in the list.

How to Upload Image file in Retrofit 2

Retrofit 2.0 solution

@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);

and

    Map<String, RequestBody> params = new HashMap<>();

    params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));



 Call<CommonResponse> call = request.requestUpdateImage(params);

you can use
image/jpg image/png image/gif

How do I create delegates in Objective-C?

Please! check below simple step by step tutorial to understand how Delegates works in iOS.

Delegate in iOS

I have created two ViewControllers (for sending data from one to another)

  1. FirstViewController implement delegate (which provides data).
  2. SecondViewController declare the delegate (which will receive data).

Create a branch in Git from another branch

If you want create a new branch from any of the existing branches in Git, just follow the options.

First change/checkout into the branch from where you want to create a new branch. For example, if you have the following branches like:

  • master
  • dev
  • branch1

So if you want to create a new branch called "subbranch_of_b1" under the branch named "branch1" follow the steps:

  1. Checkout or change into "branch1"

    git checkout branch1
    
  2. Now create your new branch called "subbranch_of_b1" under the "branch1" using the following command.

    git checkout -b subbranch_of_b1 branch1
    

    The above will create a new branch called subbranch_of_b1 under the branch branch1 (note that branch1 in the above command isn't mandatory since the HEAD is currently pointing to it, you can precise it if you are on a different branch though).

  3. Now after working with the subbranch_of_b1 you can commit and push or merge it locally or remotely.

A sample Graphical Illustration Of Creating Branches Under another Branch

push the subbranch_of_b1 to remote

 git push origin subbranch_of_b1 

CSS/HTML: What is the correct way to make text italic?

I'd say use <em> to emphasize inline elements. Use a class for block elements like blocks of text. CSS or not, the text still has to be tagged. Whether its for semantics or for visual aid, I'm assuming you'd be using it for something meaningful...

If you're emphasizing text for ANY reason, you could use <em>, or a class that italicizes your text.

It's OK to break the rules sometimes!

switch case statement error: case expressions must be constant expression

How about this other solution to keep the nice switch instead of an if-else:

private enum LayoutElement {
    NONE(-1),
    PLAY_BUTTON(R.id.playbtn),
    STOP_BUTTON(R.id.stopbtn),
    MENU_BUTTON(R.id.btnmenu);

    private static class _ {
        static SparseArray<LayoutElement> elements = new SparseArray<LayoutElement>();
    }

    LayoutElement(int id) {
        _.elements.put(id, this);
    }

    public static LayoutElement from(View view) {
        return _.elements.get(view.getId(), NONE);
    }

}

So in your code you can do this:

public void onClick(View src) {
    switch(LayoutElement.from(src)) {
    case PLAY_BUTTTON:
        checkwificonnection();
        break;

    case STOP_BUTTON:
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
        break;

    case MENU_BUTTON:
        openOptionsMenu();
        break;
    }
}

Enums are static so this will have very limited impact. The only window for concern would be the double lookup involved (first on the internal SparseArray and later on the switch table)

That said, this enum can also be utilised to fetch the items in a fluent manner, if needed by keeping a reference to the id... but that's a story for some other time.

List of Timezone IDs for use with FindTimeZoneById() in C#?

var timeZoneInfos = TimeZoneInfo.GetSystemTimeZones();

The above gives you a list of timezones, which includes the ids.

Counting repeated characters in a string in Python

Python 2.7+ includes the collections.Counter class:

import collections
results = collections.Counter(the_string)
print(results)

How can I do a line break (line continuation) in Python?

You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \ to a line to explicitly break it:

x = (tuples_first_value,
     second_value)
y = 1 + \
    2

Pretty print in MongoDB shell as default

Since it is basically a javascript shell, you can also use toArray():

db.collection.find().toArray()

However, this will print all the documents of the collection unlike pretty() that will allow you to iterate. Refer: http://docs.mongodb.org/manual/reference/method/cursor.toArray/

How to copy a file to a remote server in Python using SCP or SSH?

You can use the vassal package, which is exactly designed for this.

All you need is to install vassal and do

from vassal.terminal import Terminal
shell = Terminal(["scp username@host:/home/foo.txt foo_local.txt"])
shell.run()

Also, it will save you authenticate credential and don't need to type them again and again.

Java Command line arguments

Use the apache commons cli if you plan on extending that past a single arg.

"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."

Commons CLI supports different types of options:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code: http://jsfiddle.net/zdam/7kLFU/

JQuery Datatables's Documentation: http://www.datatables.net/

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            // apply the plugin
            var dataTable = element.dataTable(options);



            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }
        ]; 

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true
        };


        $scope.sampleProductCategories = [

              {
                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                  "action":"x"
              }
              ,
              {
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                  "action":"x"
              }
           ,
              {
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",
                  "action":"x"
              }

        ];            

}

Set The Window Position of an application via command line

If you are happy to run a batch file along with a couple of tiny helper programs, a complete solution is posted here:
How can a batch file run a program and set the position and size of the window? - Stack Overflow (asked: May 1, 2012)

Android WebView, how to handle redirects in app instead of opening a browser

Create a WebViewClient, and override the shouldOverrideUrlLoading method.

webview.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url){
        // do your handling codes here, which url is the requested url
        // probably you need to open that url rather than redirect:
        view.loadUrl(url);
        return false; // then it is not handled by default action
   }
});

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

Display PDF file inside my android application

Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.

Also see https://github.com/loosemoose/androidpdf for a sample implementation of this.

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

Eclipse C++ : "Program "g++" not found in PATH"

In my case, I didnt mark for instalation the mingw32-gcc-g++ package in the installation manager, that's why eclipse didn't know it.

Needed to go to the instalation manager, mark it (in basic setup tab) and update catalogue

What is the difference between bottom-up and top-down?

rev4: A very eloquent comment by user Sammaron has noted that, perhaps, this answer previously confused top-down and bottom-up. While originally this answer (rev3) and other answers said that "bottom-up is memoization" ("assume the subproblems"), it may be the inverse (that is, "top-down" may be "assume the subproblems" and "bottom-up" may be "compose the subproblems"). Previously, I have read on memoization being a different kind of dynamic programming as opposed to a subtype of dynamic programming. I was quoting that viewpoint despite not subscribing to it. I have rewritten this answer to be agnostic of the terminology until proper references can be found in the literature. I have also converted this answer to a community wiki. Please prefer academic sources. List of references: {Web: 1,2} {Literature: 5}

Recap

Dynamic programming is all about ordering your computations in a way that avoids recalculating duplicate work. You have a main problem (the root of your tree of subproblems), and subproblems (subtrees). The subproblems typically repeat and overlap.

For example, consider your favorite example of Fibonnaci. This is the full tree of subproblems, if we did a naive recursive call:

TOP of the tree
fib(4)
 fib(3)...................... + fib(2)
  fib(2)......... + fib(1)       fib(1)........... + fib(0)
   fib(1) + fib(0)   fib(1)       fib(1)              fib(0)
    fib(1)   fib(0)
BOTTOM of the tree

(In some other rare problems, this tree could be infinite in some branches, representing non-termination, and thus the bottom of the tree may be infinitely large. Furthermore, in some problems you might not know what the full tree looks like ahead of time. Thus, you might need a strategy/algorithm to decide which subproblems to reveal.)


Memoization, Tabulation

There are at least two main techniques of dynamic programming which are not mutually exclusive:

  • Memoization - This is a laissez-faire approach: You assume that you have already computed all subproblems and that you have no idea what the optimal evaluation order is. Typically, you would perform a recursive call (or some iterative equivalent) from the root, and either hope you will get close to the optimal evaluation order, or obtain a proof that you will help you arrive at the optimal evaluation order. You would ensure that the recursive call never recomputes a subproblem because you cache the results, and thus duplicate sub-trees are not recomputed.

    • example: If you are calculating the Fibonacci sequence fib(100), you would just call this, and it would call fib(100)=fib(99)+fib(98), which would call fib(99)=fib(98)+fib(97), ...etc..., which would call fib(2)=fib(1)+fib(0)=1+0=1. Then it would finally resolve fib(3)=fib(2)+fib(1), but it doesn't need to recalculate fib(2), because we cached it.
    • This starts at the top of the tree and evaluates the subproblems from the leaves/subtrees back up towards the root.
  • Tabulation - You can also think of dynamic programming as a "table-filling" algorithm (though usually multidimensional, this 'table' may have non-Euclidean geometry in very rare cases*). This is like memoization but more active, and involves one additional step: You must pick, ahead of time, the exact order in which you will do your computations. This should not imply that the order must be static, but that you have much more flexibility than memoization.

    • example: If you are performing fibonacci, you might choose to calculate the numbers in this order: fib(2),fib(3),fib(4)... caching every value so you can compute the next ones more easily. You can also think of it as filling up a table (another form of caching).
    • I personally do not hear the word 'tabulation' a lot, but it's a very decent term. Some people consider this "dynamic programming".
    • Before running the algorithm, the programmer considers the whole tree, then writes an algorithm to evaluate the subproblems in a particular order towards the root, generally filling in a table.
    • *footnote: Sometimes the 'table' is not a rectangular table with grid-like connectivity, per se. Rather, it may have a more complicated structure, such as a tree, or a structure specific to the problem domain (e.g. cities within flying distance on a map), or even a trellis diagram, which, while grid-like, does not have a up-down-left-right connectivity structure, etc. For example, user3290797 linked a dynamic programming example of finding the maximum independent set in a tree, which corresponds to filling in the blanks in a tree.

(At it's most general, in a "dynamic programming" paradigm, I would say the programmer considers the whole tree, then writes an algorithm that implements a strategy for evaluating subproblems which can optimize whatever properties you want (usually a combination of time-complexity and space-complexity). Your strategy must start somewhere, with some particular subproblem, and perhaps may adapt itself based on the results of those evaluations. In the general sense of "dynamic programming", you might try to cache these subproblems, and more generally, try avoid revisiting subproblems with a subtle distinction perhaps being the case of graphs in various data structures. Very often, these data structures are at their core like arrays or tables. Solutions to subproblems can be thrown away if we don't need them anymore.)

[Previously, this answer made a statement about the top-down vs bottom-up terminology; there are clearly two main approaches called Memoization and Tabulation that may be in bijection with those terms (though not entirely). The general term most people use is still "Dynamic Programming" and some people say "Memoization" to refer to that particular subtype of "Dynamic Programming." This answer declines to say which is top-down and bottom-up until the community can find proper references in academic papers. Ultimately, it is important to understand the distinction rather than the terminology.]


Pros and cons

Ease of coding

Memoization is very easy to code (you can generally* write a "memoizer" annotation or wrapper function that automatically does it for you), and should be your first line of approach. The downside of tabulation is that you have to come up with an ordering.

*(this is actually only easy if you are writing the function yourself, and/or coding in an impure/non-functional programming language... for example if someone already wrote a precompiled fib function, it necessarily makes recursive calls to itself, and you can't magically memoize the function without ensuring those recursive calls call your new memoized function (and not the original unmemoized function))

Recursiveness

Note that both top-down and bottom-up can be implemented with recursion or iterative table-filling, though it may not be natural.

Practical concerns

With memoization, if the tree is very deep (e.g. fib(10^6)), you will run out of stack space, because each delayed computation must be put on the stack, and you will have 10^6 of them.

Optimality

Either approach may not be time-optimal if the order you happen (or try to) visit subproblems is not optimal, specifically if there is more than one way to calculate a subproblem (normally caching would resolve this, but it's theoretically possible that caching might not in some exotic cases). Memoization will usually add on your time-complexity to your space-complexity (e.g. with tabulation you have more liberty to throw away calculations, like using tabulation with Fib lets you use O(1) space, but memoization with Fib uses O(N) stack space).

Advanced optimizations

If you are also doing a extremely complicated problems, you might have no choice but to do tabulation (or at least take a more active role in steering the memoization where you want it to go). Also if you are in a situation where optimization is absolutely critical and you must optimize, tabulation will allow you to do optimizations which memoization would not otherwise let you do in a sane way. In my humble opinion, in normal software engineering, neither of these two cases ever come up, so I would just use memoization ("a function which caches its answers") unless something (such as stack space) makes tabulation necessary... though technically to avoid a stack blowout you can 1) increase the stack size limit in languages which allow it, or 2) eat a constant factor of extra work to virtualize your stack (ick), or 3) program in continuation-passing style, which in effect also virtualizes your stack (not sure the complexity of this, but basically you will effectively take the deferred call chain from the stack of size N and de-facto stick it in N successively nested thunk functions... though in some languages without tail-call optimization you may have to trampoline things to avoid a stack blowout).


More complicated examples

Here we list examples of particular interest, that are not just general DP problems, but interestingly distinguish memoization and tabulation. For example, one formulation might be much easier than the other, or there may be an optimization which basically requires tabulation:

  • the algorithm to calculate edit-distance[4], interesting as a non-trivial example of a two-dimensional table-filling algorithm

Oracle Error ORA-06512

I also had the same error. In my case reason was I have created a update trigger on a table and under that trigger I am again updating the same table. And when I have removed the update statement from the trigger my problem has been resolved.

How do I get a YouTube video thumbnail from the YouTube API?

Save file as .js

_x000D_
_x000D_
  var maxVideos = 5;_x000D_
  $(document).ready(function(){_x000D_
  $.get(_x000D_
    "https://www.googleapis.com/youtube/v3/videos",{_x000D_
      part: 'snippet,contentDetails',_x000D_
      id:'your_video_id',_x000D_
      kind: 'youtube#videoListResponse',_x000D_
      maxResults: maxVideos,_x000D_
      regionCode: 'IN',_x000D_
      key: 'Your_API_KEY'},_x000D_
      function(data){_x000D_
        var output;_x000D_
        $.each(data.items, function(i, item){_x000D_
          console.log(item);_x000D_
                thumb = item.snippet.thumbnails.high.url;_x000D_
          output = '<div id="img"><img src="' + thumb + '"></div>';_x000D_
          $('#thumbnail').append(output);_x000D_
        })_x000D_
        _x000D_
      }_x000D_
    );_x000D_
}); 
_x000D_
.main{_x000D_
 width:1000px;_x000D_
 margin:auto;_x000D_
}_x000D_
#img{_x000D_
float:left;_x000D_
display:inline-block;_x000D_
margin:5px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <title>Thumbnails</title>_x000D_
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div class="main">_x000D_
 <ul id="thumbnail"> </ul>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to list the files inside a JAR file?

One more for the road that's a bit more flexible for matching specific filenames because it uses wildcard globbing. In a functional style this could resemble:

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;

import static java.nio.file.FileSystems.getDefault;
import static java.nio.file.FileSystems.newFileSystem;
import static java.util.Collections.emptyMap;

/**
 * Responsible for finding file resources.
 */
public class ResourceWalker {
  /**
   * Globbing pattern to match font names.
   */
  public static final String GLOB_FONTS = "**.{ttf,otf}";

  /**
   * @param directory The root directory to scan for files matching the glob.
   * @param c         The consumer function to call for each matching path
   *                  found.
   * @throws URISyntaxException Could not convert the resource to a URI.
   * @throws IOException        Could not walk the tree.
   */
  public static void walk(
    final String directory, final String glob, final Consumer<Path> c )
    throws URISyntaxException, IOException {
    final var resource = ResourceWalker.class.getResource( directory );
    final var matcher = getDefault().getPathMatcher( "glob:" + glob );

    if( resource != null ) {
      final var uri = resource.toURI();
      final Path path;
      FileSystem fs = null;

      if( "jar".equals( uri.getScheme() ) ) {
        fs = newFileSystem( uri, emptyMap() );
        path = fs.getPath( directory );
      }
      else {
        path = Paths.get( uri );
      }

      try( final var walk = Files.walk( path, 10 ) ) {
        for( final var it = walk.iterator(); it.hasNext(); ) {
          final Path p = it.next();
          if( matcher.matches( p ) ) {
            c.accept( p );
          }
        }
      } finally {
        if( fs != null ) { fs.close(); }
      }
    }
  }
}

Consider parameterizing the file extensions, left an exercise for the reader.

Be careful with Files.walk. According to the documentation:

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

Likewise, newFileSystem must be closed, but not before the walker has had a chance to visit the file system paths.

How to import a SQL Server .bak file into MySQL?

In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL.

Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want.

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

iOS Simulator > Menu Bar > Debug > Open System Log


Old ways:

iOS Simulator prints its logs directly to stdout, so you can see the logs mixed up with system logs.

Open the Terminal and type: tail -f /var/log/system.log

Then run the simulator.

EDIT:

This stopped working on Mavericks/Xcode 5. Now you can access the simulator logs in its own folder: ~/Library/Logs/iOS Simulator/<sim-version>/system.log

You can either use the Console.app to see this, or just do a tail (iOS 7.0.3 64 bits for example):

tail -f ~/Library/Logs/iOS\ Simulator/7.0.3-64/system.log

EDIT 2:

They are now located in ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log

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

How to name variables on the fly?

Don't make data frames. Keep the list, name its elements but do not attach it.

The biggest reason for this is that if you make variables on the go, almost always you will later on have to iterate through each one of them to perform something useful. There you will again be forced to iterate through each one of the names that you have created on the fly.

It is far easier to name the elements of the list and iterate through the names.

As far as attach is concerned, its really bad programming practice in R and can lead to a lot of trouble if you are not careful.

Rounding SQL DateTime to midnight

SELECT getdate()

Result: 2012-12-14 16:03:33.360

SELECT convert(datetime,convert(bigint, getdate()))

Result 2012-12-15 00:00:00.000

How to debug a GLSL shader?

GLSL Sandbox has been pretty handy to me for shaders.

Not debugging per se (which has been answered as incapable) but handy to see the changes in output quickly.

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

What is the difference between char * const and const char *?

Rule of thumb: read the definition from right to left!


const int *foo;

Means "foo points (*) to an int that cannot change (const)".
To the programmer this means "I will not change the value of what foo points to".

  • *foo = 123; or foo[0] = 123; would be invalid.
  • foo = &bar; is allowed.

int *const foo;

Means "foo cannot change (const) and points (*) to an int".
To the programmer this means "I will not change the memory address that foo refers to".

  • *foo = 123; or foo[0] = 123; is allowed.
  • foo = &bar; would be invalid.

const int *const foo;

Means "foo cannot change (const) and points (*) to an int that cannot change (const)".
To the programmer this means "I will not change the value of what foo points to, nor will I change the address that foo refers to".

  • *foo = 123; or foo[0] = 123; would be invalid.
  • foo = &bar; would be invalid.

How to display text in pygame?

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

How can I set an SQL Server connection string?

They are a number of things to worry about when connecting to SQL Server on another machine.

  • Host/IP address of the machine
  • Initial catalog (database name)
  • Valid username/password

Very often SQL Server may be running as a default instance which means you can simply specify the hostname/IP address, but you may encounter a scenario where it is running as a named instance (SQL Server Express Edition for instance). In this scenario you'll have to specify the hostname/instance name.

Generate an integer sequence in MySQL

I found this solution on the web

SET @row := 0;
SELECT @row := @row + 1 as row, t.*
FROM some_table t, (SELECT @row := 0) r

Single query, fast, and does exactly what I wanted: now I can "number" the "selections" found from a complex query with unique numbers starting at 1 and incrementing once for each row in the result.

I think this will also work for the issue listed above: adjust the initial starting value for @row and add a limit clause to set the maximum.

BTW: I think that the "r" is not really needed.

ddsp

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You should only need to unbind the service in onDestroy(). Then, The warning will go.

See here.

As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().

iPhone - Get Position of UIView within entire UIWindow

Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift

extension UIView {
    var globalFrame: CGRect? {
        let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
        return self.superview?.convert(self.frame, to: rootView)
    }
}

What is the difference between map and flatMap and a good use case for each?

Flatmap and Map both transforms the collection.

Difference:

map(func)
Return a new distributed dataset formed by passing each element of the source through a function func.

flatMap(func)
Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

The transformation function:
map: One element in -> one element out.
flatMap: One element in -> 0 or more elements out (a collection).

TypeScript and field initializers

I suggest an approach that does not require Typescript 2.1:

class Person {
    public name: string;
    public address?: string;
    public age: number;

    public constructor(init:Person) {
        Object.assign(this, init);
    }

    public someFunc() {
        // todo
    }
}

let person = new Person(<Person>{ age:20, name:"John" });
person.someFunc();

key points:

  • Typescript 2.1 not required, Partial<T> not required
  • It supports functions (in comparison with simple type assertion which does not support functions)

VB.NET Empty String Array

A little verbose, but self documenting...

Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray

Import regular CSS file in SCSS file?

You can use a third-party importer to customise @import semantics.

node-sass-import-once, which works with node-sass (for Node.js) can inline import CSS files.

Example of direct usage:

var sass = require('node-sass');,
    importOnce = require('node-sass-import-once');

sass.render({
  file: "input.scss",
  importer: importOnce,
  importOnce: {
    css: true,
  }
});

Example grunt-sass config:

var importOnce = require("node-sass-import-once");
grunt.loadNpmTasks("grunt-sass");

grunt.initConfig({
  sass: {
    options: {
      sourceMap: true,
      importer: importOnce
    },
    dev: {
      files: {
        "dist/style.css": "scss/**/*.scss"
      }
    }
  });

Note that node-sass-import-once cannot currently import Sass partials without an explicit leading underscore. For example with the file partials/_partial.scss:

  • @import partials/_partial.scss succeeds
  • @import * partials/partial.scss fails

In general, be aware that a custom importer could change any import semantics. Read the docs before you start using it.

Python function to convert seconds into minutes, hours, and days

Patching Mr.B's answer (sorry, not enough rep. to comment), we can return variable granularity based on the amount of time. For example, we don't say "1 week, 5 seconds", we just say "1 week":

def display_time(seconds, granularity=2):
    result = []

    for name, count in intervals:
        value = seconds // count
        if value:
            seconds -= value * count
            if value == 1:
                name = name.rstrip('s')
            result.append("{} {}".format(value, name))
        else:
            # Add a blank if we're in the middle of other values
            if len(result) > 0:
                result.append(None)
    return ', '.join([x for x in result[:granularity] if x is not None])

Some sample input:

for diff in [5, 67, 3600, 3605, 3667, 24*60*60, 24*60*60+5, 24*60*60+57, 24*60*60+3600, 24*60*60+3667, 2*24*60*60, 2*24*60*60+5*60*60, 7*24*60*60, 7*24*60*60 + 24*60*60]:
    print "For %d seconds: %s" % (diff, display_time(diff, 2))

...returns this output:

For 5 seconds: 5 seconds
For 67 seconds: 1 minute, 7 seconds
For 3600 seconds: 1 hour
For 3605 seconds: 1 hour
For 3667 seconds: 1 hour, 1 minute
For 86400 seconds: 1 day
For 86405 seconds: 1 day
For 86457 seconds: 1 day
For 90000 seconds: 1 day, 1 hour
For 90067 seconds: 1 day, 1 hour
For 172800 seconds: 2 days
For 190800 seconds: 2 days, 5 hours
For 604800 seconds: 1 week
For 691200 seconds: 1 week, 1 day

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

Twitter Bootstrap - add top space between rows

I added these classes to my bootstrap stylesheet

.voffset  { margin-top: 2px; }
.voffset1 { margin-top: 5px; }
.voffset2 { margin-top: 10px; }
.voffset3 { margin-top: 15px; }
.voffset4 { margin-top: 30px; }
.voffset5 { margin-top: 40px; }
.voffset6 { margin-top: 60px; }
.voffset7 { margin-top: 80px; }
.voffset8 { margin-top: 100px; }
.voffset9 { margin-top: 150px; }

Example

<div class="container">
  <div class="row voffset2">
    <div class="col-lg-12">
      <p>
        Vertically offset text.
      </p>
    </div>
  </div>
</div>

Set custom HTML5 required field validation message

Code snippet

Since this answer got very much attention, here is a nice configurable snippet I came up with:

/**
  * @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
  * @link https://stackoverflow.com/a/16069817/603003
  * @license MIT 2013-2015 ComFreek
  * @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
  * You MUST retain this license header!
  */
(function (exports) {
    function valOrFunction(val, ctx, args) {
        if (typeof val == "function") {
            return val.apply(ctx, args);
        } else {
            return val;
        }
    }

    function InvalidInputHelper(input, options) {
        input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));

        function changeOrInput() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
                input.setCustomValidity("");
            }
        }

        function invalid() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
               input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
            }
        }

        input.addEventListener("change", changeOrInput);
        input.addEventListener("input", changeOrInput);
        input.addEventListener("invalid", invalid);
    }
    exports.InvalidInputHelper = InvalidInputHelper;
})(window);

Usage

jsFiddle

<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
  defaultText: "Please enter an email address!",

  emptyText: "Please enter an email address!",

  invalidText: function (input) {
    return 'The email address "' + input.value + '" is invalid!';
  }
});

More details

  • defaultText is displayed initially
  • emptyText is displayed when the input is empty (was cleared)
  • invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)

You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.

Compatibility

Tested in:

  • Chrome Canary 47.0.2
  • IE 11
  • Microsoft Edge (using the up-to-date version as of 28/08/2015)
  • Firefox 40.0.3
  • Opera 31.0

Old answer

You can see the old revision here: https://stackoverflow.com/revisions/16069817/6

How to set the height of an input (text) field in CSS?

You use this style code

.heighttext{
 float:right;
 height:30px;
 width:70px;
 }

What are the First and Second Level caches in (N)Hibernate?

by default, NHibernate uses first level caching which is Session Object based. but if you are running in a multi-server environment, then the first level cache may not very scalable along with some performance issues. it is happens because of the fact that it has to make very frequent trips to the database as the data is distributed over multiple servers. in other words NHibernate provides a basic, not-so-sophisticated in-process L1 cache out of box. However, it doesn’t provide features that a caching solution must have to have a notable impact on the application performance.

so the questions of all these problem is the use of a L2 cache which is associated with the session factory objects. it reduces the time consuming trips to the database so ultimately increases the app response time.

What does <T> denote in C#

It is a generic type parameter, see Generics documentation.

T is not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).

T GetDefault<T>()
{
    return default(T);
}

Note that the return type is T. With this method you can get the default value of any type by calling the method as:

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET uses generics in collections, ... example:

List<int> integerList = new List<int>();

This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:

public class List<T> : ...
{
    public void Add(T item);
}

Some more information about generics.

You can limit the scope of the type T.

The following example only allows you to invoke the method with types that are classes:

void Foo<T>(T item) where T: class
{
}

The following example only allows you to invoke the method with types that are Circle or inherit from it.

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.

Jupyter notebook not running code. Stuck on In [*]

updating ipykernel did it for me. it seems arch linux's ipykernel package had been outdated for some time

just do pip install --upgrade ipykernel

reference here: github solution

Maximum length of the textual representation of an IPv6 address?

45 characters.

You might expect an address to be

0000:0000:0000:0000:0000:0000:0000:0000

8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.

But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:192.168.100.228]. Written out fully:

0000:0000:0000:0000:0000:ffff:192.168.100.228

(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

error: ORA-65096: invalid common user or role name in oracle

99.9% of the time the error ORA-65096: invalid common user or role name means you are logged into the CDB when you should be logged into a PDB.

But if you insist on creating users the wrong way, follow the steps below.

DANGER

Setting undocumented parameters like this (as indicated by the leading underscore) should only be done under the direction of Oracle Support. Changing such parameters without such guidance may invalidate your support contract. So do this at your own risk.

Specifically, if you set "_ORACLE_SCRIPT"=true, some data dictionary changes will be made with the column ORACLE_MAINTAINED set to 'Y'. Those users and objects will be incorrectly excluded from some DBA scripts. And they may be incorrectly included in some system scripts.

If you are OK with the above risks, and don't want to create common users the correct way, use the below answer.


Before creating the user run:

alter session set "_ORACLE_SCRIPT"=true;  

I found the answer here

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

How to create a function in a cshtml template?

If you want to access your page's global variables, you can do so:

@{
    ViewData["Title"] = "Home Page";

    var LoadingButtons = Model.ToDictionary(person => person, person => false);

    string GetLoadingState (string person) => LoadingButtons[person] ? "is-loading" : string.Empty;
}

jquery - disable click

Use off() method after click event is triggered to disable element for the further click.

$('#clickElement').off('click');

Get the client's IP address in socket.io

for 1.0.4:

io.sockets.on('connection', function (socket) {
  var socketId = socket.id;
  var clientIp = socket.request.connection.remoteAddress;

  console.log(clientIp);
});

Scanner method to get a char

sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time

example: sc.next().charat(2)------------>>>>>>>>

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

How to combine class and ID in CSS selector?

use: tag.id ; tag#classin the tag variables in your css.

Bind service to activity in Android

I tried to call

startService(oIntent);
bindService(oIntent, mConnection, Context.BIND_AUTO_CREATE);

consequently and I could create a sticky service and bind to it. Detailed tutorial for Bound Service Example.

In a bootstrap responsive page how to center a div

Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
</head>_x000D_
<body>_x000D_
    <div class="d-flex justify-content-center align-items-center bg-secondary w-100" style="height: 300px;">_x000D_
        <div class="bg-primary" style="width: 200px; height: 50px;"></div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

logger configuration to log to file and print to stdout

Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.

Here's a quick example reusing the assumed values and LOGFILE from the question:

import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys

log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)

fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)

targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value

' Close customer workbook
customerWorkbook.Close

Why write <script type="text/javascript"> when the mime type is set by the server?

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

He also says:

W3C did not adopt the language attribute, favoring instead a type attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes "text/javascript" or "application/ecmascript" or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write <script>. It is smallest, and it works on the most browsers.

For entertainment purposes only, I tried out the following five scripts

  <script type="application/ecmascript">alert("1");</script>
  <script type="text/javascript">alert("2");</script>
  <script type="baloney">alert("3");</script>
  <script type="">alert("4");</script>
  <script >alert("5");</script>

On Chrome, all but script 3 (type="baloney") worked. IE8 did not run script 1 (type="application/ecmascript") or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type attribute, but that it you use it you better use a legal (browser dependent) value.

Accessing the web page's HTTP Headers in JavaScript

As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.

In Express, for example, the following works:

app.get('/somepage', (req, res) => { res.render('somepage.hbs', {headers: req.headers}); }) The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

Define: What is a HashSet?

A HashSet has an internal structure (hash), where items can be searched and identified quickly. The downside is that iterating through a HashSet (or getting an item by index) is rather slow.

So why would someone want be able to know if an entry already exists in a set?

One situation where a HashSet is useful is in getting distinct values from a list where duplicates may exist. Once an item is added to the HashSet it is quick to determine if the item exists (Contains operator).

Other advantages of the HashSet are the Set operations: IntersectWith, IsSubsetOf, IsSupersetOf, Overlaps, SymmetricExceptWith, UnionWith.

If you are familiar with the object constraint language then you will identify these set operations. You will also see that it is one step closer to an implementation of executable UML.

Android open pdf file

The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);

And for function:

getUriFromFile(localFile)

private Uri getUriFromFile(File file){
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        return Uri.fromFile(file);
    }else {
        return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
    }
}

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

There is no tracking information for the current branch

This happens due to current branch has no tracking on the branch on the remote. so you can do it with 2 ways.

  1. Pull with specific branch name

git pull origin master

  1. Or you can specific branch to track to the local branch.

git branch --set-upstream-to=origin/

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Git stash pop- needs merge, unable to refresh index

I have found that the best solution is to branch off your stash and do a resolution afterwards.

git stash branch <branch-name>

if you drop of clear your stash, you may lose your changes and you will have to recur to the reflog.

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

How do I create a URL shortener?

My Python 3 version

base_list = list("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
base = len(base_list)

def encode(num: int):
    result = []
    if num == 0:
        result.append(base_list[0])

    while num > 0:
        result.append(base_list[num % base])
        num //= base

    print("".join(reversed(result)))

def decode(code: str):
    num = 0
    code_list = list(code)
    for index, code in enumerate(reversed(code_list)):
        num += base_list.index(code) * base ** index
    print(num)

if __name__ == '__main__':
    encode(341413134141)
    decode("60FoItT")

Is there a way to call a stored procedure with Dapper?

Here is code for getting value return from Store procedure

Stored procedure:

alter proc [dbo].[UserlogincheckMVC]    
@username nvarchar(max),    
@password nvarchar(max)
as    
begin    
    if exists(select Username from Adminlogin where Username =@username and Password=@password)    
        begin        
            return 1  
        end    
    else    
        begin     
            return 0  
        end    
end 

Code:

var parameters = new DynamicParameters();
string pass = EncrytDecry.Encrypt(objUL.Password);
conx.Open();
parameters.Add("@username", objUL.Username);
parameters.Add("@password", pass);
parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure);
int result = parameters.Get<int>("@RESULT");

How to add AUTO_INCREMENT to an existing column?

I had existing data in the first column and they were 0's. First I made the first column nullable. Then I set the data for the column to null. Then I set the column as an index. Then I made it a primary key with auto incrementing turned on. This is where I used another persons answer above:

ALTER TABLE `table_name` CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;

This Added numbers to all the rows of this table starting at one. If I ran the above code first it wasn't working because all the values were 0's. And making it an index was also required before making it auto incrementing. Next I made the column a primary key.

Java Enum Methods - return opposite direction enum

Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.

It doesn't read nicely though; perhaps a switch would be more manageable?

public enum Direction {
    NORTH(1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.SOUTH;
        }
    },
    SOUTH(-1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.NORTH;
        }
    },
    EAST(-2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.WEST;
        }
    },
    WEST(2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.EAST;
        }
    };

    Direction(int code){
        this.code=code;
    }
    protected int code;

    public int getCode() {
        return this.code;
    }

    public abstract Direction getOppositeDirection();
}

Android Horizontal RecyclerView scroll Direction

In Recycler Layout manager the second parameter is spanCount increase or decrease in span count will change number of elements show on your screen

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2, //The number of Columns in the grid
,GridLayoutManager.HORIZONTAL,false);
                recyclerView.setLayoutManager(mLayoutManager);

jQuery .scrollTop(); + animation

Try this instead:

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}

PHP sessions that have already been started

Yes, you can detect if the session is already running by checking isset($_SESSION). However the best answer is simply not to call session_start() more than once.

It should be called very early in your script, possibly even the first line, and then not called again.

If you have it in more than one place in your code then you're asking to get this kind of bug. Cut it down so it's only in one place and can only be called once.

How to use moment.js library in angular 2 typescript app?

Not sure if this is still an issue for people, however... Using SystemJS and MomentJS as library, this solved it for me

/*
 * Import Custom Components
 */
import * as moment from 'moment/moment'; // please use path to moment.js file, extension is set in system.config

// under systemjs, moment is actually exported as the default export, so we account for that
const momentConstructor: (value?: any) => moment.Moment = (<any>moment).default || moment;

Works fine from there for me.

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

  • When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.

  • By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs:

To fix this issue add following lines After Return and Before Begin statement:

READS SQL DATA
DETERMINISTIC

For Example :

CREATE FUNCTION f2()
RETURNS CHAR(36) CHARACTER SET utf8
/*ADD HERE */
READS SQL DATA
DETERMINISTIC
BEGIN

For more detail about this issue please read Here

How to pass a variable from Activity to Fragment, and pass it back?

To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.

On the newInstance function of your fragment you add the arguments you wanna send to it:

/**
 * Create a new instance of DetailsFragment, initialized to
 * show the text at 'index'.
 */
public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}

Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this:

Bundle args = getArguments();
int index = args.getInt("index", 0);

If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.

Documentation tutorial:

http://developer.android.com/training/basics/fragments/communicating.html

Invisible characters - ASCII

There is actually a truly invisible character: U+FEFF. This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM for short is an invisible character that doesn't take up any space. You can copy the character bellow between the > and <.

Here is the character:

> <

How to catch this character in action:

  • Copy the character between the > and <,
  • Write a line of text, then randomly put your caret in the line of text
  • Paste the character in the line.
  • Go to the beginning of the line and press and hold the right arrow key.

You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!

EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php

Select a random sample of results from a query result

I know this has already been answered, but seeing so many visits here I'd like to add one version that uses the SAMPLE clause but still allows to filter the rows first:

with cte1 as (
    select *
    from t_your_table
    where your_column = 'ABC'
)
select * from cte1 sample (5)

Note however that the base select needs a ROWID column, which means it may not work for some views for example.

WPF loading spinner

use an enum type to indicate your ViewModel's State

public enum ViewModeType
{
    Default, 
    Busy
    //etc.
}

then in your ViewModels Base class use a property

public ViewModeType ViewMode
{
    get { return this.viewMode; }
    set
    {
        if (this.viewMode != value)
        {
            this.viewMode = value;
                            //You should notify property changed here
        }
    }
}

and in view trigger the ViewMode and if it is busy show busyindicator:

<Trigger Property="ViewMode" Value="Busy">
    <!-- Show BusyIndicator -->
</Trigger>

How do I do multiple CASE WHEN conditions using SQL Server 2008?

case 
    when a.REASONID in ('02','03','04','05','06') then
        case b.CALSOC 
            when '1' then 'yes' 
            when '2' then 'no' 
            else 'no' 
        end
    else 'no' 
end 

Get Row Index on Asp.net Rowcommand event

ImageButton \ Button etc.

CommandArgument='<%# Container.DataItemIndex%>' 

code-behind

protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = e.CommandArgument;
}

Getting activity from context in android

Context may be an Application, a Service, an Activity, and more.

Normally the context of Views in an Activity is the Activity itself so you may think you can just cast this Context to Activity but actually you can't always do it, because the context can also be a ContextThemeWrapper in this case.

ContextThemeWrapper is used heavily in the recent versions of AppCompat and Android (thanks to the android:theme attribute in layouts) so I would personally never perform this cast.

So short answer is: you can't reliably retrieve an Activity from a Context in a View. Pass the Activity to the view by calling a method on it which takes the Activity as parameter.

Import XXX cannot be resolved for Java SE standard classes

If the project is Maven, you can try this way :

  1. right click the "Maven Dependencies"-->"Build Path"-->"Remove from the build path";
  2. right click the project ,navigate to "Maven"--->"Update project....";

Then the import issue should be solved .

Fast query runs slow in SSRS

I Faced the same issue. For me it was just to unckeck the option :

Tablix Properties=> Page Break Option => Keep together on one page if possible

Of SSRS Report. It was trying to put all records on the same page instead of creating many pages.

SQL JOIN vs IN performance?

Each database's implementation but you can probably guess that they all solve common problems in more or less the same way. If you are using MSSQL have a look at the execution plan that is generated. You can do this by turning on the profiler and executions plans. This will give you a text version when you run the command.

I am not sure what version of MSSQL you are using but you can get a graphical one in SQL Server 2000 in the query analyzer. I am sure that this functionality is lurking some where in SQL Server Studio Manager in later versions.

Have a look at the exeuction plan. As far as possible avoid table scans unless of course your table is small in which case a table scan is faster than using an index. Read up on the different join operations that each different scenario produces.

Gradle failed to resolve library in Android Studio

I had the same problem, the first thing that came to mind was repositories. So I checked the build.gradle file for the whole project and added the following code, then synchronized the gradle with project and problem was solved!

allprojects {
    repositories {
        jcenter()
    }
}

Eclipse change project files location

You can copy your .classpath and .project files to the root of the new project directory and then choose 'Import...' from the file menu, and select 'General/Existing Projects into Workspace.' In the resulting dialog, locate the root of the new project directory and finish. Make sure that you have deleted the old project from the work space before importing.

Rotate label text in seaborn factorplot

I had a problem with the answer by @mwaskorn, namely that

g.set_xticklabels(rotation=30)

fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add

plt.xticks(rotation=45)

Render HTML string as real HTML in a React component

If you have HTML in a string, I would recommend using a package called html-react-parser.

Install it: npm install html-react-parser or if you use yarn, yarn add html-react-parser

Use it something like this

import parse from 'html-react-parser'
const yourHtmlString = '<h1>Hello</h1>'
<div>
    {parse(yourHtmlString)}
</div>

Reference: https://www.npmjs.com/package/html-react-parser

How to select where ID in Array Rails ActiveRecord without exception

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

will work even if some of the ids don't exist. This works in the

user.comments.find_all_by_id(potentially_nonexistent_ids)

case as well.

Update: Rails 4

Comment.where(id: [2, 3, 5])

python pandas convert index to datetime

It should work as expected. Try to run the following example.

import pandas as pd
import io

data = """value          
"2015-09-25 00:46"    71.925000
"2015-09-25 00:47"    71.625000
"2015-09-25 00:48"    71.333333
"2015-09-25 00:49"    64.571429
"2015-09-25 00:50"    72.285714"""

df = pd.read_table(io.StringIO(data), delim_whitespace=True)

# Converting the index as date
df.index = pd.to_datetime(df.index)

# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df

#                          value  A   B
# 2015-09-25 00:46:00  71.925000  0  46
# 2015-09-25 00:47:00  71.625000  0  47
# 2015-09-25 00:48:00  71.333333  0  48
# 2015-09-25 00:49:00  64.571429  0  49
# 2015-09-25 00:50:00  72.285714  0  50

Difference between Spring MVC and Spring Boot

Spring MVC is a sub-project of the Spring Framework, targeting design and development of applications that use the MVC (Model-View-Controller) pattern. Spring MVC is designed to integrate fully and completely with the Spring Framework and transitively, most other sub-projects.

Spring Boot can be understood quite well from this article by the Spring Engineering team. It is supposedly opinionated, i.e. it heavily advocates a certain style of rapid development, but it is designed well enough to accommodate exceptions to the rule, if you will. In short, it is a convention over configuration methodology that is willing to understand your need to break convention when warranted.

Can't include C++ headers like vector in Android NDK

I'm using Android Studio and as of 19th of January 2016 this did the trick for me. (This seems like something that changes every year or so)

Go to: app -> Gradle Scripts -> build.gradle (Module: app)

Then under model { ... android.ndk { ... and add a line: stl = "gnustl_shared"

Like this:

model {

    ...

    android.ndk {
        moduleName = "gl2jni"
        cppFlags.add("-Werror")
        ldLibs.addAll(["log", "GLESv2"])
        stl = "gnustl_shared"     //  <-- this is the line that I added
    }

    ...

}

Convert a Python int into a big-endian string of bytes

The shortest way, I think, is the following:

import struct
val = 0x11223344
val = struct.unpack("<I", struct.pack(">I", val))[0]
print "%08x" % val

This converts an integer to a byte-swapped integer.

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

SELECT * FROM (
    SELECT * FROM Table1 WHERE Field1 = Value1
    UNION
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

When does Java's Thread.sleep throw InterruptedException?

Methods like sleep() and wait() of class Thread might throw an InterruptedException. This will happen if some other thread wanted to interrupt the thread that is waiting or sleeping.

Get Wordpress Category from Single Post

For the lazy and the learning, to put it into your theme, Rfvgyhn's full code

<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>

What is the Windows version of cron?

Not exactly a Windows version, however you can use Cygwin's crontab. For install instructions, see here: here.

How can I introduce multiple conditions in LIKE operator?

This might help:

select * from tbl where col like '[ABC-XYZ-PQR]%'

I've used this in SQL Server 2005 and it worked.

Session state can only be used when enableSessionState is set to true either in a configuration

I realise there is an accepted answer, but this may help people. I found I had a similar problem with a ASP.NET site using NET 3.5 framework when running it in Visual Studio 2012 using IIS Express 8. I'd tried all of the above solutions and none worked - in the end running the solution in the in-built VS 2012 webserver worked. Not sure why, but I suspect it was a link between 3.5 framework and IIS 8.

How to open up a form from another form in VB.NET?

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                          Handles Button3.Click

    Dim box = New AboutBox1()
    box.Show()

End Sub

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

How can I clear event subscriptions in C#?

class c1
{
    event EventHandler someEvent;
    ResetSubscriptions() => someEvent = delegate { };
}

It is better to use delegate { } than null to avoid the null ref exception.

How to get a parent element to appear above child

Since your divs are position:absolute, they're not really nested as far as position is concerned. On your jsbin page I switched the order of the divs in the HTML to:

<div class="child"><div class="parent"></div></div>

and the red box covered the blue box, which I think is what you're looking for.

Clear screen in shell

In addition to being an all-around great CLI library, click also provides a platform-agnostic clear() function:

import click
click.clear()

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

Run react-native on android emulator

You probably haven't run the Android SDK in forever. So you probably just have to update it. If you open the Android Studio Software it'll probably let you know that and ask to update it for you. Otherwise refer to following link: Update Android SDK

Centering a canvas

Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.

Center canvas to middle of the screen or parent element. No wrapping.

HTML:

<canvas id="canvas" width="400" height="300">No canvas support</canvas>

CSS:

#canvas {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
}

Javascript:

window.onload = window.onresize = function() {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.8;
}

Works like a charm - tested: firefox, chrome

fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Ok, I figured it out. The issue was that I didn't have the correct permissions set for myrepo.git and the parent directory git.

As root I logged into the server and used:

$ chown username /home/username/git

This then returns drwxrwxr-x 4 username root 4096 2012-10-30 15:51 /home/username/git with the following:

$ ls -ld /home/username/git

I then make a new directory for myrepo.git inside git:

$ mkdir myrepo.git
$ ls -ld myrepo.git/
drwxr-xr-x 2 root root 4096 2012-10-30 18:41 myrepo.git/

but it has the user set to root, so I change it to username the same way as before.

$ chown username myrepo.git/
$ ls -ld myrepo.git/
drwxr-xr-x 2 username root 4096 2012-10-30 18:41 myrepo.git/

I then sign out of root and sign into server as username:

Inside git directory:

$ cd myrepo.git/
$ git --bare init
Initialized empty Git repository in /home/username/git/myrepo.git/

On local machine:

$ git remote add origin      
ssh://[email protected]/home/username/git/myrepo.git
$ git push origin master

SUCCESS!

Hopefully this comes in handy for anyone else that runs into the same issue in the future!

Resources

Find Java classes implementing an interface

I really like the reflections library for doing this.

It provides a lot of different types of scanners (getTypesAnnotatedWith, getSubTypesOf, etc), and it is dead simple to write or extend your own.

How to create a table from select query result in SQL Server 2008

Try using SELECT INTO....

SELECT ....
INTO     TABLE_NAME(table you want to create)
FROM source_table

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

For tracking changes to a folder where the folder was moved, I started using:

git rev-list --all --pretty=oneline -- "*/foo/subfoo/*"

This isn't perfect as it will grab other folders with the same name, but if it is unique, then it seems to work.

What are all codecs and formats supported by FFmpeg?

The formats and codecs supported by your build of ffmpeg can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.

Formats (muxers and demuxers):

List all formats:

ffmpeg -formats

Display options specific to, and information about, a particular muxer:

ffmpeg -h muxer=matroska

Display options specific to, and information about, a particular demuxer:

ffmpeg -h demuxer=gif

Codecs (encoders and decoders):

List all codecs:

ffmpeg -codecs

List all encoders:

ffmpeg -encoders

List all decoders:

ffmpeg -decoders

Display options specific to, and information about, a particular encoder:

ffmpeg -h encoder=mpeg4

Display options specific to, and information about, a particular decoder:

ffmpeg -h decoder=aac

Reading the results

There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:

$ ffmpeg -encoders
[…]
Encoders:
 V..... = Video
 A..... = Audio
 S..... = Subtitle
 .F.... = Frame-level multithreading
 ..S... = Slice-level multithreading
 ...X.. = Codec is experimental
 ....B. = Supports draw_horiz_band
 .....D = Supports direct rendering method 1
 ------
[…]
 V.S... mpeg4                MPEG-4 part 2

In this example V.S... indicates that the encoder mpeg4 is a Video encoder and supports Slice-level multithreading.

Also see

What is a codec and how does it differ from a format?

Pandas: Looking up the list of sheets in an excel file

If you:

  • care about performance
  • don't need the data in the file at execution time.
  • want to go with conventional libraries vs rolling your own solution

Below was benchmarked on a ~10Mb xlsx, xlsb file.

xlsx, xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

Benchmarks: ~ 14x speed improvement

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

Benchmarks: ~ 56x speed improvement

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Notes:

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

Python/BeautifulSoup - how to remove all tags from an element?

Use get_text(), it returns all the text in a document or beneath a tag, as a single Unicode string.

For instance, remove all different script tags from the following text:

<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>

The expected result is:

Signal et Communication
Ingénierie Réseaux et Télécommunications

Here is the source code:

#!/usr/bin/env python3
from bs4 import BeautifulSoup

text = '''
<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>
'''
soup = BeautifulSoup(text)

print(soup.get_text())

How exactly does <script defer="defer"> work?

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

webpack command not working

npm i webpack -g

installs webpack globally on your system, that makes it available in terminal window.

Greater than and less than in one statement

If this is really bothering you, why not write your own method isBetween(orderBean.getFiles().size(),0,5)?

Another option is to use isEmpty as it is a tad clearer:

if(!orderBean.getFiles().isEmpty() && orderBean.getFiles().size() < 5)

How do I generate a stream from a string?

We use the extension methods listed below. I think you should make the developer make a decision about the encoding, so there is less magic involved.

public static class StringExtensions {

    public static Stream ToStream(this string s) {
        return s.ToStream(Encoding.UTF8);
    }

    public static Stream ToStream(this string s, Encoding encoding) {
        return new MemoryStream(encoding.GetBytes(s ?? ""));
    }
}

Convert a Pandas DataFrame to a dictionary

Try to use Zip

df = pd.read_csv("file")
d= dict([(i,[a,b,c ]) for i, a,b,c in zip(df.ID, df.A,df.B,df.C)])
print d

Output:

{'p': [1, 3, 2], 'q': [4, 3, 2], 'r': [4, 0, 9]}

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Multiple line comment in Python

Try this

'''
This is a multiline
comment. I can type here whatever I want.
'''

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.

SelectSingleNode returning null for known good xml node path using XPath

I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.

I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.

EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager for it. Here's some sample code that works with your sample document:

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        doc.Load("test.xml");
        XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
        string msgID = idNode.Attributes["extension"].Value;
        Console.WriteLine(msgID);
    }
}

PHPUnit assert that an exception was thrown?

public function testException() {
    try {
        $this->methodThatThrowsException();
        $this->fail("Expected Exception has not been raised.");
    } catch (Exception $ex) {
        $this->assertEquals($ex->getMessage(), "Exception message");
    }

}

Executing another application from Java

I assume that you know how to execute the command using the ProcessBuilder.

Executing a command from Java always should read the stdout and stderr streams from the process. Otherwise it can happen that the buffer is full and the process cannot continue because writing its stdout or stderr blocks.

Bootstrap 3 Glyphicons CDN

An alternative would be to use Font-Awesome for icons:

Including Font-Awesome

Open Font-Awesome on CDNJS and copy the CSS url of the latest version:

<link rel="stylesheet" href="<url>">

Or in CSS

@import url("<url>");

For example (note, the version will change):

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

Usage:

<i class="fa fa-bed"></i>

It contains a lot of icons!

Android Studio - Gradle sync project failed

Update for 2018:

I have faced this issue recently and it was resolved by updating android studio & updating gradle when prompted then rebuilding the project

What is the difference between typeof and instanceof and when should one be used vs. the other?

no need to overwhelm with ton of above examples, just keep in mind two points of view:

  1. typeof var; is an unary operator will return the original type or root type of var. so that it will return primitive types(string, number, bigint, boolean, undefined, and symbol) or object type.

  2. in case of higher-level object, like built-in objects (String, Number, Boolean, Array..) or complex or custom objects, all of them is object root type, but instance type built base on them is vary(like OOP class inheritance concept), here a instanceof A - a binary operator - will help you, it will go through the prototype chain to check whether constructor of the right operand(A) appears or not.

so whenever you want to check "root type" or work with primitive variable - use "typeof", otherwise using "instanceof".

null is a special case,which is seemingly primitive, but indeed is a special case for object. Using a === null to check null instead.

on the other hand, function is also a special case, which is built-in object but typeof return function

as you can see instanceof must go through the prototype chain meanwhile typeof just check the root type one time so it's easy to understand why typeof is faster than instanceof

Why doesn't JavaScript have a last method?

pop() method will pop the last value out. But the problem is that you will lose the last value in the array

set div height using jquery (stretch div height)

$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});

function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/ 
$('#content').css({"height":calculatecontsize + "px"} );
}

Import Excel spreadsheet columns into SQL Server database

Microsoft suggest several methods:

  • SQL Server Data Transformation Services (DTS)
  • Microsoft SQL Server 2005 Integration Services (SSIS)
  • SQL Server linked servers
  • SQL Server distributed queries
  • ActiveX Data Objects (ADO) and the Microsoft OLE DB Provider for SQL Server
  • ADO and the Microsoft OLE DB Provider for Jet 4.0

If the wizard (DTS) isn't working (and I think it should) you could try something like this http://www.devasp.net/net/articles/display/771.html which basically suggests doing something like

INSERT INTO [tblTemp] ([Column1], [Column2], [Column3], [Column4])

SELECT A.[Column1], A.[Column2], A.[Column3], A.[Column4]
FROM OPENROWSET 
('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\Excel.xls;HDR=YES', 'select * from [Sheet1$]') AS A;

Check if list is empty in C#

You should use a simple IF statement

List<String> data = GetData();

if (data.Count == 0)
    throw new Exception("Data Empty!");

PopulateGrid();
ShowGrid();

ld cannot find -l<library>

you can add the Path to coinhsl lib to LD_LIBRARY_PATH variable. May be that will help.

export LD_LIBRARY_PATH=/xx/yy/zz:$LD_LIBRARY_PATH

where /xx/yy/zz represent the path to coinhsl lib.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.

   navigator.html5={
     canvas: (function(){
      var dc= document.createElement('canvas');
      if(!dc.getContext) return 0;
      var c= dc.getContext('2d');
      return typeof c.fillText== 'function'? 2: 1;
     })(),
     localStorage: (function(){
      return !!window.localStorage;
     })(),
     webworkers: (function(){
      return !!window.Worker;
     })(),
     offline: (function(){
      return !!window.applicationCache;
     })()
    }

Looping through all rows in a table column, Excel-VBA

You can loop through the cells of any column in a table by knowing just its name and not its position. If the table is in sheet1 of the workbook:

Dim rngCol as Range
Dim cl as Range
Set rngCol = Sheet1.Range("TableName[ColumnName]")
For Each cl in rngCol
    cl.Value = "PHEV"
Next cl

The code above will loop through the data values only, excluding the header row and the totals row. It is not necessary to specify the number of rows in the table.

Use this to find the location of any column in a table by its column name:

Dim colNum as Long
colNum = Range("TableName[Column name to search for]").Column

This returns the numeric position of a column in the table.

How to restrict SSH users to a predefined set of commands after login?

You should acquire `rssh', the restricted shell

You can follow the restriction guides mentioned above, they're all rather self-explanatory, and simple to follow. Understand the terms `chroot jail', and how to effectively implement sshd/terminal configurations, and so on.

Being as most of your users access your terminals via sshd, you should also probably look into sshd_conifg, the SSH daemon configuration file, to apply certain restrictions via SSH. Be careful, however. Understand properly what you try to implement, for the ramifications of incorrect configurations are probably rather dire.

Choosing the best concurrency list in Java

had better be List

The only List implementation in java.util.concurrent is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.

That said, are you sure you need it to be a List? There are a lot more options for concurrent Queues and Maps (and you can make Sets from Maps), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.

For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:

Regular expression for address field validation

As a simple one line expression recommend this,

^([a-zA-z0-9/\\''(),-\s]{2,255})$

Check existence of directory and create if doesn't exist

One-liner:

if (!dir.exists(output_dir)) {dir.create(output_dir)}

Example:

dateDIR <- as.character(Sys.Date())
outputDIR <- file.path(outD, dateDIR)
if (!dir.exists(outputDIR)) {dir.create(outputDIR)}

Python extending with - using super() Python 3 vs Python 2

Another python3 implementation that involves the use of Abstract classes with super(). You should remember that

super().__init__(name, 10)

has the same effect as

Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it. Hence super()gets translated to Person and then if you include the hidden self, you get the above code frag.

from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass


class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass


a = Man("piyush", "179")
print(a.showIdentity())

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

Updating curl worked for us. Somehow yum uses curl for its transactions.

yum update curl --disablerepo=epel

can't load package: package .: no buildable Go source files

To resolve this for my situation:

I had to specify a more specific sub-package to install.

Wrong:

go get github.com/garyburd/redigo

Correct:

go get github.com/garyburd/redigo/redis

Python list / sublist selection -1 weirdness

If you want to get a sub list including the last element, you leave blank after colon:

>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

How to delete all data from solr and hbase

If you want to delete all of the data in Solr via SolrJ do something like this.

public static void deleteAllSolrData() {
    HttpSolrServer solr = new HttpSolrServer("http://localhost:8080/solr/core/");
    try {
      solr.deleteByQuery("*:*");
    } catch (SolrServerException e) {
      throw new RuntimeException("Failed to delete data in Solr. "
          + e.getMessage(), e);
    } catch (IOException e) {
      throw new RuntimeException("Failed to delete data in Solr. "
          + e.getMessage(), e);
    }
}

If you want to delete all of the data in HBase do something like this.

public static void deleteHBaseTable(String tableName, Configuration conf) {
    HBaseAdmin admin = null;    
    try {
        admin = new HBaseAdmin(conf);
        admin.disableTable(tableName);
        admin.deleteTable(tableName);
    } catch (MasterNotRunningException e) {
        throw new RuntimeException("Unable to delete the table " + tableName
        + ". The actual exception is: " + e.getMessage(), e);
    } catch (ZooKeeperConnectionException e) {
        throw new RuntimeException("Unable to delete the table " + tableName
        + ". The actual exception is: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException("Unable to delete the table " + tableName
        + ". The actual exception is: " + e.getMessage(), e);
    } finally {
        close(admin);
    }
 }

What are the differences between a pointer variable and a reference variable in C++?

You can use the difference between references and pointers if you follow a convention for arguments passed to a function. Const references are for data passed into a function, and pointers are for data passed out of a function. In other languages, you can explicit notate this with keywords such as in and out. In C++, you can declare (by convention) the equivalent. For example,

void DoSomething(const Foo& thisIsAnInput, Foo* thisIsAnOutput)
{
   if (thisIsAnOuput)
      *thisIsAnOutput = thisIsAnInput;
}

The use of references as inputs and pointers as outputs is part of the Google style guide.

How do you tell if a checkbox is selected in Selenium for Java?

public boolean getcheckboxvalue(String element)
    {   
        WebElement webElement=driver.findElement(By.xpath(element));
        return webElement.isSelected();
    }

PHP function to generate v4 UUID

Instead of breaking it down into individual fields, it's easier to generate a random block of data and change the individual byte positions. You should also use a better random number generator than mt_rand().

According to RFC 4122 - Section 4.4, you need to change these fields:

  1. time_hi_and_version (bits 4-7 of 7th octet),
  2. clock_seq_hi_and_reserved (bit 6 & 7 of 9th octet)

All of the other 122 bits should be sufficiently random.

The following approach generates 128 bits of random data using openssl_random_pseudo_bytes(), makes the permutations on the octets and then uses bin2hex() and vsprintf() to do the final formatting.

function guidv4($data)
{
    assert(strlen($data) == 16);

    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10

    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

echo guidv4(openssl_random_pseudo_bytes(16));

With PHP 7, generating random byte sequences is even simpler using random_bytes():

function guidv4($data = null)
{
    $data = $data ?? random_bytes(16);
    // ...
}

SQL Server: Get data for only the past year

I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.

At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.

SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))

Thanks to those above whose solutions helped me arrive at what I needed.

MySQL Data - Best way to implement paging?

There's literature about it:

The main problem happens with the usage of large OFFSETs. They avoid using OFFSET with a variety of techniques, ranging from id range selections in the WHERE clause, to some kind of caching or pre-computing pages.

There are suggested solutions at Use the INDEX, Luke:

The difference in months between dates in MySQL

The DATEDIFF function can give you the number of days between two dates. Which is more accurate, since... how do you define a month? (28, 29, 30, or 31 days?)

How to split a dataframe string column into two columns?

If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:

df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]  

No more data to read from socket error

I seemed to fix my instance by removing the parameter placeholder for a parameterized query.

For some reason, using these placeholders were working fine, and then they stopped working and I got the error/bug.

As a workaround, I substituted literals for my placeholders and it started working.

Remove this

where 
    SOME_VAR = :1

Use this

where 
    SOME_VAR = 'Value'

Hide text using css

h1 {
    text-indent: -3000px; 
    line-height: 3000px;
    background-image: url(/LOGO.png);
    height: 100px; width:  600px;  /* height and width are a must */

}

Support for "border-radius" in IE

SOLVED - not rendering border radius correctly in IE 10 and 11

For those not getting the -ms-border-radius: or the border-radius: to work in IE 10,11 And it renders all square then follow these steps:

  1. Click on the gear wheel at the top right of the IE browser
  2. Click on Compatibility view settings
  3. Now uncheck the 2 boxes that are checked by default.

Ensure that the boxes are unchecked as in pic

How can I get the number of days between 2 dates in Oracle 11g?

I figured it out myself. I need

select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual

Eloquent - where not equal to

While this seems to work

Code::query()
    ->where('to_be_used_by_user_id', '!=' , 2)
    ->orWhereNull('to_be_used_by_user_id')
    ->get();

you should not use it for big tables, because as a general rule "or" in your where clause is stopping query to use index. You are going from "Key lookup" to "full table scan"

enter image description here enter image description here

Instead, try Union

$first = Code::whereNull('to_be_used_by_user_id');

$code = Code::where('to_be_used_by_user_id', '!=' , 2)
        ->union($first)
        ->get();

Get environment value in controller

All of the variables listed in .env file will be loaded into the $_ENV PHP super-global when your application receives a request. Check out the Laravel configuration page.

$_ENV['yourkeyhere'];

How can I run multiple curl requests processed sequentially?

According to the curl man page:

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

So the simplest and most efficient (curl will send them all down a single TCP connection [those to the same origin]) approach would be put them all on a single invocation of curl e.g.:

curl http://example.com/?update_=1 http://example.com/?update_=2