Programs & Examples On #Jquery mobile

jQuery Mobile is a touch-optimized web framework for smartphones and tablets. It provides a unified user interface system across all popular mobile device platforms, built on jQuery.

jquery mobile background image

Override ui-page class in your css:

.ui-page {
    background: url("image.gif");
    background-repeat: repeat;
}

Remove attribute "checked" of checkbox

Both of these should work:

$("#captureImage").prop('checked', false);

AND/OR

$("#captureImage").removeAttr('checked');

... you can try both together.

How to auto adjust the div size for all mobile / tablet display formats?

Simple:

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />

Cheers!

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

jQuery Mobile how to check if button is disabled?

Use .prop instead:

$('#deliveryNext').prop('disabled')

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

Centering elements in jQuery Mobile

I had found problems with some of the other methods mentioned here. Another way to do it would be to use layout grid B, and put your content in block b, and leave blocks a and c empty.

http://demos.jquerymobile.com/1.1.2/docs/content/content-grids.html

_x000D_
_x000D_
<div class="ui-grid-b">_x000D_
 <div class="ui-block-a"></div>_x000D_
 <div class="ui-block-b">Your Content Here</div>_x000D_
 <div class="ui-block-c"></div>_x000D_
</div><!-- /grid-b -->
_x000D_
_x000D_
_x000D_

Long Press in JavaScript?

Based on Maycow Moura's answer, I wrote this. It also ensures that the user didn't do a right click, which would trigger a long press and works on mobile devices. DEMO

var node = document.getElementsByTagName("p")[0];
var longpress = false;
var presstimer = null;
var longtarget = null;

var cancel = function(e) {
    if (presstimer !== null) {
        clearTimeout(presstimer);
        presstimer = null;
    }

    this.classList.remove("longpress");
};

var click = function(e) {
    if (presstimer !== null) {
        clearTimeout(presstimer);
        presstimer = null;
    }

    this.classList.remove("longpress");

    if (longpress) {
        return false;
    }

    alert("press");
};

var start = function(e) {
    console.log(e);

    if (e.type === "click" && e.button !== 0) {
        return;
    }

    longpress = false;

    this.classList.add("longpress");

    if (presstimer === null) {
        presstimer = setTimeout(function() {
            alert("long click");
            longpress = true;
        }, 1000);
    }

    return false;
};

node.addEventListener("mousedown", start);
node.addEventListener("touchstart", start);
node.addEventListener("click", click);
node.addEventListener("mouseout", cancel);
node.addEventListener("touchend", cancel);
node.addEventListener("touchleave", cancel);
node.addEventListener("touchcancel", cancel);

You should also include some indicator using CSS animations:

p {
    background: red;
    padding: 100px;
}

.longpress {
    -webkit-animation: 1s longpress;
            animation: 1s longpress;
}

@-webkit-keyframes longpress {
    0%, 20% { background: red; }
    100% { background: yellow; }
}

@keyframes longpress {
    0%, 20% { background: red; }
    100% { background: yellow; }
}

jQuery Mobile - back button

You can try this script in the header of HTML code:

<script>
   $.extend(  $.mobile , {
   ajaxEnabled: false,
   hashListeningEnabled: false
   });
</script>

Disable scrolling when touch moving certain element

To my surprise, the "preventDefault()" method is working for me on latest Google Chrome (version 85) on iOS 13.7. It also works on Safari on the same device and also working on my Android 8.0 tablet. I am currently implemented it for 2D view on my site here: https://papercraft-maker.com

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

Disable Buttons in jQuery Mobile

If I'm reading this question correctly, you may be missing that a jQuery mobile "button" widget is not the same thing as an HTML button element. I think this boils down to you can't call $('input').button('disable') unless you have previously called $('input').button(); to initialize a jQuery Mobile button widget on your input.

Of course, you may not want to be using jQuery button widget functionality, in which case Alexander's answer should set you right.

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

jQuery Cross Domain Ajax

The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.

$.ajax({
    type: 'GET',
    dataType: "text", // You need to use dataType text else it will try to parse it.
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

jQuery Mobile: Stick footer to bottom of page

I thought I'd share my CSS only solution here. This way you can avoid the extra overhead of using JS for this.

This isn't a fixed position footer. The footer will be offscreen if the page content is taller than the screen. I think it looks better this way.

The body and .ui-page min-height and height are necessary to prevent the footer from jumping up and down during transitions.

Works with the latest JQM version as of now, 1.4.0

body,
.ui-page {
    min-height:100% !important;
    height:auto !important;
}

.ui-content {
    margin-bottom:42px; /* HEIGHT OF YOUR FOOTER */
}

.ui-footer {
    position:absolute !important;
    width:100%;
    bottom:0;
}

disable past dates on datepicker

<div class="input-group date" data-provide="datepicker" data-date-start-date="0d">
    <input type="text" class="form-control" id="input_id" name="input_name" />
    <div class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </div>
</div> 

JQuery Parsing JSON array

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});

jQuery Mobile: document ready vs. page events

Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).

$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});

You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:

$(window).unload(function () { debugger; console.log("window unloaded");});

And you will see what I mean.

Jquery change <p> text programmatically

It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?

something like this:

$("#gender").trigger("pageinit");

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

How can I check if a checkbox is checked?

Try this:

function validate() {
  var remember = document.getElementById("remember");
  if (remember.checked) {
    alert("checked");
  } else {
    alert("You didn't check it! Let me check it for you.");
  }
}

Your script doesn't know what the variable remember is. You need to get the element first using getElementById().

wordpress contactform7 textarea cols and rows change in smaller screens

I know this post is old, sorry for that.

You can also type 10x for cols and x2 for rows, if you want to have only one attribute.

[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->

How to use document.getElementByName and getElementByTag?

  1. The getElementsByName() method accesses all elements with the specified name. this method returns collection of elements that is an array.
  2. The getElementsByTagName() method accesses all elements with the specified tagname. this method returns collection of elements that is an array.
  3. Accesses the first element with the specified id. this method returns only a single element.

eg:

<script type="text/javascript">
    function getElements() {
        var x=document.getElementById("y");
        alert(x.value);
    }
</script>
</head>
<body>
    <input name="x" id="y" type="text" size="20" /><br />

This will return a single HTML element and display the value attribute of it.

<script type="text/javascript">
    function getElements() {
        var x=document.getElementsByName("x");
        alert(x.length);
    }
</script>
</head>
<body>
    <input name="x" id="y" type="text" size="20" /><br />
    <input name="x" id="y" type="text" size="20" /><br />

this will return an array of HTML elements and number of elements that match the name attribute.

Extracted from w3schools.

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

for (String keys : objectSet.keySet())  
{
   System.out.println(keys + ":"+ objectSet.get(keys));
}

send Content-Type: application/json post with node.js

Using request with headers and post.

var options = {
            headers: {
                  'Authorization': 'AccessKey ' + token,
                  'Content-Type' : 'application/json'
            },
            uri: 'https://myurl.com/param' + value',
            method: 'POST',
            json: {'key':'value'}
 };
      
 request(options, function (err, httpResponse, body) {
    if (err){
         console.log("Hubo un error", JSON.stringify(err));
    }
    //res.status(200).send("Correcto" + JSON.stringify(body));
 })

How do I pass multiple parameters in Objective-C?

for create method:

-(void)mymethods:(NSString *)aCont withsecond:(NSString *)a-second {
//method definition...
}

for call the method:

[mymethods:self.contoCorrente withsecond:self.asecond];

Is there a bash command which counts files?

This simple one-liner should work in any shell, not just bash:

ls -1q log* | wc -l

ls -1q will give you one line per file, even if they contain whitespace or special characters such as newlines.

The output is piped to wc -l, which counts the number of lines.

syntax for creating a dictionary into another dictionary in python

dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

sum two columns in R

Try this for creating a column3 as a sum of column1 + column 2 in a table

tablename$column3=rowSums(cbind(tablename$column1,tablename$column2))

Import Google Play Services library in Android Studio

I had similar issue Cannot resolve com.google.android.gms.common.

I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!

Summary:

  1. Installed/Updated Google Play Services, and Google Repository from SDK Manager
  2. Added dependency in build.gradle: compile 'com.google.android.gms:play-services:4.0.30'
  3. Updated AndroidManifest.xml with <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

CMake does not find Visual C++ compiler

Check name folder too long or not.

Set angular scope variable in markup

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

Loop through an array php

Using foreach loop without key

foreach($array as $item) {
    echo $item['filename'];
    echo $item['filepath'];

    // to know what's in $item
    echo '<pre>'; var_dump($item);
}

Using foreach loop with key

foreach($array as $i => $item) {
    echo $item[$i]['filename'];
    echo $item[$i]['filepath'];

    // $array[$i] is same as $item
}

Using for loop

for ($i = 0; $i < count($array); $i++) {
    echo $array[$i]['filename'];
    echo $array[$i]['filepath'];
}

var_dump is a really useful function to get a snapshot of an array or object.

.m2 , settings.xml in Ubuntu

You can find your maven files here:

cd ~/.m2

Probably you need to copy settings.xml in your .m2 folder:

cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/

If no .m2 folder exists:

mkdir -p ~/.m2

How to write palindrome in JavaScript

To avoid errors with special characters use this function below

function palindrome(str){
  var removeChar = str.replace(/[^A-Z0-9]/ig, "").toLowerCase();
  var checkPalindrome = removeChar.split('').reverse().join('');
  if(removeChar === checkPalindrome){
     return true;
  }else{
    return false;
  }
}

find -exec with multiple commands

Another way is like this:

multiple_cmd() { 
    tail -n1 $1; 
    ls $1 
}; 
export -f multiple_cmd; 
find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;

in one line

multiple_cmd() { tail -1 $1; ls $1 }; export -f multiple_cmd; find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;
  • "multiple_cmd()" - is a function
  • "export -f multiple_cmd" - will export it so any other subshell can see it
  • "find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;" - find that will execute the function on your example

In this way multiple_cmd can be as long and as complex, as you need.

Hope this helps.

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

You can also use a pretty simple for loop:

for f in `find . -not -name "*Music*"`
do
    cp $f /target/dir
done

How do you append to a file?

If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:

Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

By using append mode, the operating system will place any write at the end of the file.

f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".

WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.

Redirect stdout to a file in Python?

import sys
sys.stdout = open('stdout.txt', 'w')

Center a button in a Linear layout

You also can Try this Code:

<LinearLayout
            android:id="@+id/linear_layout"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:orientation="horizontal"
            android:weightSum="2.0"
            android:background="@drawable/anyBackground" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/img_mail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/yourImage" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:layout_weight="1" >



<ImageView
            android:id="@+id/img_save"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="@drawable/yourImage" />
        </LinearLayout>
        </LinearLayout>

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Try this solution if works.

window.onkeypress = function(e) {
    if ((e.which || e.keyCode) == 116) {
        alert("fresh");
    }
}

ADB Driver and Windows 8.1

If all other solutions did not work for your device try this guide how to make a truly universal adb and fastboot driver out of Google USB driver. The resulting driver works for adb, recovery and fastboot modes in all versions of Windows.

Difference between filter and filter_by in SQLAlchemy

It is a syntax sugar for faster query writing. Its implementation in pseudocode:

def filter_by(self, **kwargs):
    return self.filter(sql.and_(**kwargs))

For AND you can simply write:

session.query(db.users).filter_by(name='Joe', surname='Dodson')

btw

session.query(db.users).filter(or_(db.users.name=='Ryan', db.users.country=='England'))

can be written as

session.query(db.users).filter((db.users.name=='Ryan') | (db.users.country=='England'))

Also you can get object directly by PK via get method:

Users.query.get(123)
# And even by a composite PK
Users.query.get(123, 321)

When using get case its important that object can be returned without database request from identity map which can be used as cache(associated with transaction)

How might I extract the property values of a JavaScript object into an array?

Assuming your dataObject is defined the way you specified, you do this:

var dataArray = [];
for (var key in dataObject)
    dataArray.push(dataObject[key]);

And end up having dataArray populated with inner objects.

REST HTTP status codes for failed validation or invalid duplicate

Status Code 304 Not Modified would also make an acceptable response to a duplicate request. This is similar to processing a header of If-None-Match using an entity tag.

In my opinion, @Piskvor's answer is the more obvious choice to what I perceive is the intent of the original question, but I have an alternative that is also relevant.

If you want to treat a duplicate request as a warning or notification rather than as an error, a response status code of 304 Not Modified and Content-Location header identifying the existing resource would be just as valid. When the intent is merely to ensure that a resource exists, a duplicate request would not be an error but a confirmation. The request is not wrong, but is simply redundant, and the client can refer to the existing resource.

In other words, the request is good, but since the resource already exists, the server does not need to perform any further processing.

How to set root password to null

Wanted to put my own 2cents in here bcuz the above answers did not work for me. On centos 7, mysql community v8, shell is bash.

The correct commands would be as follows:

# start mysql without password checking
systemctl stop mysqld 2>/dev/null
systemctl set-environment MYSQLD_OPTS="--skip-grant-tables" &&
systemctl start mysqld

# set default password to nothing
mysql -u root mysql <<- 'EOF'
    FLUSH PRIVILEGES;
    UNINSTALL COMPONENT 'file://component_validate_password';
    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '';
    FLUSH PRIVILEGES;
    INSTALL COMPONENT 'file://component_validate_password';
EOF

# restart mysql normally
systemctl restart mysqld

then you can login without password:

mysql -u root

Could not load NIB in bundle

In my case, I was creating a framework with Cocoapods. The problems was this line:

s.static_framework = true

in my framework.podspec file

After commented this line above all problems to access storyboards or XIBs went out.

Change value of input and submit form in JavaScript

You can use the onchange event:

<form name="myform" id="myform" action="action.php">
    <input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" onclick="DoSubmit()" />
</form>

use mysql SUM() in a WHERE clause

When using aggregate functions to filter, you must use a HAVING statement.

SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500

ORDER BY date and time BEFORE GROUP BY name in mysql

I had a different variation on this question where I only had a single DATETIME field and needed a limit after a group by or distinct after sorting descending based on the datetime field, but this is what helped me:

select distinct (column) from
(select column from database.table
order by date_column DESC) as hist limit 10

In this instance with the split fields, if you can sort on a concat, then you might be able to get away with something like:

select name,date,time from
(select name from table order by concat(date,' ',time) ASC)
as sorted

Then if you wanted to limit you would simply add your limit statement to the end:

select name,date,time from
(select name from table order by concat(date,' ',time) ASC)
as sorted limit 10

How to get history on react-router v4?

This works! https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);

Reloading .env variables without restarting server (Laravel 5, shared hosting)

To be clear there are 4 types of caches you can clear depending upon your case.

php artisan cache:clear

You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.

php artisan route:cache

This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.

php artisan config:cache 

This will clear the caching of the env file and reload it

php artisan view:clear 

This will clear the compiled view files of your application.

For Shared Hosting

Most of the shared hosting providers don't provide SSH access to the systems. In such a case you will need to create a route and call the following line as below:

Route::get('/clear-cache', function() {
    Artisan::call('cache:clear');
    return "All cache cleared";
});

Is it possible to validate the size and type of input=file in html5

if your using php for the backend maybe you can use this code.

// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
    $msg = "Image File Size is Greater than 2MB.";
    header("Location: ../product.php?error=$msg");
    exit();
}  

How to convert AAR to JAR

Resource based .aar-projects

Finding the classes.jar file inside the .aar file is pretty trivial. However, that approach does not work, if the .aar-project defined some resources (example: R.layout.xyz)

  • Therefore deaar from CommonsGuy helped me to get a valid ADT-friendly project out of an .aar-file. In my case I converted subsampling-scale-image-view. It took me about an hour to set up ruby on my PC.

  • Another approach is using android-maven-plugin for Eclipse/ADT as CommonsGuy writes in his blog.

  • Yet another approach could be, just cloning the whole desired project as source from git and import it as "Existing Android project"

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

How to Convert unsigned char* to std::string in C++?

Here is the complete code

#include <bits/stdc++.h>

using namespace std;

typedef unsigned char BYTE;

int main() {
  //method 1;
  std::vector<BYTE> data = {'H','E','L','L','O','1','2','3'};
  //string constructor accepts only const char
  std::string s((const char*)&(data[0]), data.size());
  std::cout << s << std::endl;

  //method 2
  std::string s2(data.begin(),data.end());
  std::cout << s2 << std::endl;

  //method 3
  std::string s3(reinterpret_cast<char const*>(&data[0]), data.size()) ;
  std::cout << s3 << std::endl;
 
  return 0;
}

How to log cron jobs?

There are at least three different types of logging:

  1. The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.

  2. The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:

     * * * *  COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
    
    • I would also consider checking the permissions of /ABSOLUTE_PATH_TO_LOG, and run the command from that user's permissions. Just for verification, while you test whether it might be a potential source of problems.
  3. The logging of the program itself, with its own error-handling and logging for tracking purposes.

There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:

$locate python

Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.

  • Another common source of problems is the syntax in the cronjob. Remember that there are special characters you can use for lists (commas), to define ranges (dashes -), to define increment of ranges (slashes), etc. Take a look: http://www.softpanorama.org/Utilities/cron.shtml

Arrays.asList() of an array

As far as I understand it, the sort function in the collection class can only be used to sort collections implementing the comparable interface.

You are supplying it a array of integers. You should probably wrap this around one of the know Wrapper classes such as Integer. Integer implements comparable.

Its been a long time since I have worked on some serious Java, however reading some matter on the sort function will help.

How to update Python?

  • Official Python .msi installers are designed to replace:

    • any previous micro release (in x.y.z, z is "micro") because they are guaranteed to be backward-compatible and binary-compatible
    • a "snapshot" (built from source) installation with any micro version
  • A snapshot installer is designed to replace any snapshot with a lower micro version.

(See responsible code for 2.x, for 3.x)

Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:

  • If you installed any modules from bdist_wininst packages (Windows .exes), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logic
  • modules installed with setuptools/pip that reside in Lib\site-packages can just be deleted afterwards
  • packages that you installed per-user, if any, reside in %APPDATA%/Python/PythonXY/site-packages and can likewise be deleted

Group list by values

len = max(key for (item, key) in list)
newlist = [[] for i in range(len+1)]
for item,key in list:
  newlist[key].append(item)

You can do it in a single list comprehension, perhaps more elegant but O(n**2):

[[item for (item,key) in list if key==i] for i in range(max(key for (item,key) in list)+1)]

Generating an MD5 checksum of a file

In Python 3.8+ you can do

import hashlib
with open("your_filename.txt", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippet). It's cryptographically secure and faster than MD5.

How to convert URL parameters to a JavaScript object?

Split on & to get name/value pairs, then split each pair on =. Here's an example:

var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
var obj = str.split("&").reduce(function(prev, curr, i, arr) {
    var p = curr.split("=");
    prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
    return prev;
}, {});

Another approach, using regular expressions:

var obj = {}; 
str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
    obj[decodeURIComponent(key)] = decodeURIComponent(value);
}); 

This is adapted from John Resig's "Search and Don’t Replace".

How to run a method every X seconds

The solution you will use really depends on how long you need to wait between each execution of your function.

If you are waiting for longer than 10 minutes, I would suggest using AlarmManager.

// Some time when you want to run
Date when = new Date(System.currentTimeMillis());

try {
    Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched

    // Note: this could be getActivity if you want to launch an activity
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
        context,
        0, // id (optional)
        someIntent, // intent to launch
        PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
    );

    AlarmManager alarms = (AlarmManager) context.getSystemService(
        Context.ALARM_SERVICE
    );

    alarms.setRepeating(
        AlarmManager.RTC_WAKEUP,
        when.getTime(),
        AlarmManager.INTERVAL_FIFTEEN_MINUTES,
        pendingIntent
    );
} catch(Exception e) {
    e.printStackTrace();
}

Once you have broadcasted the above Intent, you can receive your Intent by implementing a BroadcastReceiver. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter); method. For more information on BroadcastReceiver's please refer to the official documentation..

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent)
    {
        System.out.println("MyReceiver: here!") // Do your work here
    }
}

If you are waiting for shorter than 10 minutes then I would suggest using a Handler.

final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second

handler.postDelayed(new Runnable() {
    public void run() {
        System.out.println("myHandler: here!"); // Do your work here
        handler.postDelayed(this, delay);
    }
}, delay);

Javascript Thousand Separator / string format

There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number

It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:

$.number(12345.4556, 2);          // -> 12,345.46
$.number(12345.4556, 3, ',', ' ') // -> 12 345,456

You can use it inside input fields directly, which is nicer, using same options like above:

$("input").number(true, 2);

Or you can apply to a whole set of DOM elements using selector:

$('span.number').number(true, 2);

Laravel orderBy on a relationship

Try this solution.

$mainModelData = mainModel::where('column', $value)
    ->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
    ->orderBy('relation_table.title', 'ASC')
    ->with(['relationModal' => function ($q) {
        $q->where('column', 'value');
    }])->get();

Example:

$user = User::where('city', 'kullu')
    ->join('salaries', 'users.id', '=', 'salaries.user_id')
    ->orderBy('salaries.amount', 'ASC')
    ->with(['salaries' => function ($q) {
        $q->where('amount', '>', '500000');
    }])->get();

You can change the column name in join() as per your database structure.

WPF Image Dynamically changing Image source during runtime

Try Stretch="UniformToFill" on the Image

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

That's not the real error, here's how to find it:

Go to the hadoop jobtracker web-dashboard, find the hive mapreduce jobs that failed and look at the logs of the failed tasks. That will show you the real error.

The console output errors are useless, largely beause it doesn't have a view of the individual jobs/tasks to pull the real errors (there could be errors in multiple tasks)

Hope that helps.

Read Session Id using Javascript

For PHP's PHPSESSID variable, this function works:

function getPHPSessId() {
    var phpSessionId = document.cookie.match(/PHPSESSID=[A-Za-z0-9]+\;/i);

    if(phpSessionId == null) 
        return '';

    if(typeof(phpSessionId) == 'undefined')
        return '';

    if(phpSessionId.length <= 0)
        return '';

    phpSessionId = phpSessionId[0];

    var end = phpSessionId.lastIndexOf(';');
    if(end == -1) end = phpSessionId.length;

    return phpSessionId.substring(10, end);
}

OS detecting makefile

That's the job that GNU's automake/autoconf are designed to solve. You might want to investigate them.

Alternatively you can set environment variables on your different platforms and make you Makefile conditional against them.

How to install Python MySQLdb module using pip?

If pip3 isn't working, you can try:

sudo apt install python3-mysqldb

How can I fill a div with an image while keeping it proportional?

The CSS object-fit: cover and object-position: left center property values now address this issue.

unsigned int vs. size_t

Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide size_t. The C standards committee introduced size_t to eliminate a portability problem

Explained in detail at embedded.com (with a very good example)

Git push error '[remote rejected] master -> master (branch is currently checked out)'

You can simply convert your remote repository to bare repository (there is no working copy in the bare repository - the folder contains only the actual repository data).

Execute the following command in your remote repository folder:

git config --bool core.bare true

Then delete all the files except .git in that folder. And then you will be able to perform git push to the remote repository without any errors.

How to declare string constants in JavaScript?

Use global namespace or global object like Constants.

var Constants = {};

And using defineObject write function which will add all properties to that object and assign value to it.

function createConstant (prop, value) {
    Object.defineProperty(Constants , prop, {
      value: value,
      writable: false
   });
};

How to export data from Excel spreadsheet to Sql Server 2008 table

There are several tools which can import Excel to SQL Server.

I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...

I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.

Angular directives - when and how to use compile, controller, pre-link and post-link

Pre-link function

Each directive's pre-link function is called whenever a new related element is instantiated.

As seen previously in the compilation order section, pre-link functions are called parent-then-child, whereas post-link functions are called child-then-parent.

The pre-link function is rarely used, but can be useful in special scenarios; for example, when a child controller registers itself with the parent controller, but the registration has to be in a parent-then-child fashion (ngModelController does things this way).

Do not:

  • Inspect child elements (they may not be rendered yet, bound to scope, etc.).

Communication between multiple docker-compose projects

If you are

  • trying to communicate between two containers from different docker-compose projects and don't want to use the same network (because let's say they would have PostgreSQL or Redis container on the same port and you would prefer to not changing these ports and not use it at the same network)
  • developing locally and want to imitate communication between two docker compose projects
  • running two docker-compose projects on localhost
  • developing especially Django apps or Django Rest Framework (drf) API and running app inside container on some exposed port
  • getting Connection refused while trying to communicate between two containers

And you want to

  • container api_a communicate to api_b (or vice versa) without the same "docker network"

(example below)

you can use "host" of the second container as IP of your computer and port that is mapped from inside Docker container. You can obtain IP of your computer with this script (from: Finding local IP addresses using Python's stdlib):

import socket
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

Example:

project_api_a/docker-compose.yml:

networks:
  app-tier:
    driver: bridge

services:
  api:
    container_name: api_a
    image: api_a:latest
    depends_on:
      - postgresql
    networks:
      - app-tier

inside api_a container you are running Django app: manage.py runserver 0.0.0.0:8000

and second docker-compose.yml from other project:

project_api_b/docker-compose-yml :

networks:
  app-tier:
    driver: bridge

services:
  api:
    container_name: api_b
    image: api_b:latest
    depends_on:
      - postgresql
    networks:
      - app-tier

inside api_b container you are running Django app: manage.py runserver 0.0.0.0:8001

And trying to connect from container api_a to api_b then URL of api_b container will be: http://<get_ip_from_script_above>:8001/

It can be especially valuable if you are using even more than two(three or more) docker-compose projects and it's hard to provide common network for all of it - it's good workaround and solution

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

How to clone a Date object?

I found out that this simple assignmnent also works:

dateOriginal = new Date();
cloneDate = new Date(dateOriginal);

But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

HTML table with horizontal scrolling (first column fixed)

Based on skube's approach, I found the minimal set of CSS I needed was:

_x000D_
_x000D_
.horizontal-scroll-except-first-column {_x000D_
  width: 100%;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table {_x000D_
  margin-left: 8em;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th:first-child,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td:first-child {_x000D_
  position: absolute;_x000D_
  width: 8em;_x000D_
  margin-left: -8em;_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.horizontal-scroll-except-first-column > table > * > tr > th,_x000D_
.horizontal-scroll-except-first-column > table > * > tr > td {_x000D_
  /* Without this, if a cell wraps onto two lines, the first column_x000D_
   * will look bad, and may need padding. */_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<div class="horizontal-scroll-except-first-column">_x000D_
  <table>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>FIXED</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> <td>66666</td> <td>77777</td> <td>88888</td> <td>99999</td> <td>AAAAA</td> <td>BBBBB</td> <td>CCCCC</td> <td>DDDDD</td> <td>EEEEE</td> <td>FFFFF</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery adding 2 numbers from input fields

Adding strings concatenates them:

> "1" + "1"
"11"

You have to parse them into numbers first:

/* parseFloat is used here. 
 * Because of it's not known that 
 * whether the number has fractional places.
 */

var a = parseFloat($('#a').val()),
    b = parseFloat($('#b').val());

Also, you have to get the values from inside of the click handler:

$("submit").on("click", function() {
   var a = parseInt($('#a').val(), 10),
       b = parseInt($('#b').val(), 10);
});

Otherwise, you're using the values of the textboxes from when the page loads.

Extracting the last n characters from a string in R

I'm not aware of anything in base R, but it's straight-forward to make a function to do this using substr and nchar:

x <- "some text in a string"

substrRight <- function(x, n){
  substr(x, nchar(x)-n+1, nchar(x))
}

substrRight(x, 6)
[1] "string"

substrRight(x, 8)
[1] "a string"

This is vectorised, as @mdsumner points out. Consider:

x <- c("some text in a string", "I really need to learn how to count")
substrRight(x, 6)
[1] "string" " count"

ReferenceError: fetch is not defined

You should add this import in your file:

import * as fetch from 'node-fetch';

And then, run this code to add the node-fetch:

yarn add node-fetch

Transfer files to/from session I'm logged in with PuTTY

PuTTY usually comes with a client called psftp which you can leverage for this purpose. I don't believe you can do it through the standard PuTTY client (although I may be proven wrong on that).

PuTTY only gives you access to manipulate the remote machine. It doesn't provide a direct link between the two file systems any more than sitting down at the remote machine does.

When is TCP option SO_LINGER (0) required?

The typical reason to set a SO_LINGER timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT state, tying up all the available resources on a server.

When a TCP connection is closed cleanly, the end that initiated the close ("active close") ends up with the connection sitting in TIME_WAIT for several minutes. So if your protocol is one where the server initiates the connection close, and involves very large numbers of short-lived connections, then it might be susceptible to this problem.

This isn't a good idea, though - TIME_WAIT exists for a reason (to ensure that stray packets from old connections don't interfere with new connections). It's a better idea to redesign your protocol to one where the client initiates the connection close, if possible.

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

Android: Difference between Parcelable and Serializable?

There is some performance issue regarding to marshaling and unmarshaling. Parcelable is twice faster than Serializable.

Please go through the following link:

http://www.3pillarglobal.com/insights/parcelable-vs-java-serialization-in-android-app-development

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

You'll have to uninstall XAMPP 1.7.2 and install XAMPP 1.7.0, which contains PHP 5.2.8.

D:\Documents and Settings\box>php -v

PHP 5.2.8 (cli) (built: Dec  8 2008 19:31:23)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
    with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
    with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies

XAMPP 1.6.8 contains PHP 5.2.6.

D:\Documents and Settings\box>php -v
PHP 5.2.6 (cli) (built: May  2 2008 18:02:07)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
    with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
    with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies

Storing JSON in database vs. having a new column for each key

some time joins on the table will be an overhead. lets say for OLAP. if i have two tables one is ORDERS table and other one is ORDER_DETAILS. For getting all the order details we have to join two tables this will make the query slower when no of rows in the tables increase lets say in millions or so.. left/right join is too slower than inner join. I Think if we add JSON string/Object in the respective ORDERS entry JOIN will be avoided. add report generation will be faster...

Fade In Fade Out Android Animation in Java

Another alternative:

No need to define 2 animation for fadeIn and fadeOut. fadeOut is reverse of fadeIn.

So you can do this with Animation.REVERSE like this:

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(1000);
alphaAnimation.setRepeatCount(1);
alphaAnimation.setRepeatMode(Animation.REVERSE);
view.findViewById(R.id.imageview_logo).startAnimation(alphaAnimation);

then onAnimationEnd:

alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
    @Override
        public void onAnimationStart(Animation animation) {
            //TODO: Run when animation start
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            //TODO: Run when animation end
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            //TODO: Run when animation repeat
        }
    });

How can one pull the (private) data of one's own Android app?

Backed up Game data with apk. Nougat Oneplus 2.

**adb backup "-apk com.nekki.shadowfight" -f "c:\myapk\samsung2.ab"**

While loop to test if a file exists in bash

I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.

I found that if I ran cat /tmp/list.txt the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1; just before the cat /tmp/list.txt it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.

My final code:

while [ ! -f /tmp/list.txt ];
do
    sleep 1;
done;
sleep 1;
cat /tmp/list.txt;

Hope this helps save someone a frustrating half hour!

Passing parameters in rails redirect_to

routes.rb

 match 'controller_name/action_name' => 'controller_name#action_name', via: [:get, :post], :as => :abc

Any controller you want to redirect with parameters are given below:

redirect_to abc_path(@abc, id: @id), :notice => "message fine" 

Read response headers from API response - Angular 5 + TypeScript

You should use the new HttpClient. You can find more information here.

http
  .get<any>('url', {observe: 'response'})
  .subscribe(resp => {
    console.log(resp.headers.get('X-Token'));
  });

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

How to use setInterval and clearInterval?

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

Git log to get commits only for a specific branch

Here I present an alias based on Richard Hansen's answer (and Ben C's suggestion), but that I adapted to exclude tags. The alias should be fairly robust.

# For Git 1.22+
git config --global alias.only '!b=${1:-$(git branch --show-current)}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'
# For older Git:
git config --global alias.only '!b=${1:-$(git symbolic-ref -q --short HEAD)}; b=${b##heads/}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'

Example of use:

git only mybranch  # Show commits that are in mybranch ONLY
git only           # Show commits that are ONLY in current branch

Note that ONLY means commits that would be LOST (after garbage collection) if the given branch was deleted (excluding the effect of tags). The alias should work even if there is unfortunately a tag named mybranch (thanks to prefix heads/). Note also that no commits are shown if they are part of any remote branch (including upstream if any), in compliance with the definition of ONLY.

The alias shows the one-line history as a graph of the selected commits.

  a --- b --- c --- master
   \           \
    \           d
     \           \
      e --- f --- g --- mybranch (HEAD)
       \
        h --- origin/other

With example above, git only would show:

  * (mybranch,HEAD)
  * g
  |\
  | * d
  * f 

In order to include tags (but still excluding HEAD), the alias becomes (adapt as above for older Git):

git config --global alias.only '!b=${1:-$(git branch --show-current)};  git log --oneline --graph --all --not --exclude="refs/heads/$b" --exclude=HEAD --all #'

Or the variant that includes all the tags including HEAD (and removing current branch as default since it won't output anything):

git config --global alias.only '!git log --oneline --graph --all --not --exclude=\"refs/heads/$1\" --all #'

This last version is the only one that really satisfies the criteria commits-that-are-lost-if-given-branch-is-deleted, since a branch cannot be deleted if it is checked out, and no commit pointed by HEAD or any other tag will be lost. However the first two variants are more useful.

Finally, the alias does not work with remote branches (eg. git only origin/master). The alias must be modified, for instance:

git config --global alias.remote-only '!git log --oneline --graph "$1" --not --exclude="$1" --remotes --branches #'

Confused about stdin, stdout and stderr?

Here is a lengthy article on stdin, stdout and stderr:

To summarize:

Streams Are Handled Like Files

Streams in Linux—like almost everything else—are treated as though they were files. You can read text from a file, and you can write text into a file. Both of these actions involve a stream of data. So the concept of handling a stream of data as a file isn’t that much of a stretch.

Each file associated with a process is allocated a unique number to identify it. This is known as the file descriptor. Whenever an action is required to be performed on a file, the file descriptor is used to identify the file.

These values are always used for stdin, stdout, and stderr:

0: stdin
1: stdout
2: stderr

Ironically I found this question on stack overflow and the article above because I was searching for information on abnormal / non-standard streams. So my search continues.

What are the alternatives now that the Google web search API has been deprecated?

Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"

Custom Search Control Panel - Sites to search

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

Observable Finally on Subscribe

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

I think finalize() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

Jan 2019: Updated for RxJS 6

How do you clone a Git repository into a specific folder?

Usage

git clone <repository>

Clone the repository located at the <repository> onto the local machine. The original repository can be located on the local filesystem or on a remote machine accessible via HTTP or SSH.

git clone <repo> <directory>

Clone the repository located at <repository> into the folder called <directory> on the local machine.

Source: Setting up a repository

Connect to Oracle DB using sqlplus

it would be something like this

sqlplus -s /nolog  <<-!
connect ${ORACLE_UID}/${ORACLE_PWD}@${ORACLE_DB};
whenever sqlerror exit sql.sqlcode;
set pagesize 0;
set linesize 150;
spool <query_output.dat> APPEND
@$<input_query.dat>
spool off;
exit;
!

here

ORACLE_UID=<user name>
ORACLE_PWD=<password>
ORACLE_DB=//<host>:<port>/<DB name>

Inheriting from a template class in c++

For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.

Specifically, Area is not a template class, but a class template. That is, it is a template from which classes can be generated. Area<int> is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would be Area<char>. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.

Since Area is not a class, you cannot derive the class Rectangle from it. You only can derive a class from another class (or several of them). Since Area<int> is a class, you could, for example, derive Rectangle from it:

class Rectangle:
  public Area<int>
{
  // ...
};

Since Area<int> and Area<char> are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):

class Rectangle:
  public Area<int>,
  public Area<char>
{
  // ...
};

However you have to specify which classed to derive from when you define Rectangle. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.

What you can do is to make Rectangle a template as well. If you write

template<typename T> class Rectangle:
  public Area<T>
{
  // ...
};

You have a template Rectangle from which you can get a class Rectangle<int> which derives from Area<int>, and a different class Rectangle<char> which derives from Area<char>.

It may be that you want to have a single type Rectangle so that you can pass all sorts of Rectangle to the same function (which itself doesn't need to know the Area type). Since the Rectangle<T> classes generated by instantiating the template Rectangle are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:

class Rectangle // not inheriting from any Area type
{
  // Area independent interface
};

template<typename T> class SpecificRectangle:
  public Rectangle,
  public Area<T>
{
  // Area dependent stuff
};

void foo(Rectangle&); // A function which works with generic rectangles

int main()
{
  SpecificRectangle<int> intrect;
  foo(intrect);

  SpecificRectangle<char> charrect;
  foo(charrect);
}

If it is important that your generic Rectangle is derived from a generic Area you can do the same trick with Area too:

class Area
{
  // generic Area interface
};

class Rectangle:
  public virtual Area // virtual because of "diamond inheritance"
{
  // generic rectangle interface
};

template<typename T> class SpecificArea:
  public virtual Area
{
  // specific implementation of Area for type T
};

template<typename T> class SpecificRectangle:
  public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later
  public SpecificArea<T> // no virtual inheritance needed here
{
  // specific implementation of Rectangle for type T
};

git stash -> merge stashed change with current changes

May be, it is not the very worst idea to merge (via difftool) from ... yes ... a branch!

> current_branch=$(git status | head -n1 | cut -d' ' -f3)
> stash_branch="$current_branch-stash-$(date +%yy%mm%dd-%Hh%M)"
> git stash branch $stash_branch
> git checkout $current_branch
> git difftool $stash_branch

Breaking out of a nested loop

C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable INT_MAX -1 is often good choice):

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        if (exit_condition)
        {
            // cause the outer loop to break:
            // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue 
            i = int.MaxValue - 1;
            Console.WriteLine("Hi");
            // break the inner loop
            break;
        }
    }
    // if you have code in outer loop it will execute after break from inner loop    
}

As note in code says break will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case.

This approach works with for and while loops but does not work for foreach. In case of foreach you won't have code access to the hidden enumerator so you can't change it (and even if you could IEnumerator doesn't have some "MoveToEnd" method).

Acknowledgments to inlined comments' authors:
i = INT_MAX - 1 suggestion by Meta
for/foreach comment by ygoe.
Proper IntMax by jmbpiano
remark about code after inner loop by blizpasta

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Force re-download of release dependency using Maven

I think following command may help you!


mvn -U clean install

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

Apologies in advance for this lo-tech suggestion, but another option, which finally worked for me after battling NuGet for several hours, is to re-create a new empty project, Web API in my case, and just copy the guts of your old, now-broken project into the new one. Took me about 15 minutes.

How do I get extra data from intent on Android?

Kotlin

First Activity

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

Second Activity

val value = getIntent().getStringExtra("key")

Suggestion

Always put keys in constant file for more managed way.

companion object {
    val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}

Best way to find os name and version in Unix/Linux platform

In every distribute it has difference files so I write most common ones:

---- CentOS Linux distro
`cat /proc/version`
---- Debian Linux distro
`cat /etc/debian_version`
---- Redhat Linux distro
`cat /etc/redhat-release` 
---- Ubuntu Linux distro
`cat /etc/issue`   or   `cat /etc/lsb-release`

in last one /etc/issue didn't exist so I tried the second one and it returned the right answer

How to test the `Mosquitto` server?

To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).

You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:

On the machine with Mosquitto Server running, enter image description here

On the outside-word machine with mqtt-spy running, enter image description here

I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really. And also to my knowledge to run the mosquitto_sub and mosquitto_pub you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,

sudo apt-get install mosquitto-clients

Increment value in mysql update query

You can do this without having to query the actual amount of points, so it will save you some time and resources during the script execution.

mysql_query("UPDATE `member_profile` SET `points`= `points` + 1 WHERE `user_id` = '".intval($userid)."'");

Else, what you were doing wrong is that you passed the old amount of points as a string (points='5'+1), and you can't add a number to a string. ;)

Compare given date with today

$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');

var_dump(strtotime($today) > strtotime($expiry)); //false or true

How do I create a pause/wait function using Qt?

Similar to some answers here, but maybe a little more lightweight

void MyClass::sleepFor(qint64 milliseconds){
    qint64 timeToExitFunction = QDateTime::currentMSecsSinceEpoch()+milliseconds;
    while(timeToExitFunction>QDateTime::currentMSecsSinceEpoch()){
        QApplication::processEvents(QEventLoop::AllEvents, 100);
    }
}

How to generate a random number between 0 and 1?

Have you tried with: replacing ((rand() % 10000) / 10000.0), with:(rand() % 2). This worked for me!

So you could do something like this:

double r2()
{
     srand(time(NULL));
     return(rand() % 2);
}

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

How to substitute shell variables in complex text files

If you want env variables to be replaced in your source files while keeping all of the non env variables as they are, you can use the following command:

envsubst "$(printf '${%s} ' $(env | sed 's/=.*//'))" < source.txt > destination.txt

The syntax for replacing only specific variables is explained here. The command above is using a sub-shell to list all defined variables and then passing it to the envsubst

So if there's a defined env variable called $NAME, and your source.txt file looks like this:

Hello $NAME
Your balance is 123 ($USD)

The destination.txt will be:

Hello Arik
Your balance is 123 ($USD)

Notice that the $NAME is replaced and the $USD is left untouched

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

Custom domain for GitHub project pages

Overview

The documentation is a little confusing when it comes to project pages, as opposed to user pages. It feels like you should have to do more, but actually the process is very easy.

It involves:

  1. Setting up 2 static A records for the naked (no www) domain.
  2. Creating one CNAME record for www which will point to a GitHub URL. This will handle www redirection for you.
  3. Creating a file called CNAME (capitalised) in your project root on the gh-pages branch. This will tell Github what URL to respond to.
  4. Wait for everything to propagate.

What you will get

Your content will be served from a URL of the form http://nicholasjohnson.com.

Visiting http://www.nicholasjohnson.com will return a 301 redirect to the naked domain.

The path will be respected by the redirect, so traffic to http://www.nicholasjohnson.com/angular will be redirected to http://nicholasjohnson.com/angular.

You can have one project page per repository, so if your repos are open you can have as many as you like.

Here's the process:

1. Create A records

For the A records, point @ to the following ip addresses:

@: 185.199.108.153
@: 185.199.109.153
@: 185.199.110.153
@: 185.199.111.153

These are the static Github IP addresses from which your content will be served.

2. Create a CNAME Record

For the CNAME record, point www to yourusername.github.io. Note the trailing full stop. Note also, this is the username, not the project name. You don't need to specify the project name yet. Github will use the CNAME file to determine which project to serve content from.

e.g.

www: forwardadvance.github.io.

The purpose of the CNAME is to redirect all www subdomain traffic to a GitHub page which will 301 redirect to the naked domain.

Here's a screenshot of the configuration I use for my own site http://nicholasjohnson.com:

A and CNAME records required for Github Static Pages

3. Create a CNAME file

Add a file called CNAME to your project root in the gh-pages branch. This should contain the domain you want to serve. Make sure you commit and push.

e.g.

nicholasjohnson.com

This file tells GitHub to use this repo to handle traffic to this domain.

4. Wait

Now wait 5 minutes, your project page should now be live.

Ruby Arrays: select(), collect(), and map()

EDIT: I just realized you want to filter details, which is an array of hashes. In that case you could do

details.reject { |item| item[:qty].empty? }

The inner data structure itself is not an Array, but a Hash. You can also use select here, but the block is given the key and value in this case:

irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", 
    :qty2=>"1", :price=>"5,204.34 P"}

Or using reject, which is the inverse of select (excludes all items for which the given condition holds):

h.reject { |key, value| value.empty? }

Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:

Hash[h.reject { |key, value| value.empty? }]

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

AngularJS - Animate ng-view transitions

Angularjs 1.1.4 has now introduced the ng-animate directive to help animating different elements, in particular ng-view.

You can also watch the video about this new featue

UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I hit this error calling:

dict(my_data)

I fixed this with:

import json

json.loads(my_data)

Checking if a field contains a string

https://docs.mongodb.com/manual/reference/sql-comparison/

http://php.net/manual/en/mongo.sqltomongo.php

MySQL

SELECT * FROM users WHERE username LIKE "%Son%"

MongoDB

db.users.find({username:/Son/})

How to remove ASP.Net MVC Default HTTP Headers?

Check this blog Don't use code to remove headers. It is unstable according Microsoft

My take on this:

<system.webServer>          
    <httpProtocol>
    <!-- Security Hardening of HTTP response headers -->
    <customHeaders>
        <!--Sending the new X-Content-Type-Options response header with the value 'nosniff' will prevent 
                Internet Explorer from MIME-sniffing a response away from the declared content-type. -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- X-Frame-Options tells the browser whether you want to allow your site to be framed or not. 
                 By preventing a browser from framing your site you can defend against attacks like clickjacking. 
                 Recommended value "x-frame-options: SAMEORIGIN" -->
        <add name="X-Frame-Options" value="SAMEORIGIN" />

        <!-- Setting X-Permitted-Cross-Domain-Policies header to “master-only” will instruct Flash and PDF files that 
                 they should only read the master crossdomain.xml file from the root of the website. 
                 https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
        <add name="X-Permitted-Cross-Domain-Policies" value="master-only" />

        <!-- X-XSS-Protection sets the configuration for the cross-site scripting filter built into most browsers. 
                 Recommended value "X-XSS-Protection: 1; mode=block". -->
        <add name="X-Xss-Protection" value="1; mode=block" />

        <!-- Referrer-Policy allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites. 
                 If you have sensitive information in your URLs, you don't want to forward to other domains 
                 https://scotthelme.co.uk/a-new-security-header-referrer-policy/ -->
        <add name="Referrer-Policy" value="no-referrer-when-downgrade" />

        <!-- Remove x-powered-by in the response header, required by OWASP A5:2017 - Do not disclose web server configuration -->
        <remove name="X-Powered-By" />

        <!-- Ensure the cache-control is public, some browser won't set expiration without that  -->
        <add name="Cache-Control" value="public" />
    </customHeaders>
</httpProtocol>

<!-- Prerequisite for the <rewrite> section
            Install the URL Rewrite Module on the Web Server https://www.iis.net/downloads/microsoft/url-rewrite -->
<rewrite>
    <!-- Remove Server response headers (OWASP Security Measure) -->
    <outboundRules rewriteBeforeCache="true">
        <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />

            <!-- Use custom value for the Server info -->
            <action type="Rewrite" value="Your Custom Value Here." />
        </rule>
    </outboundRules>
</rewrite>
</system.webServer>

How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is BIT, though it allows NULL to be stored

ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';

Also there are other mistakes in your query

  1. When you alter a table to add column no need to mention column keyword in alter statement

  2. For adding default constraint no need to use SET keyword

  3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

Where does Oracle SQL Developer store connections?

For OS X my connection.xml files are in

/Users/<username>/.sqldeveloper/system<sqldeveloper_version>/o.jdeveloper.db.connection.<oracle_version?>/

html <input type="text" /> onchange event not working

Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

For static and dynamic inputs:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

jQuery post() with serialize and extra data

An alternative solution, in case you are needing to do this on an ajax file upload:

var data = new FormData( $('#form')[0] ).append( 'name' , value );

OR even simpler.

$('form').on('submit',function(e){

    e.preventDefault();
    var data = new FormData( this ).append('name', value );

    // ... your ajax code here ...

    return false;

});

javascript regular expression to check for IP addresses

And instead of

{1-3}

you should put

{1,3}

Interview question: Check if one string is a rotation of other string

Fist, make sure the 2 strings have the same length. Then in C, you can do this with a simple pointer iteration.


int is_rotation(char* s1, char* s2)
{
  char *tmp1;
  char *tmp2;
  char *ref2;

  assert(s1 && s2);
  if ((s1 == s2) || (strcmp(s1, s2) == 0))
    return (1);
  if (strlen(s1) != strlen(s2))
    return (0);

  while (*s2)
    {
      tmp1 = s1;
      if ((ref2 = strchr(s2, *s1)) == NULL)
        return (0);
      tmp2 = ref2;
      while (*tmp1 && (*tmp1 == *tmp2))
        {
          ++tmp1;
          ++tmp2;
          if (*tmp2 == '\0')
            tmp2 = s2;
        }
      if (*tmp1 == '\0')
        return (1);
      else
        ++s2;
    }
  return (0);
}

Find a class somewhere inside dozens of JAR files?

user1207523's script works fine for me. Here is a variant that searches for jar files recusively using find instead of simple expansion;

#!/bin/bash
for i in `find . -name '*.jar'`; do jar -tf "$i" | grep $1 | xargs -I{} echo -e "$i : {}" ; done

Make ABC Ordered List Items Have Bold Style

I know this question is a little old, but it still comes up first in a lot of Google searches. I wanted to add in a solution that doesn't involve editing the style sheet (in my case, I didn't have access):

_x000D_
_x000D_
<ol type="A">_x000D_
  <li style="font-weight: bold;">_x000D_
    <p><span style="font-weight: normal;">Text</span></p>_x000D_
  </li>_x000D_
  <li style="font-weight: bold;">_x000D_
    <p><span style="font-weight: normal;">More text</span></p>_x000D_
  </li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

How to make a new List in Java

One example:

List somelist = new ArrayList();

You can look at the javadoc for List and find all known implementing classes of the List interface that are included with the java api.

How do you add UI inside cells in a google spreadsheet using app script?

The apps UI only works for panels.

The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.

Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.

Alternatively you can also draw the button somewhere else and insert it as an image.

More info: https://developers.google.com/apps-script/guides/menus

enter image description here enter image description here enter image description here

Using Tempdata in ASP.NET MVC - Best practice

TempData is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.

To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.

Hope this helps.

How to detect if a browser is Chrome using jQuery?

As a quick addition, and I'm surprised nobody has thought of this, you could use the in operator:

"chrome" in window

Obviously this isn't using JQuery, but I figured I'd put it since it's handy for times when you aren't using any external libraries.

android pick images from gallery

For only pick from local add this :

        i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)

And this working nice :

    val i = Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    i.type = "image/*"
    i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
    startActivityForResult(Intent.createChooser(i,"Select Photo"),pickImageRequestCode)

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

Check string for nil & empty

SWIFT 3

extension Optional where Wrapped == String {

    /// Checks to see whether the optional string is nil or empty ("")
    public var isNilOrEmpty: Bool {
        if let text = self, !text.isEmpty { return false }
        return true
    }
}

Use like this on optional string:

if myString.isNilOrEmpty { print("Crap, how'd this happen?") } 

Get specific line from text file using just shell script

Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:

perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd

CSS / HTML Navigation and Logo on same line

Firstly, let's use some semantic HTML.

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Get in Touch</a></li>
    </ul>
</nav>

In fact, you can even get away with the more minimalist:

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <a href="#">Home</a>
    <a href="#">Projects</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Get in Touch</a>
</nav>

Then add some CSS:

.navigation-bar {
    width: 100%;  /* i'm assuming full width */
    height: 80px; /* change it to desired width */
    background-color: red; /* change to desired color */
}
.logo {
    display: inline-block;
    vertical-align: top;
    width: 50px;
    height: 50px;
    margin-right: 20px;
    margin-top: 15px;    /* if you want it vertically middle of the navbar. */
}
.navigation-bar > a {
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    height: 80px;        /* if you want it to take the full height of the bar */
    line-height: 80px;    /* if you want it vertically middle of the navbar */
}

Obviously, the actual margins, heights and line-heights etc. depend on your design.

Other options are to use tables or floats for layout, but these are generally frowned upon.

Last but not least, I hope you get cured of div-itis.

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

SELECT * 
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

WebView and Cookies on Android

My problem is cookies are not working "within" the same session. –

Burak: I had the same problem. Enabling cookies fixed the issue.

CookieManager.getInstance().setAcceptCookie(true);

MySql difference between two timestamps in days?

SELECT DATEDIFF( now(), '2013-06-20' );

here datediff takes two arguments 'upto-date', 'from-date'

What i have done is, using now() function, i can get no. of days since 20-june-2013 till today.

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

If you add this to your web.config transformation file, you can also set certain publish options to have debugging enabled or disabled:

<system.web>
    <customErrors mode="Off" defaultRedirect="~/Error.aspx" xdt:Transform="Replace"/>
</system.web>

How do I enable TODO/FIXME/XXX task tags in Eclipse?

I'm using Eclipse Classic 3.7.1.

The solution is: Window > Preferences > General > Editors > Sctructured Text Editors > Task Tags and checking "Enable searching for Task Tags" checkbox.

Where can I find a list of Mac virtual key codes?

Found an answer here.

So:

  • Command key is 55
  • Shift is 56
  • Caps Lock 57
  • Option is 58
  • Control is 59.

Messages Using Command prompt in Windows 7

Type "msg /?" in the command prompt to get various ways of sending meessages to a user.

Type "net send /?" in the command prompt to get another variation of sending messages across.

Print "hello world" every X seconds

This is the simple way to use thread in java:

for(int i = 0; i< 10; i++) {
    try {
        //sending the actual Thread of execution to sleep X milliseconds
        Thread.sleep(3000);
    } catch(Exception e) {
        System.out.println("Exception : "+e.getMessage());
    }
    System.out.println("Hello world!");
}

How to get named excel sheets while exporting from SSRS

To add tab names while exporting to excel, I used the following method:

  • On the report design window, select the tablix object.
  • Open properties window of the tablix object.
  • Add the required tab name to the PageName property.
  • Run the report
  • Export the report to Excel.
  • Now the worksheet name is the same as the PageName property of the tablix object.

How to get input textfield values when enter key is pressed in react js?

html

<input id="something" onkeyup="key_up(this)" type="text">

script

function key_up(e){
    var enterKey = 13; //Key Code for Enter Key
    if (e.which == enterKey){
        //Do you work here
    }
}

Next time, Please try providing some code.

How do I pre-populate a jQuery Datepicker textbox with today's date?

You've got 2 options:

OPTION A) Marks as "active" in your calendar, only when you click in the input.

Js:

$('input.datepicker').datepicker(
                        {   
                            changeMonth: false,
                            changeYear: false,
                            beforeShow: function(input, instance) { 
                                $(input).datepicker('setDate', new Date());
                            }
                        }                         
                     );

Css:

div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,
        div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active  {
            background: #1ABC9C;
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            display: inline-block;
            width: 24px; height: 24px;
        }?

OPTION B) Input by default with today. You've to populate first the datepicker .

$("input.datepicker").datepicker().datepicker("setDate", new Date());

Simple way to encode a string according to a password?

Python has no built-in encryption schemes, no. You also should take encrypted data storage serious; trivial encryption schemes that one developer understands to be insecure and a toy scheme may well be mistaken for a secure scheme by a less experienced developer. If you encrypt, encrypt properly.

You don’t need to do much work to implement a proper encryption scheme however. First of all, don’t re-invent the cryptography wheel, use a trusted cryptography library to handle this for you. For Python 3, that trusted library is cryptography.

I also recommend that encryption and decryption applies to bytes; encode text messages to bytes first; stringvalue.encode() encodes to UTF8, easily reverted again using bytesvalue.decode().

Last but not least, when encrypting and decrypting, we talk about keys, not passwords. A key should not be human memorable, it is something you store in a secret location but machine readable, whereas a password often can be human-readable and memorised. You can derive a key from a password, with a little care.

But for a web application or process running in a cluster without human attention to keep running it, you want to use a key. Passwords are for when only an end-user needs access to the specific information. Even then, you usually secure the application with a password, then exchange encrypted information using a key, perhaps one attached to the user account.

Symmetric key encryption

Fernet – AES CBC + HMAC, strongly recommended

The cryptography library includes the Fernet recipe, a best-practices recipe for using cryptography. Fernet is an open standard, with ready implementations in a wide range of programming languages and it packages AES CBC encryption for you with version information, a timestamp and an HMAC signature to prevent message tampering.

Fernet makes it very easy to encrypt and decrypt messages and keep you secure. It is the ideal method for encrypting data with a secret.

I recommend you use Fernet.generate_key() to generate a secure key. You can use a password too (next section), but a full 32-byte secret key (16 bytes to encrypt with, plus another 16 for the signature) is going to be more secure than most passwords you could think of.

The key that Fernet generates is a bytes object with URL and file safe base64 characters, so printable:

from cryptography.fernet import Fernet

key = Fernet.generate_key()  # store in a secure location
print("Key:", key.decode())

To encrypt or decrypt messages, create a Fernet() instance with the given key, and call the Fernet.encrypt() or Fernet.decrypt(), both the plaintext message to encrypt and the encrypted token are bytes objects.

encrypt() and decrypt() functions would look like:

from cryptography.fernet import Fernet

def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)

def decrypt(token: bytes, key: bytes) -> bytes:
    return Fernet(key).decrypt(token)

Demo:

>>> key = Fernet.generate_key()
>>> print(key.decode())
GZWKEhHGNopxRdOHS4H4IyKhLQ8lwnyU7vRLrM3sebY=
>>> message = 'John Doe'
>>> encrypt(message.encode(), key)
'gAAAAABciT3pFbbSihD_HZBZ8kqfAj94UhknamBuirZWKivWOukgKQ03qE2mcuvpuwCSuZ-X_Xkud0uWQLZ5e-aOwLC0Ccnepg=='
>>> token = _
>>> decrypt(token, key).decode()
'John Doe'

Fernet with password – key derived from password, weakens the security somewhat

You can use a password instead of a secret key, provided you use a strong key derivation method. You do then have to include the salt and the HMAC iteration count in the message, so the encrypted value is not Fernet-compatible anymore without first separating salt, count and Fernet token:

import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

backend = default_backend()
iterations = 100_000

def _derive_key(password: bytes, salt: bytes, iterations: int = iterations) -> bytes:
    """Derive a secret key from a given password and salt"""
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(), length=32, salt=salt,
        iterations=iterations, backend=backend)
    return b64e(kdf.derive(password))

def password_encrypt(message: bytes, password: str, iterations: int = iterations) -> bytes:
    salt = secrets.token_bytes(16)
    key = _derive_key(password.encode(), salt, iterations)
    return b64e(
        b'%b%b%b' % (
            salt,
            iterations.to_bytes(4, 'big'),
            b64d(Fernet(key).encrypt(message)),
        )
    )

def password_decrypt(token: bytes, password: str) -> bytes:
    decoded = b64d(token)
    salt, iter, token = decoded[:16], decoded[16:20], b64e(decoded[20:])
    iterations = int.from_bytes(iter, 'big')
    key = _derive_key(password.encode(), salt, iterations)
    return Fernet(key).decrypt(token)

Demo:

>>> message = 'John Doe'
>>> password = 'mypass'
>>> password_encrypt(message.encode(), password)
b'9Ljs-w8IRM3XT1NDBbSBuQABhqCAAAAAAFyJdhiCPXms2vQHO7o81xZJn5r8_PAtro8Qpw48kdKrq4vt-551BCUbcErb_GyYRz8SVsu8hxTXvvKOn9QdewRGDfwx'
>>> token = _
>>> password_decrypt(token, password).decode()
'John Doe'

Including the salt in the output makes it possible to use a random salt value, which in turn ensures the encrypted output is guaranteed to be fully random regardless of password reuse or message repetition. Including the iteration count ensures that you can adjust for CPU performance increases over time without losing the ability to decrypt older messages.

A password alone can be as safe as a Fernet 32-byte random key, provided you generate a properly random password from a similar size pool. 32 bytes gives you 256 ^ 32 number of keys, so if you use an alphabet of 74 characters (26 upper, 26 lower, 10 digits and 12 possible symbols), then your password should be at least math.ceil(math.log(256 ** 32, 74)) == 42 characters long. However, a well-selected larger number of HMAC iterations can mitigate the lack of entropy somewhat as this makes it much more expensive for an attacker to brute force their way in.

Just know that choosing a shorter but still reasonably secure password won’t cripple this scheme, it just reduces the number of possible values a brute-force attacker would have to search through; make sure to pick a strong enough password for your security requirements.

Alternatives

Obscuring

An alternative is not to encrypt. Don't be tempted to just use a low-security cipher, or a home-spun implementation of, say Vignere. There is no security in these approaches, but may give an inexperienced developer that is given the task to maintain your code in future the illusion of security, which is worse than no security at all.

If all you need is obscurity, just base64 the data; for URL-safe requirements, the base64.urlsafe_b64encode() function is fine. Don't use a password here, just encode and you are done. At most, add some compression (like zlib):

import zlib
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

def obscure(data: bytes) -> bytes:
    return b64e(zlib.compress(data, 9))

def unobscure(obscured: bytes) -> bytes:
    return zlib.decompress(b64d(obscured))

This turns b'Hello world!' into b'eNrzSM3JyVcozy_KSVEEAB0JBF4='.

Integrity only

If all you need is a way to make sure that the data can be trusted to be unaltered after having been sent to an untrusted client and received back, then you want to sign the data, you can use the hmac library for this with SHA1 (still considered secure for HMAC signing) or better:

import hmac
import hashlib

def sign(data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
    assert len(key) >= algorithm().digest_size, (
        "Key must be at least as long as the digest size of the "
        "hashing algorithm"
    )
    return hmac.new(key, data, algorithm).digest()

def verify(signature: bytes, data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
    expected = sign(data, key, algorithm)
    return hmac.compare_digest(expected, signature)

Use this to sign data, then attach the signature with the data and send that to the client. When you receive the data back, split data and signature and verify. I've set the default algorithm to SHA256, so you'll need a 32-byte key:

key = secrets.token_bytes(32)

You may want to look at the itsdangerous library, which packages this all up with serialisation and de-serialisation in various formats.

Using AES-GCM encryption to provide encryption and integrity

Fernet builds on AEC-CBC with a HMAC signature to ensure integrity of the encrypted data; a malicious attacker can't feed your system nonsense data to keep your service busy running in circles with bad input, because the ciphertext is signed.

The Galois / Counter mode block cipher produces ciphertext and a tag to serve the same purpose, so can be used to serve the same purposes. The downside is that unlike Fernet there is no easy-to-use one-size-fits-all recipe to reuse on other platforms. AES-GCM also doesn't use padding, so this encryption ciphertext matches the length of the input message (whereas Fernet / AES-CBC encrypts messages to blocks of fixed length, obscuring the message length somewhat).

AES256-GCM takes the usual 32 byte secret as a key:

key = secrets.token_bytes(32)

then use

import binascii, time
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.exceptions import InvalidTag

backend = default_backend()

def aes_gcm_encrypt(message: bytes, key: bytes) -> bytes:
    current_time = int(time.time()).to_bytes(8, 'big')
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.GCM(iv), backend=backend)
    encryptor = cipher.encryptor()
    encryptor.authenticate_additional_data(current_time)
    ciphertext = encryptor.update(message) + encryptor.finalize()        
    return b64e(current_time + iv + ciphertext + encryptor.tag)

def aes_gcm_decrypt(token: bytes, key: bytes, ttl=None) -> bytes:
    algorithm = algorithms.AES(key)
    try:
        data = b64d(token)
    except (TypeError, binascii.Error):
        raise InvalidToken
    timestamp, iv, tag = data[:8], data[8:algorithm.block_size // 8 + 8], data[-16:]
    if ttl is not None:
        current_time = int(time.time())
        time_encrypted, = int.from_bytes(data[:8], 'big')
        if time_encrypted + ttl < current_time or current_time + 60 < time_encrypted:
            # too old or created well before our current time + 1 h to account for clock skew
            raise InvalidToken
    cipher = Cipher(algorithm, modes.GCM(iv, tag), backend=backend)
    decryptor = cipher.decryptor()
    decryptor.authenticate_additional_data(timestamp)
    ciphertext = data[8 + len(iv):-16]
    return decryptor.update(ciphertext) + decryptor.finalize()

I've included a timestamp to support the same time-to-live use-cases that Fernet supports.

Other approaches on this page, in Python 3

AES CFB - like CBC but without the need to pad

This is the approach that All ?? V????y follows, albeit incorrectly. This is the cryptography version, but note that I include the IV in the ciphertext, it should not be stored as a global (reusing an IV weakens the security of the key, and storing it as a module global means it'll be re-generated the next Python invocation, rendering all ciphertext undecryptable):

import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_cfb_encrypt(message, key):
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(message) + encryptor.finalize()
    return b64e(iv + ciphertext)

def aes_cfb_decrypt(ciphertext, key):
    iv_ciphertext = b64d(ciphertext)
    algorithm = algorithms.AES(key)
    size = algorithm.block_size // 8
    iv, encrypted = iv_ciphertext[:size], iv_ciphertext[size:]
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    decryptor = cipher.decryptor()
    return decryptor.update(encrypted) + decryptor.finalize()

This lacks the added armoring of an HMAC signature and there is no timestamp; you’d have to add those yourself.

The above also illustrates how easy it is to combine basic cryptography building blocks incorrectly; All ?? V????y‘s incorrect handling of the IV value can lead to a data breach or all encrypted messages being unreadable because the IV is lost. Using Fernet instead protects you from such mistakes.

AES ECB – not secure

If you previously implemented AES ECB encryption and need to still support this in Python 3, you can do so still with cryptography too. The same caveats apply, ECB is not secure enough for real-life applications. Re-implementing that answer for Python 3, adding automatic handling of padding:

from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_ecb_encrypt(message, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(cipher.algorithm.block_size).padder()
    padded = padder.update(msg_text.encode()) + padder.finalize()
    return b64e(encryptor.update(padded) + encryptor.finalize())

def aes_ecb_decrypt(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
    padded = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
    return unpadder.update(padded) + unpadder.finalize()

Again, this lacks the HMAC signature, and you shouldn’t use ECB anyway. The above is there merely to illustrate that cryptography can handle the common cryptographic building blocks, even the ones you shouldn’t actually use.

WCF Service , how to increase the timeout?

Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.

WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();

or

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    //More codes here 
}

Bootstrap 4 - Responsive cards in card-columns

Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns element in very similar ways to columns with .col-4 or .col-lg-3:

@import "bootstrap";

$card-column-counts: 1, 2, 3, 4, 5;

.card-columns {
    @each $column-count in $card-column-counts {
        &.card-columns-#{$column-count} {
            column-count: $column-count;
        }
    }

    @each $breakpoint in map-keys($grid-breakpoints) {
        @include media-breakpoint-up($breakpoint) {
            $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
            @each $column-count in $card-column-counts {
                &.card-columns#{$infix}-#{$column-count} {
                    column-count: $column-count;
                }
            }
        }
    }
}

The end result of this is if you have the following:

<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
   ...
</div>

Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts can be overridden to change the allowed numbers of columns.

How to set time to midnight for current day?

Try this:

DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
   .AddSeconds(-DateTime.Now.Second);

Output will be like:

07/29/2015 00:00:00

Opening a CHM file produces: "navigation to the webpage was canceled"

There are apparently different levels of authentication. Most articles I read tell you to set the MaxAllowedZone to '1' which means that local machine zone and intranet zone are allowed but '4' allows access for 'all' zones.

For more info, read this article: https://support.microsoft.com/en-us/kb/892675

This is how my registry looks (I wasn't sure it would work with the wild cards but it seems to work for me):

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x]

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000004

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"UrlAllowList"="\\\\<network_path_root>;\\\\<network_path_root>\*;\\ies-inc.local;http://www.*;http://*;https://www.*;https://*;"

As an additional note, weirdly the "UrlAllowList" key was required to make this work on another PC but not my test one. It's probably not required at all but when I added it, it fixed the problem. The user may have not closed the original file or something like that. So just a consideration. I suggest try the least and test it, then add if needed. Once you confirm, you can deploy if needed. Good Luck!

Edit: P.S. Another method that worked was mapping the path to the network locally by using mklink /d (symbolic linking in Windows 7 or newer) but mapping a network drive letter (Z: for testing) did not work. Just food for thought and I did not have to 'Unblock' any files. Also the accepted 'Solution' did not resolve the issue for me.

How do I view / replay a chrome network debugger har file saved with content?

There is an HAR Viewer developed by Jan Odvarko that you can use. You either use the online version at

Or download the source-code at https://github.com/janodvarko/harviewer.

EDIT: Chrome 62 DevTools include HAR import functionality. https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports

React JS - Uncaught TypeError: this.props.data.map is not a function

More generally, you can also convert the new data into an array and use something like concat:

var newData = this.state.data.concat([data]);  
this.setState({data: newData})

This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.

How can I check the size of a file in a Windows batch script?

Just saw this old question looking to see if Windows had something built in. The ~z thing is something I didn't know about, but not applicable for me. I ended up with a Perl one-liner:

@echo off

set yourfile=output.txt
set maxsize=10000

perl -e "-s $ENV{yourfile} > $ENV{maxsize} ? exit 1 : exit 0"
rem if %errorlevel%. equ 1. goto abort
if errorlevel 1 goto abort

echo OK!
exit /b 0

:abort
echo Bad!
exit /b 1

Algorithm to detect overlapping periods

How about a custom interval-tree structure? You'll have to tweak it a little bit to define what it means for two intervals to "overlap" in your domain.

This question might help you find an off-the-shelf interval-tree implementation in C#.

if statements matching multiple values

Is this what you are looking for ?

if (new int[] { 1, 2, 3, 4, 5 }.Contains(value))

Installing and Running MongoDB on OSX

Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:

Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed

The easiest solution is to open the terminal and type

$ mongod --dbpath ~/data/db

Note: dbpath here is "Users/user" where data/db directories are created

i.e., you need to create directory data and sub directory db in your user folder. For e.g say `

/Users/johnny/data

After mongo db is up. Open another terminal in new window and type

$ mongo

it will open mongo shell with your mongo db connection opened in another terminal.

HttpClient.GetAsync(...) never returns when using await/async

You are misusing the API.

Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).

This is managed by the ASP.NET SynchronizationContext.

By default, when you await a Task, the method resumes on a captured SynchronizationContext (or a captured TaskScheduler, if there is no SynchronizationContext). Normally, this is just what you want: an asynchronous controller action will await something, and when it resumes, it resumes with the request context.

So, here's why test5 fails:

  • Test5Controller.Get executes AsyncAwait_GetSomeDataAsync (within the ASP.NET request context).
  • AsyncAwait_GetSomeDataAsync executes HttpClient.GetAsync (within the ASP.NET request context).
  • The HTTP request is sent out, and HttpClient.GetAsync returns an uncompleted Task.
  • AsyncAwait_GetSomeDataAsync awaits the Task; since it is not complete, AsyncAwait_GetSomeDataAsync returns an uncompleted Task.
  • Test5Controller.Get blocks the current thread until that Task completes.
  • The HTTP response comes in, and the Task returned by HttpClient.GetAsync is completed.
  • AsyncAwait_GetSomeDataAsync attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get.
  • Deadlock.

Here's why the other ones work:

  • (test1, test2, and test3): Continuations_GetSomeDataAsync schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task returned by Continuations_GetSomeDataAsync to complete without having to re-enter the request context.
  • (test4 and test6): Since the Task is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync to use the ASP.NET request context when it is ready to continue.

And here's the best practices:

  1. In your "library" async methods, use ConfigureAwait(false) whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  2. Don't block on Tasks; it's async all the way down. In other words, use await instead of GetResult (Task.Result and Task.Wait should also be replaced with await).

That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async (which doesn't block a request thread).

More information:

Update 2012-07-13: Incorporated this answer into a blog post.

How to map a composite key with JPA and Hibernate?

Looks like you are doing this from scratch. Try using available reverse engineering tools like Netbeans Entities from Database to at least get the basics automated (like embedded ids). This can become a huge headache if you have many tables. I suggest avoid reinventing the wheel and use as many tools available as possible to reduce coding to the minimum and most important part, what you intent to do.

nodejs npm global config missing on windows

Have you tried running npm config list? And, if you want to see the defaults, run npm config ls -l.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

For my scenario, I found that there was a identity node in the web.config file.

<identity impersonate="true" userName="blah" password="blah">

When I removed the userName and password parameters from node, it started working.

Another option might be that you need to make sure that the specified userName has access to work with those "Temporary ASP.NET Files" folders found in the various C:\Windows\Microsoft.NET\Framework{version} folders.

Hoping this helps someone else out!

jQuery Get Selected Option From Dropdown

For dropdown options you probably want something like this:

var conceptName = $('#aioConceptName').find(":selected").text();

The reason val() doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected property to the selected option which is a child of the dropdown.

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

"multiple target patterns" Makefile error

I had this problem (colons in the target name) because I had -n in my GREP_OPTIONS environment variable. Apparently, this caused configure to generate the Makefile incorrectly.

Rolling back bad changes with svn in Eclipse

If you want to do 1 file at a time you can go to the History view for the file assuming you have an Eclipse SVN plugin installed. "Team->Show History"

In the History view, find the last good version of that file, right click and choose "Get Contents". This will replace your current version with that version's contents. Then you can commit the changes when you've fixed it all up.

How do I generate a random int number?

The numbers generated by the inbuilt Random class (System.Random) generates pseudo random numbers.

If you want true random numbers, the closest we can get is "secure Pseudo Random Generator" which can be generated by using the Cryptographic classes in C# such as RNGCryptoServiceProvider.

Even so, if you still need true random numbers you will need to use an external source such as devices accounting for radioactive decay as a seed for an random number generator. Since, by definition, any number generated by purely algorithmic means cannot be truly random.

Set the value of an input field

document.getElementById("fieldId").value = "Value";

or

document.forms['formId']['fieldId'].value = "Value";

or

document.getElementById("fieldId").setAttribute('value','Value');

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I also encountered this exception with error message,

java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)

and found that some strange bug occurs when trying to use

BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath));

to write a String "orazg 54" cast from a generic type in a class.

//key is of generic type <Key extends Comparable<Key>>
writer.write(item.getKey() + "\t" + item.getValue() + "\n");

This String is of length 9 containing chars with the following code points:

111 114 97 122 103 9 53 52 10

However, if the BufferedWriter in the class is replaced with:

FileOutputStream outputStream = new FileOutputStream(filePath);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

it can successfully write this String without exceptions. In addition, if I write the same String create from the characters it still works OK.

String string = new String(new char[] {111, 114, 97, 122, 103, 9, 53, 52, 10});
BufferedWriter writer = Files.newBufferedWriter(Paths.get("a.txt"));
writer.write(string);
writer.close();

Previously I have never encountered any Exception when using the first BufferedWriter to write any Strings. It's a strange bug that occurs to BufferedWriter created from java.nio.file.Files.newBufferedWriter(path, options)

1 = false and 0 = true?

I suspect it's just following the Linux / Unix standard for returning 0 on success.

Does it really say "1" is false and "0" is true?

Call to a member function on a non-object

you can use 'use' in function like bellow example

function page_properties($objPortal) use($objPage){    
    $objPage->set_page_title($myrow['title']);
}

How do I iterate through lines in an external file with shell?

This might work for you:

cat <<\! >names.txt
> alison
> barb
> charlie
> david
> !
OIFS=$IFS; IFS=$'\n'; NAMES=($(<names.txt)); IFS=$OIFS
echo "${NAMES[@]}"
alison barb charlie david
echo "${NAMES[0]}"
alison
for NAME in "${NAMES[@]}";do echo $NAME;done
alison
barb
charlie
david

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Pass a PHP array to a JavaScript function

In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:

<script type="javascript">
    day = new Array(<?php echo implode(',', $day); ?>);
    week = new Array(<?php echo implode(',',$week); ?>);
    month = new Array(<?php echo implode(',',$month); ?>);

    <!--  Then pass it to the JavaScript function:   -->

    drawChart(<?php echo count($day); ?>, day, week, month);
</script>

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

Initialize static variables in C++ class?

Some answers seem to be a little misleading.

You don't have to ...

  • Assign a value to some static object when initializing, because assigning a value is Optional.
  • Create another .cpp file for initializing since it can be done in the same Header file.

Also, you can even initialize a static object in the same class scope just like a normal variable using the inline keyword.


Initialize with no values in the same file

#include <string>
class A
{
    static std::string str;
    static int x;
};
std::string A::str;
int A::x;

Initialize with values in the same file

#include <string>
class A
{
    static std::string str;
    static int x;
};
std::string A::str = "SO!";
int A::x = 900;

Initialize in the same class scope using the inline keyword

#include <string>
class A
{
    static inline std::string str = "SO!";
    static inline int x = 900;
};

Magento - How to add/remove links on my account navigation?

Most of the above work, but for me, this was the easiest.

Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.

http://www.magentocommerce.com/magento-connect/frontend-links-manager.html

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

Eclipse does not start when I run the exe?

I had a similar problem with Eclipse mars. It suddenly over the weekend stopped working and if you ran it from a command window (Windows x64) it would flash up a line or two and then stop.

I installed Eclipse neon yesterday and it worked, but today it stopped working and went wrong in the same way.

Just now I installed the JDK from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

I installed version 8u101 and then neon started. I have not changed eclipse.ini (although I had a look at it) nor have I deleted the plugins (I renamed the folder and found that this had no effect).

Hence I think this difficult to work out problem relates to the JDK/JRE. It would be nice if Eclipse gave a bit more information to go on, but such is life.

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

How can I get the iOS 7 default blue color programmatically?

Here is a simple method to get the default system tint color:

+ (UIColor*)defaultSystemTintColor
{
   static UIColor* systemTintColor = nil;
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
      UIView* view = [[UIView alloc] init];
      systemTintColor = view.tintColor;
   });
   return systemTintColor;
}

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

Adding an identity to an existing column

Right click on table name in Object Explorer. You will get some options. Click on 'Design'. A new tab will be opened for this table. You can add Identity constraint here in 'Column Properties'.

How to get the currently logged in user's user id in Django?

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>

How to use java.Set

Did you override equals and hashCode in the Block class?

EDIT:

I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

How do I "break" out of an if statement?

Have a label at a point you want to jump to and in side your if use goto

if(condition){
     if(jumpCondition) goto label
}
label:

Convert a string date into datetime in Oracle

You can use a cast to char to see the date results

_x000D_
_x000D_
 select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
_x000D_
_x000D_

How to add and remove classes in Javascript without jQuery

Add & Remove Classes (tested on IE8+)

Add trim() to IE (taken from: .trim() in JavaScript not working in IE)

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Add and Remove Classes:

function addClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {
    element.setAttribute("class",currentClassName + " "+ className);
  }
  else {
    element.setAttribute("class",className); 
  }
}
function removeClass(element,className) {
  var currentClassName = element.getAttribute("class");
  if (typeof currentClassName!== "undefined" && currentClassName) {

    var class2RemoveIndex = currentClassName.indexOf(className);
    if (class2RemoveIndex != -1) {
        var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
        var updatedClassName = currentClassName.replace(class2Remove,"").trim();
        element.setAttribute("class",updatedClassName);
    }
  }
  else {
    element.removeAttribute("class");   
  } 
}

Usage:

var targetElement = document.getElementById("myElement");

addClass(targetElement,"someClass");

removeClass(targetElement,"someClass");

A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

Casting a variable using a Type variable

Putting boxing and unboxing aside for simplicity, there's no specific runtime action involved in casting along the inheritance hierarchy. It's mostly a compile time thing. Essentially, a cast tells the compiler to treat the value of the variable as another type.

What you could do after the cast? You don't know the type, so you wouldn't be able to call any methods on it. There wouldn't be any special thing you could do. Specifically, it can be useful only if you know the possible types at compile time, cast it manually and handle each case separately with if statements:

if (type == typeof(int)) {
    int x = (int)obj;
    DoSomethingWithInt(x);
} else if (type == typeof(string)) {
    string s = (string)obj;
    DoSomethingWithString(s);
} // ...

Round a divided number in Bash

bash will not give you correct result of 3/2 since it doesn't do floating pt maths. you can use tools like awk

$ awk  'BEGIN { rounded = sprintf("%.0f", 3/2); print rounded }'
2

or bc

$ printf "%.0f" $(echo "scale=2;3/2" | bc)
2

How to Make A Chevron Arrow Using CSS?

Here's a different approach:

1) Use the multiplication character: &times; ×

2) Hide half of it with overflow:hidden

3) Then add a triangle as a pseudo element for the tip.

The advantage here is that no transforms are necessary. (It will work in IE8+)

FIDDLE

_x000D_
_x000D_
.arrow {_x000D_
  position: relative;_x000D_
}_x000D_
.arrow:before {_x000D_
  content: '×';_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  font-size: 240px;_x000D_
  font-weight: bold;_x000D_
  font-family: verdana;_x000D_
  width: 103px;_x000D_
  height: 151px;_x000D_
  overflow: hidden;_x000D_
  line-height: 117px;_x000D_
}_x000D_
.arrow:after {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  left: 101px;_x000D_
  top: 51px;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border-style: solid;_x000D_
  border-width: 25px 0 25px 24px;_x000D_
  border-color: transparent transparent transparent black;_x000D_
}
_x000D_
<div class="arrow"></div>
_x000D_
_x000D_
_x000D_

Pull request vs Merge request

There is a subtle difference in terms of conflict management. In case of conflicts, a pull request in Github will result in a merge commit on the destination branch. In Gitlab, when a conflict is found, the modifications made will be on a merge commit on the source branch.

See https://docs.gitlab.com/ee/user/project/merge_requests/resolve_conflicts.html

"GitLab resolves conflicts by creating a merge commit in the source branch that is not automatically merged into the target branch. This allows the merge commit to be reviewed and tested before the changes are merged, preventing unintended changes entering the target branch without review or breaking the build."

How do I use jQuery to redirect?

You forgot the HTTP part:

window.location.href = "http://example.com/Registration/Success/";

How to sort a list/tuple of lists/tuples by the element at a given index?

I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:

reverse = True

and the result will be as follows:

data.sort(key=lambda tup: tup[1], reverse=True)

T-SQL: Looping through an array of known values

What I do in this scenario is create a table variable to hold the Ids.

  Declare @Ids Table (id integer primary Key not null)
  Insert @Ids(id) values (4),(7),(12),(22),(19)

-- (or call another table valued function to generate this table)

Then loop based on the rows in this table

  Declare @Id Integer
  While exists (Select * From @Ids)
    Begin
      Select @Id = Min(id) from @Ids
      exec p_MyInnerProcedure @Id 
      Delete from @Ids Where id = @Id
    End

or...

  Declare @Id Integer = 0 -- assuming all Ids are > 0
  While exists (Select * From @Ids
                where id > @Id)
    Begin
      Select @Id = Min(id) 
      from @Ids Where id > @Id
      exec p_MyInnerProcedure @Id 
    End

Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.

Change tab bar item selected color in a storyboard

XCode 8.2, iOS 10, Swift 3: now there's an unselectedItemTintColor attribute for tabBar:

self.tabBar.unselectedItemTintColor = UIColor(red: 0/255.0, green: 200/255.0, blue: 0/255.0, alpha: 1.0)

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

Can grep show only words that match search pattern?

You could pipe your grep output into Perl like this:

grep "th" * | perl -n -e'while(/(\w*th\w*)/g) {print "$1\n"}'

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

What is the "-->" operator in C/C++?

This --> is not an operator at all. We have an operator like ->, but not like -->. It is just a wrong interpretation of while(x-- >0) which simply means x has the post decrement operator and this loop will run till it is greater than zero.

Another simple way of writing this code would be while(x--). The while loop will stop whenever it gets a false condition and here there is only one case, i.e., 0. So it will stop when the x value is decremented to zero.