Programs & Examples On #Browser cache

Browser caches are an instance of the optimization mechanism known as a cache. There is an HTML5 specification for a browser cache mechanism called Appcache.

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>

In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.

// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];   
for (i=0; i < cacheBust.length; i++){
     var el = document.createElement('script');
     el.src = cacheBust[i]+"?v=" + Math.random();
     document.getElementsByTagName('head')[0].appendChild(el);
}

Make page to tell browser not to cache/preserve input values

Basically, there are two ways to clear the cache:

<form autocomplete="off"></form>

or

$('#Textfiledid').attr('autocomplete', 'off');

How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</IfModule>

Disabling Chrome cache for website development

Until the bug is fixed you could use Clear Cache Chrome plugin and you can also set a keyboard shortcut for it.

After installing it, right click and go to options:

enter image description here

Check Automatically reload active tab after clearing data:

enter image description here

Select Everything for Time Period:

enter image description here

And then you can go to Menu => Tools => Extensions:

enter image description here

Click on keyboard shortcuts at the bottom:

enter image description here

And set your keyboard shortcut, for example Ctrl + Shift +R:

enter image description here

How do you cache an image in Javascript

as @Pointy said you don't cache images with javascript, the browser does that. so this may be what you are asking for and may not be... but you can preload images using javascript. By putting all of the images you want to preload into an array and putting all of the images in that array into hidden img elements, you effectively preload (or cache) the images.

var images = [
'/path/to/image1.png',
'/path/to/image2.png'
];

$(images).each(function() {
var image = $('<img />').attr('src', this);
});

Disable browser cache for entire ASP.NET website

UI

<%@ OutPutCache Location="None"%>
<%
    Response.Buffer = true;
    Response.Expires = -1;
    Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
    Response.CacheControl = "no-cache";
%>

Background

Context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
Response.Expires = -1;          
Response.Cache.SetNoStore();

Form/JavaScript not working on IE 11 with error DOM7011

I faced the same issue before. I cleared all the IE caches/browsing history/cookies & re-launch IE. It works after caches removed.

You may have a try. :)

AngularJS disable partial caching on dev machine

If you are talking about cache that is been used for caching of templates without reloading whole page, then you can empty it by something like:

.controller('mainCtrl', function($scope, $templateCache) {
  $scope.clearCache = function() { 
    $templateCache.removeAll();
  }
});

And in markup:

<button ng-click='clearCache()'>Clear cache</button>

And press this button to clear cache.

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


If the file you try to recover has Content-Encoding: gzip in the header section, and you are using linux (or as in my case, you have Cygwin installed) you can do the following:

  1. visit chrome://view-http-cache/ and click the page you want to recover
  2. copy the last (fourth) section of the page verbatim to a text file (say: a.txt)
  3. xxd -r a.txt| gzip -d

Note that other answers suggest passing -p option to xxd - I had troubles with that presumably because the fourth section of the cache is not in the "postscript plain hexdump style" but in a "default style".

It also does not seem necessary to replace double spaces with a single space, as chrome_xxd.py is doing (in case it is necessary you can use sed 's/ / /g' for that).

Prevent browser caching of AJAX call result

I use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond:

$.get('/getdata?_=' + new Date().getTime(), function(data) {
    console.log(data); 
});

Edit: This answer is several years old. It still works (hence I haven't deleted it), but there are better/cleaner ways of achieving this now. My preference is for this method, but this answer is also useful if you want to disable caching for every request during the lifetime of a page.

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

What's the difference between Cache-Control: max-age=0 and no-cache?

max-age=0

This is equivalent to clicking Refresh, which means, give me the latest copy unless I already have the latest copy.

no-cache

This is holding Shift while clicking Refresh, which means, just redo everything no matter what.

How to prevent Browser cache on Angular 2 site?

Found a way to do this, simply add a querystring to load your components, like so:

@Component({
  selector: 'some-component',
  templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
  styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})

This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:

new Date().toISOString() //2016-09-24T00:43:21.584Z

And substring some characters so that it will only change after an hour for example:

new Date().toISOString().substr(0,13) //2016-09-24T00

Hope this helps

How to prevent Browser cache for php site

try this

<?php

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

How to force a web browser NOT to cache images

You may write a proxy script for serving images - that's a bit more of work though. Something likes this:

HTML:

<img src="image.php?img=imageFile.jpg&some-random-number-262376" />

Script:

// PHP
if( isset( $_GET['img'] ) && is_file( IMG_PATH . $_GET['img'] ) ) {

  // read contents
  $f = open( IMG_PATH . $_GET['img'] );
  $img = $f.read();
  $f.close();

  // no-cache headers - complete set
  // these copied from [php.net/header][1], tested myself - works
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Some time in the past
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
  header("Cache-Control: no-store, no-cache, must-revalidate"); 
  header("Cache-Control: post-check=0, pre-check=0", false); 
  header("Pragma: no-cache"); 

  // image related headers
  header('Accept-Ranges: bytes');
  header('Content-Length: '.strlen( $img )); // How many bytes we're going to send
  header('Content-Type: image/jpeg'); // or image/png etc

  // actual image
  echo $img;
  exit();
}

Actually either no-cache headers or random number at image src should be sufficient, but since we want to be bullet proof..

Leverage browser caching, how on apache or .htaccess?

I was doing the same thing a couple days ago. Added this to my .htaccess file:

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif¦jpe?g¦png¦ico¦css¦js¦swf)$">
Header set Cache-Control "public"
</FilesMatch>

And now when I run google speed page, leverage browwer caching is no longer a high priority.

Hope this helps.

Stylesheet not updating

I ran into this problem too, a lot of people seem to recommend force reloading your page, which won't fix the issue in cases such as if you're running it on a server. I believe the optimal solution in this scenario is to timestamp your css.

  1. This is how I do it in my Django template:

<link rel="stylesheet" href="{% static 'home/radioStyles.css' %}?{% now 'U' %}" type="text/css"/>

Where adding ?{% now 'U' %} to the end of your css file would fix this issue.

  1. How you would do it with just CSS (hopefully someone edits this to a cleaner version, this looks a little janky but it does work, tested it):

<link rel="stylesheet" type="text/css" href="style.css?Wednesday 2nd February 2020 12PM" />

Where ?Wednesday 2nd February 2020 12PM (current date) seems to fix the issue, I also noticed just putting the time fixes it too.

How to force reloading a page when using browser back button?

An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:

Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

To show a new Form on click of a button in C#

This worked for me using it in a toolstrip menu:

 private void calculatorToolStripMenuItem_Click(object sender, EventArgs e)
 {
     calculator form = new calculator();
     form.Show(); // or form.ShowDialog(this);
 }

List<String> to ArrayList<String> conversion issue

Take a look at ArrayList#addAll(Collection)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behaviour of this call is undefined if the specified collection is this list, and this list is nonempty.)

So basically you could use

ArrayList<String> listOfStrings = new ArrayList<>(list.size());
listOfStrings.addAll(list);

How to convert a byte array to its numeric value (Java)?

Complete java converter code for all primitive types to/from arrays http://www.daniweb.com/code/snippet216874.html

Assign multiple values to array in C

Exactly, you nearly got it:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

HTML table sort

The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.

The basic process is:

  1. add a click handler to each table header
  2. the click handler notes the index of the column to be sorted
  3. the table is converted to an array of arrays (rows and cells)
  4. that array is sorted using javascript sort function
  5. the data from the sorted array is inserted back into the HTML table

The table should, of course, be nice HTML. Something like this...

<table>
 <thead>
  <tr><th>Name</th><th>Age</th></tr>
 </thead>
 <tbody>
  <tr><td>Sioned</td><td>62</td></tr>
  <tr><td>Dylan</td><td>37</td></tr>
  ...etc...
 </tbody>
</table>

So, first adding the click handlers...

const table = document.querySelector('table'); //get the table to be sorted

table.querySelectorAll('th') // get all the table header elements
  .forEach((element, columnNo)=>{ // add a click handler for each 
    element.addEventListener('click', event => {
        sortTable(table, columnNo); //call a function which sorts the table by a given column number
    })
  })

This won't work right now because the sortTable function which is called in the event handler doesn't exist.

Lets write it...

function sortTable(table, sortColumn){
  // get the data from the table cells
  const tableBody = table.querySelector('tbody')
  const tableData = table2data(tableBody);
  // sort the extracted data
  tableData.sort((a, b)=>{
    if(a[sortColumn] > b[sortColumn]){
      return 1;
    }
    return -1;
  })
  // put the sorted data back into the table
  data2table(tableBody, tableData);
}

So now we get to the meat of the problem, we need to make the functions table2data to get data out of the table, and data2table to put it back in once sorted.

Here they are ...

// this function gets data from the rows and cells 
// within an html tbody element
function table2data(tableBody){
  const tableData = []; // create the array that'll hold the data rows
  tableBody.querySelectorAll('tr')
    .forEach(row=>{  // for each table row...
      const rowData = [];  // make an array for that row
      row.querySelectorAll('td')  // for each cell in that row
        .forEach(cell=>{
          rowData.push(cell.innerText);  // add it to the row data
        })
      tableData.push(rowData);  // add the full row to the table data 
    });
  return tableData;
}

// this function puts data into an html tbody element
function data2table(tableBody, tableData){
  tableBody.querySelectorAll('tr') // for each table row...
    .forEach((row, i)=>{  
      const rowData = tableData[i]; // get the array for the row data
      row.querySelectorAll('td')  // for each table cell ...
        .forEach((cell, j)=>{
          cell.innerText = rowData[j]; // put the appropriate array element into the cell
        })
      tableData.push(rowData);
    });
}

And that should do it.

A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2" is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

CSS: How to align vertically a "label" and "input" inside a "div"?

Use padding on the div (top and bottom) and vertical-align:middle on the label and input.

example at http://jsfiddle.net/VLFeV/1/

FORCE INDEX in MySQL - where do I put it?

The syntax for index hints is documented here:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html

FORCE INDEX goes right after the table reference:

SELECT * FROM (
    SELECT owner_id,
           product_id,
           start_time,
           price,
           currency,
           name,
           closed,
           active,
           approved,
           deleted,
           creation_in_progress
    FROM db_products FORCE INDEX (products_start_time)
    ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
      AND resultstable.active = 1
      AND resultstable.approved = 1
      AND resultstable.deleted = 0
      AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC

WARNING:

If you're using ORDER BY before GROUP BY to get the latest entry per owner_id, you're using a nonstandard and undocumented behavior of MySQL to do that.

There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.

Search the tag for many explanations of better solutions for this type of query.

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

Can an Android Toast be longer than Toast.LENGTH_LONG?

If you need a long Toast, there's a practical alternative, but it requires your user to click on an OK button to make it go away. You can use an AlertDialog like this:

String message = "This is your message";
new AlertDialog.Builder(YourActivityName.this)
    .setTitle("Optional Title (you can omit this)")
    .setMessage(message)
    .setPositiveButton("ok", null)
    .show();

If you have a long message, chances are, you don't know how long it will take for your user to read the message, so sometimes it is a good idea to require your user to click on an OK button to continue. In my case, I use this technique when a user clicks on a help icon.

Use a content script to access the page context variables and functions

The only thing missing hidden from Rob W's excellent answer is how to communicate between the injected page script and the content script.

On the receiving side (either your content script or the injected page script) add an event listener:

document.addEventListener('yourCustomEvent', function (e) {
  var data = e.detail;
  console.log('received', data);
});

On the initiator side (content script or injected page script) send the event:

var data = {
  allowedTypes: 'those supported by structured cloning, see the list below',
  inShort: 'no DOM elements or classes/functions',
};

document.dispatchEvent(new CustomEvent('yourCustomEvent', { detail: data }));

Notes:

  • DOM messaging uses structured cloning algorithm, which can transfer only some types of data in addition to primitive values. It can't send class instances or functions or DOM elements.
  • In Firefox, to send an object (i.e. not a primitive value) from the content script to the page context you have to explicitly clone it into the target using cloneInto (a built-in function), otherwise it'll fail with a security violation error.

    document.dispatchEvent(new CustomEvent('yourCustomEvent', {
      detail: cloneInto(data, document.defaultView),
    }));
    

PHP: How do you determine every Nth iteration of a loop?

You can also do it without modulus. Just reset your counter when it matches.

if($counter == 2) { // matches every 3 iterations
   echo 'image-file';
   $counter = 0; 
}

Uncaught ReferenceError: function is not defined with onclick

Never use .onclick(), or similar attributes from a userscript! (It's also poor practice in a regular web page).

The reason is that userscripts operate in a sandbox ("isolated world"), and onclick operates in the target-page scope and cannot see any functions your script creates.

Always use addEventListener()Doc (or an equivalent library function, like jQuery .on()).

So instead of code like:

something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'


You would use:

something.outerHTML += '<input id="btnsave" ...>'

document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);

For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML like that, you destroy the previous event listeners!

Without refactoring your code much, you can pass data with data attributes. So use code like this:

for (i = 0; i < EmoteURLLines.length; i++) {
    if (checkIMG (EmoteURLLines[i])) {
        localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
        localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
        localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
        if (i == 0) {
            console.log (resetSlot ());
        }
        emoteTab[2].innerHTML  += '<span style="cursor:pointer;" id="' 
                                + EmoteNameLines[i] 
                                + '" data-usage="' + EmoteUsageLines[i] + '">'
                                + '<img src="' + EmoteURLLines[i] + '" /></span>'
                                ;
    } else {
        alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
    }
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
    targetSpans[J].addEventListener ("click", appendEmote, false);
}

Where appendEmote is like:

function appendEmote (zEvent) {
    //-- this and the parameter are special in event handlers.  see the linked doc.
    var emoteUsage  = this.getAttribute ("data-usage");
    shoutdata.value += emoteUsage;
}


WARNINGS:

  • Your code reuses the same id for several elements. Don't do this, it's invalid. A given ID should occur only once per page.
  • Every time you use .outerHTML or .innerHTML, you trash any event handlers on the affected nodes. If you use this method beware of that fact.

CASE in WHERE, SQL Server

.. ELSE a.Country ...

I suppose

mysql stored-procedure: out parameter

I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...

I don't know what since I called some procedures before successfully (but there where no out parameters)...

For this one I had entered

CALL my_sqrt(4,@out_value);
SELECT @out_value;

And it results with an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2

Strangely, if I write just:

CALL my_sqrt(4,@out_value); 

The result message is: "Query canceled"

I guess, for now I will use only terminal...

Webpack.config how to just copy the index.html to the dist folder

Option 1

In your index.js file (i.e. webpack entry) add a require to your index.html via file-loader plugin, e.g.:

require('file-loader?name=[name].[ext]!../index.html');

Once you build your project with webpack, index.html will be in the output folder.

Option 2

Use html-webpack-plugin to avoid having an index.html at all. Simply have webpack generate the file for you.

In this case if you want to keep your own index.html file as template, you may use this configuration:

{
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
}

See the docs for more information.

sort dict by value python

If you actually want to sort the dictionary instead of just obtaining a sorted list use collections.OrderedDict

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> data = {1: 'b', 2: 'a'}
>>> d = OrderedDict(sorted(data.items(), key=itemgetter(1)))
>>> d
OrderedDict([(2, 'a'), (1, 'b')])
>>> d.values()
['a', 'b']

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

Difference between Date(dateString) and new Date(dateString)

You're not getting an "invalid date" error. Rather, the value of temp is "Invalid Date".

Is your date string in a valid format? If you're using Firefox, check Date.parse

In Firefox javascript console:

>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000

I would try a different date string format.

Zebi, are you using Internet Explorer?

How to get image size (height & width) using JavaScript?

Before acquire element's attributes,the document page should be onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}

how to stop a running script in Matlab

One solution I adopted--for use with java code, but the concept is the same with mexFunctions, just messier--is to return a FutureValue and then loop while FutureValue.finished() or whatever returns true. The actual code executes in another thread/process. Wrapping a try,catch around that and a FutureValue.cancel() in the catch block works for me.

In the case of mex functions, you will need to return somesort of pointer (as an int) that points to a struct/object that has all the data you need (native thread handler, bool for complete etc). In the case of a built in mexFunction, your mexFunction will most likely need to call that mexFunction in the separate thread. Mex functions are just DLLs/shared objects after all.

PseudoCode

FV = mexLongProcessInAnotherThread();
try
  while ~mexIsDone(FV);
    java.lang.Thread.sleep(100); %pause has a memory leak
    drawnow; %allow stdout/err from mex to display in command window
  end
catch
  mexCancel(FV);
end

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

jQuery javascript regex Replace <br> with \n

Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:

<textarea id="ta0"></textarea>
<button onclick="
  var ta = document.getElementById('ta0');
  var text = 'some<br>text<br />to<br/>replace';
  var re = /<br *\/?>/gi;
  ta.value = text.replace(re, '\n');
">Add stuff to text area</button>

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

How to change identity column values programmatically?

If you need to change the IDs occasionally, it's probably best not to use an identity column. In the past we've implemented autonumber fields manually using a 'Counters' table that tracks the next ID for each table. IIRC we did this because identity columns were causing database corruption in SQL2000 but being able to change IDs was occasionally useful for testing.

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

How to simulate a click with JavaScript?

Here's what I cooked up. It's pretty simple, but it works:

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

Usage:

eventFire(document.getElementById('mytest1'), 'click');

Creating a mock HttpServletRequest out of a url string?

You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.

In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

Pretty printing XML with javascript

All of the javascript functions given here won't work for an xml document having unspecified white spaces between the end tag '>' and the start tag '<'. To fix them, you just need to replace the first line in the functions

var reg = /(>)(<)(\/*)/g;

by

var reg = /(>)\s*(<)(\/*)/g;

CSV file written with Python has blank lines between each row

with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

The "lineterminator='\r'" permit to pass to next row, without empty row between two.

How to avoid "Permission denied" when using pip with virtualenv

I've also had this happen (by accident) after creating a new venv while inside an existing virtual environment. an easy way to diagnose this would be to see where the python is symlinked to, i.e. run:

ls -l venv/bin/python

and make sure it points to the appropriate Python binary. For most systems this will be /usr/bin/python or /usr/bin/python3. while if it points to an existing virtual environment it'll be something like /home/youruser/somedir/bin/python. if it's the latter than I'd suggest recreating the venv while making sure that you aren't "inside" any existing virtualenv (i.e. run deactivate )

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

Dependencies vs dev dependencies

Dev dependencies are modules which are only required during development whereas dependencies are required at runtime. If you are deploying your application, dependencies has to be installed, or else your app simply will not work. Libraries that you call from your code that enables the program to run can be considered as dependencies.

Eg- React , React - dom

Dev dependency modules need not be installed in the production server since you are not gonna develop in that machine .compilers that covert your code to javascript , test frameworks and document generators can be considered as dev-dependencies since they are only required during development .

Eg- ESLint , Babel , webpack

@FYI,

mod-a
  dev-dependents:
    - mod-b
  dependents:
    - mod-c

mod-d
?  dev-dependents:
    - mod-e
  dependents:
    - mod-a

----

npm install mod-d

installed modules:
  - mod-d
  - mod-a
  - mod-c

----

checkout the mod-d code repository

npm install

installed modules:
  - mod-a
  - mod-c
  - mod-e

If you are publishing to npm, then it is important that you use the correct flag for the correct modules. If it is something that your npm module needs to function, then use the "--save" flag to save the module as a dependency. If it is something that your module doesn't need to function but it is needed for testing, then use the "--save-dev" flag.

# For dependent modules
?npm install dependent-module --save

?# For dev-dependent modules
np?m install development-module --save-dev

Android - set TextView TextStyle programmatically?

I´ve resolved it with two simple methods.

Follow the explanation.

My existing style declaration:

<style name="SearchInfoText">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textSize">24sp</item>
    <item name="android:textColor">@color/Church_Grey</item>
    <item name="android:shadowColor">@color/Shadow_Church</item>
    <item name="android:shadowRadius">3</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
</style>

My Android Java code:

    TextView locationName = new TextView(getSupportActivity());
    locationName.setId(IdGenerator.generateViewId());
    locationName.setText(location.getName());
    locationName.setLayoutParams(super.centerHorizontal());
    locationName.setTextSize(24f);
    locationName.setPadding(0, 0, 0, 15);
    locationName.setTextColor(getResources().getColor(R.color.Church_Grey));
    locationName.setShadowLayer(3, 1, 1,  getResources().getColor(R.color.Shadow_Church));

Regards.

Cleanest Way to Invoke Cross-Thread Events

As an interesting side note, WPF's binding handles marshaling automatically so you can bind the UI to object properties that are modified on background threads without having to do anything special. This has proven to be a great timesaver for me.

In XAML:

<TextBox Text="{Binding Path=Name}"/>

How to make remote REST call inside Node.js? any CURL?

I found superagent to be really useful, it is very simple for example

const superagent=require('superagent')
superagent
.get('google.com')
.set('Authorization','Authorization object')
.set('Accept','application/json')

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

Overlay a background-image with an rgba background-color

_x000D_
_x000D_
/* Working method */_x000D_
.tinted-image {_x000D_
  background: _x000D_
    /* top, transparent red, faked with gradient */ _x000D_
    linear-gradient(_x000D_
      rgba(255, 0, 0, 0.45), _x000D_
      rgba(255, 0, 0, 0.45)_x000D_
    ),_x000D_
    /* bottom, image */_x000D_
    url(https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg);_x000D_
    height: 1280px;_x000D_
    width: 960px;_x000D_
    background-size: cover;_x000D_
}_x000D_
_x000D_
.tinted-image p {_x000D_
    color: #fff;_x000D_
    padding: 100px;_x000D_
  }
_x000D_
<div class="tinted-image">_x000D_
  _x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam distinctio, temporibus tempora a eveniet quas  qui veritatis sunt perferendis harum!</p>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

source: https://css-tricks.com/tinted-images-multiple-backgrounds/

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

Vim: faster way to select blocks of text in visual mode

v35G will select everything from the cursor up to line 35.

v puts you in select mode, 35 specifies the line number that you want to G go to.

You could also use v} which will select everything up to the beginning of the next paragraph.

Code not running in IE 11, works fine in Chrome

I also recently faced the prob. I solved using ^ which is similar to startwith in jquery. Say,

var str = array[a].id;
if (str.startsWith('REP')) {..........}

we can use

if($("[id^=str]").length){..........}

Here, str is id of element.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

Which sort algorithm works best on mostly sorted data?

If you are in need of specific implementation for sorting algorithms, data structures or anything that have a link to the above, could I recommend you the excellent "Data Structures and Algorithms" project on CodePlex?

It will have everything you need without reinventing the wheel.

Just my little grain of salt.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

try this...    
<script type="text/javascript">
    function test(){
    var av=document.getElementById("mytext").value;
    alert(av);
    }
    </script>

    <input type="text" value="" id="mytext">
    <input type="button" onclick="test()" value="go" />

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

Checked/Valid example for:

  • multiple file inputs
  • for one or MULTIPLE FILES upload - $.grep() to remove files from array with errors
  • image and audio format
  • dynamic file types from string by new RegExp()

Notice: acceptFileTypes.test() - check mime types, for adio file like .mp3 it will be audio/mpeg - not only extenstion. For all blueimp options: https://github.com/blueimp/jQuery-File-Upload/wiki/Options

$('input[type="file"]').each(function(i){

    // .form_files is my div/section of form for input file and progressbar
    var $progressbar = $(this).parents('.form_files:first').find('.progress-bar:first');

    var $image_format = 'jpg|jpeg|jpe|png|gif';
    var $audio_format = 'mp3|mpeg';
    var $all_formats = $image_format + '|' + $audio_format;

    var $image_size = 2;
    var $audio_size = 10;
    var mb = 1048576;

    $(this).fileupload({
        // ...
        singleFileUploads: false,   // << send all together, not single
        // ...
        add: function (e, data) {

            // array with all indexes of files with errors
            var error_uploads_indexes = [];

            // when add file - each file
            $.each(data.files, function(index, file) {

                // array for all errors
                var uploadErrors = [];


                // validate all formats first
                if($all_formats){

                    // check all formats first - before size
                    var acceptFileTypes = "(\.|\/)(" + $all_formats + ")$";
                    acceptFileTypes = new RegExp(acceptFileTypes, "i");

                    // when wrong format
                    if(data.files[index]['type'].length && !acceptFileTypes.test(data.files[index]['type'])) {
                        uploadErrors.push('Not an accepted file type');

                    }else{

                        // default size is image_size
                        var $my_size = $image_size;

                            // check audio format
                            var acceptFileTypes = "(\.|\/)(" + $audio_format + ")$";
                            acceptFileTypes = new RegExp(acceptFileTypes, "i");

                            // alert(data.files[index]['type']);
                            // alert(acceptFileTypes.test('audio/mpeg'));

                            // if is audio then size is audio_size
                            if(data.files[index]['type'].length && acceptFileTypes.test(data.files[index]['type'])) {
                                $my_size = $audio_size;
                            }

                        // check size
                        if(data.files[index]['size'] > $my_size * mb) {
                            uploadErrors.push('Filesize is too big');
                        };
                    };

                }; // << all_formats

                // when errors
                if(uploadErrors.length > 0) {
                    //  alert(uploadErrors.join("\n"));

                    // mark index of error file
                    error_uploads_indexes.push(index);
                    // alert error
                    alert(uploadErrors.join("\n"));

                };

            }); // << each


            // remove indexes (files) with error
            data.files = $.grep( data.files, function( n, i ) {
                return $.inArray(i, error_uploads_indexes) ==-1;
            });


            // if are files to upload
            if(data.files.length){
                // upload by ajax
                var jqXHR = data.submit().done(function (result, textStatus, jqXHR) {
                        //...
                     alert('done!') ;
                        // ...
                });
            } // 

        }, // << add
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $progressbar.css(
                'width',
                progress + '%'
                );
        }
    }); // << file_upload

    //          
}); // << each input file

Datatables Select All Checkbox

You can use this option provided by dataTable itself using buttons.

dom: 'Bfrtip',
 buttons: [
      'selectAll',
      'selectNone'
 ]'

Here is a sample code

var tableFaculty = $('#tableFaculty').DataTable({
    "columns": [
        {
            data: function (row, type, set) {
                return '';
            }
        },
        {data: "NAME"}
    ],
    "columnDefs": [
        {
            orderable: false,
            className: 'select-checkbox',
            targets: 0
        }
    ],
    select: {
        style: 'multi',
        selector: 'td:first-child'
    },
    dom: 'Bfrtip',
    buttons: [
        'selectAll',
        'selectNone'
    ],
    "order": [[0, 'desc']]
});

Using Custom Domains With IIS Express

For Visual Studio 2015 the steps in the above answers apply but the applicationhost.config file is in a new location. In your "solution" folder follow the path, this is confusing if you upgraded and would have TWO versions of applicationhost.config on your machine.

\.vs\config

Within that folder you will see your applicationhost.config file

Alternatively you could just search your solution folder for the .config file and find it that way.

I personally used the following configuration:

enter image description here

With the following in my hosts file:

127.0.0.1       jam.net
127.0.0.1       www.jam.net

And the following in my applicationhost.config file:

<site name="JBN.Site" id="2">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="C:\Dev\Jam\shoppingcart\src\Web\JBN.Site" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation="*:49707:" />
            <binding protocol="http" bindingInformation="*:49707:localhost" /> 
    </bindings>
</site>

Remember to run your instance of visual studio 2015 as an administrator! If you don't want to do this every time I recomend this:

How to Run Visual Studio as Administrator by default

I hope this helps somebody, I had issues when trying to upgrade to visual studio 2015 and realized that none of my configurations were being carried over.

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

This worked for me, I have an spring boot project that compiles in Java 8 but I don't know why one day my maven started compiling with Java 11, in Ubuntu I used to fix it:

sudo update-java-alternatives  -l

That showed me the availave JDK on my pc:

java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.8.0-openjdk-amd64       1081       /usr/lib/jvm/java-1.8.0-openjdk-amd64`

So I finally run this command to choose the desired one:

sudo update-java-alternatives  -s java-1.8.0-openjdk-amd64 

And that's it, for more into take a look at How to use the command update alternatives

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

How to use orderby with 2 fields in linq?

If you have two or more field to order try this:

var soterdList = initialList.OrderBy(x => x.Priority).
                                    ThenBy(x => x.ArrivalDate).
                                    ThenBy(x => x.ShipDate);

You can add other fields with clasole "ThenBy"

Converting between java.time.LocalDateTime and java.util.Date

Here is what I came up with ( and like all Date Time conundrums it is probably going to be disproved based on some weird timezone-leapyear-daylight adjustment :D )

Round-tripping: Date <<->> LocalDateTime

Given: Date date = [some date]

(1) LocalDateTime << Instant<< Date

    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

(2) Date << Instant << LocalDateTime

    Instant instant = ldt.toInstant(ZoneOffset.UTC);
    Date date = Date.from(instant);

Example:

Given:

Date date = new Date();
System.out.println(date + " long: " + date.getTime());

(1) LocalDateTime << Instant<< Date:

Create Instant from Date:

Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("Instant from Date:\n" + instant);

Create Date from Instant (not necessary,but for illustration):

date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());

Create LocalDateTime from Instant

LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
System.out.println("LocalDateTime from Instant:\n" + ldt);

(2) Date << Instant << LocalDateTime

Create Instant from LocalDateTime:

instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println("Instant from LocalDateTime:\n" + instant);

Create Date from Instant:

date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());

The output is:

Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574

Instant from Date:
2013-11-01T14:13:04.574Z

Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574

LocalDateTime from Instant:
2013-11-01T14:13:04.574

Instant from LocalDateTime:
2013-11-01T14:13:04.574Z

Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

Can I run a 64-bit VMware image on a 32-bit machine?

The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website.

You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.

Formatting doubles for output in C#

Use

Console.WriteLine(String.Format("  {0:G17}", i));

That will give you all the 17 digits it have. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. {0:R} will not always give you 17 digits, it will give 15 if the number can be represented with that precision.

which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision. There isn't any thing you can to do to make the the double return more digits that is the way it's implemented. If you don't like it do a new double class yourself...

.NET's double cant store any more digits than 17 so you cant see 6.89999999999999946709 in the debugger you would see 6.8999999999999995. Please provide an image to prove us wrong.

width:auto for <input> fields

As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.

There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.

First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:

input {
  width: 98%;
  padding: 1%;
}

Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:

<fieldset>
    <input type="text" />
</fieldset>

And this CSS:

fieldset {
  position: relative;
}

input {
    position: absolute;
    left: 0;
    right: 0;
}

This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.

Other than this there are some JS solutions, but I don't like applying basic styling with JS.

Build Error - missing required architecture i386 in file

Though it is possible that something got deleted, it has been my experience that something gets screwed up in the project file. I have yet to pin down what that "something" is. I've had similar issues when the SDK installation is just fine. There are a couple of options.

First, add all of your files to a new project. This seems to usually work. Kind of a pain, though.

Second, you can right-click project in XCode/Get Info/Build/Library Search Paths. Add new paths similar to /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.sdk/usr/lib. Add appropriate versions of that string for each version (2.2.1, etc) and platform (simulator or iPhoneOS). Perform a similar action for Framework Search Paths if frameworks are your problem.

Third, which is more work but more reliable, is to open project.pbxproj from within MyProject.xcodeproj (Textmate is good for this). Look for "/* Begin XCBuildConfiguration section */", then "LIBRARY_SEARCH_PATHS" and "FRAMEWORK_SEARCH_PATHS". Add or modify the paths as appropriate, and save the file.

In any case, a pain in the butt, and I'd sure like to pin-point the cause because I've had this happen a couple of times. Project builds fine, then just up and refuses to do so with what seems to be little reason.

How to hide a div element depending on Model value? MVC

Try:

<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>

Use the "Display" style attribute with your bool model attribute to define the div's visibility.

Notepad++ cached files location

I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

CSS opacity only to background color, not the text on it?

This will work with every browser

div {
    -khtml-opacity: .50;
    -moz-opacity: .50;
    -ms-filter: ”alpha(opacity=50)”;
    filter: alpha(opacity=50);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
    opacity: .50;
}

If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent to achieve this. CSS Opacity That Doesn’t Affect Child Elements

Check a working demo at CSS Opacity That Doesn't Affect "Children"

Why doesn't the Scanner class have a nextChar method?

I would imagine that it has to do with encoding. A char is 16 bytes and some encodings will use one byte for a character whereas another will use two or even more. When Java was originally designed, they assumed that any Unicode character would fit in 2 bytes, whereas now a Unicode character can require up to 4 bytes (UTF-32). There is no way for Scanner to represent a UTF-32 codepoint in a single char.

You can specify an encoding to Scanner when you construct an instance, and if not provided, it will use the platform character-set. But this still doesn't handle the issue with 3 or 4 byte Unicode characters, since they cannot be represented as a single char primitive (since char is only 16 bytes). So you would end up getting inconsistent results.

background-image: url("images/plaid.jpg") no-repeat; wont show up

You either use :

background-image: url("images/plaid.jpg");
background-repeat: no-repeat;

... or

background: transparent url("images/plaid.jpg") top left no-repeat;

... but definitively not

background-image: url("images/plaid.jpg") no-repeat;

EDIT : Demo at JSFIDDLE using absolute paths (in case you have troubles referring to your images with relative paths).

Error while sending QUERY packet

Had such a problem when executing forking in php for command line. In my case from time to time the php killed the child process. To fix this, just wait for the process to complete using the command pcntl_wait($status);

here's a piece of code for a visual example:

    #!/bin/php -n
    <?php
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set("log_errors", 1);
    ini_set('error_log', '/media/logs/php/fork.log');
    $ski = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
    error_log(getmypid().' '.$ski.' start my php');

    $pid = pcntl_fork();
    if($pid) {
    error_log(getmypid().' '.$ski.' start 2');
    // Wait for children to return. Otherwise they 
    // would turn into "Zombie" processes
    // !!!!!! add this !!!!!!
    pcntl_wait($status);
    // !!!!!! add this !!!!!!
    } else {
    error_log(getmypid().' '.$ski.' start 3');
    //[03-Apr-2020 12:13:47 UTC] PHP Warning:  Error while sending QUERY packet. PID=18048 in /speed/sport/fortest.php on line 22457
    mysqli_query($con,$query,MYSQLI_ASYNC);
error_log(getmypid().' '.$ski.' sleep child');
  sleep(15);
    exit;
    } 

   error_log(getmypid().' '.$ski.'end my php');
    exit(0);
    ?>

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

So I was running into the same thing. I tried the timeout solution which worked but not reliably. I found that if you just call it twice the location is refreshed properly

function getLocation(callback)
{   
    if(navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(function(position)
        {
            navigator.geolocation.getCurrentPosition(callback, function(){},{maximumAge:0, timeout:10000});
        },function(){}, {maximumAge:0, timeout:10000});
    }
    return true;
}

this of course is a little slower but I have not had it give me the wrong position once. I have had it hit the timeout a few times and not return anything but other then that it works great. I know this is still a little hacky and I am looking forward to someone finding the real solution.

Or if you want to make sure it is going to keep trying until you want to give up you could try something like this.

//example
$(document).ready(function(){
    getLocation(function(position){
        //do something cool with position
        console.log(position);
    });
});


var GPSTimeout = 10; //init global var NOTE: I noticed that 10 gives me the quickest result but play around with this number to your own liking


//function to be called where you want the location with the callback(position)
function getLocation(callback)
{   
    if(navigator.geolocation)
    {
        var clickedTime = (new Date()).getTime(); //get the current time
        GPSTimeout = 10; //reset the timeout just in case you call it more then once
        ensurePosition(callback, clickedTime); //call recursive function to get position
    }
    return true;
}

//recursive position function
function ensurePosition(callback, timestamp)
{
    if(GPSTimeout < 6000)//set at what point you want to just give up
    {
        //call the geolocation function
        navigator.geolocation.getCurrentPosition(
            function(position) //on success
        {
                //if the timestamp that is returned minus the time that was set when called is greater then 0 the position is up to date
            if(position.timestamp - timestamp >= 0)
                {
                    GPSTimeout = 10; //reset timeout just in case
                    callback(position); //call the callback function you created
                }
                else //the gps that was returned is not current and needs to be refreshed
                {
                    GPSTimeout += GPSTimeout; //increase the timeout by itself n*2
                    ensurePosition(callback, timestamp); //call itself to refresh
                }
            },
            function() //error: gps failed so we will try again
            {
                GPSTimeout += GPSTimeout; //increase the timeout by itself n*2
                ensurePosition(callback, timestamp);//call itself to try again
            },
            {maximumAge:0, timeout:GPSTimeout}
        )
    }       
}

I probably have some typeos and some spelling errors in here but I hope you get the idea. Let me know if anyone has questions or if someone finds something better.

Updating Anaconda fails: Environment Not Writable Error

In my case somehow CONDA_ENVS_PATH was removed, so I was having NotWritableError. So I fixed the error by specifying

CONDA_ENVS_PATH=~/my-envs:/opt/anaconda/envs

in the .bashrc file

Laravel Eloquent - distinct() and count() not working properly together

This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()

Decompile Python 2.7 .pyc

Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc

For example:

git clone https://github.com/zrax/pycdc   
cd pycdc
make  
./bin/pycdc Example.pyc > Example.py

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

For C# projects, the target of x86 does what it sounds like. It says that this assembly only supports x86 architectures. Likewise for x64. Any CPU on the other hand says that I don't care which architecture, I support both. So, the next 2 questions are (1) what is the configuration of the executable that uses these dlls? and (2) what is the bitness of your OS/Computer? The reason I ask is because if your executable is compiled to run in 64-bit, then it NEEDS all dependencies to be able to run in 64-bit mode as well. Your Any CPU assembly should be able to be loaded, but perhaps it is referencing some other dependency that is only capable of running in x86 configuration. Check all dependencies and dependencies-of-dependencies to make sure everything is either "Any CPU" or "x64" if you plan to run the executable in 64-bit mode. Otherwise, you'll have issues.

In many ways, Visual Studio does not make compiling a mixture of Any CPU and various architecture dependent assemblies easy. It is doable, but it often requires that an assembly that would otherwise be "Any CPU" to have to be compiled separately for x86 and x64 because some dependency-of-a-dependency somewhere has two versions.

Multi-line bash commands in makefile

As indicated in the question, every sub-command is run in its own shell. This makes writing non-trivial shell scripts a little bit messy -- but it is possible! The solution is to consolidate your script into what make will consider a single sub-command (a single line).

Tips for writing shell scripts within makefiles:

  1. Escape the script's use of $ by replacing with $$
  2. Convert the script to work as a single line by inserting ; between commands
  3. If you want to write the script on multiple lines, escape end-of-line with \
  4. Optionally start with set -e to match make's provision to abort on sub-command failure
  5. This is totally optional, but you could bracket the script with () or {} to emphasize the cohesiveness of a multiple line sequence -- that this is not a typical makefile command sequence

Here's an example inspired by the OP:

mytarget:
    { \
    set -e ;\
    msg="header:" ;\
    for i in $$(seq 1 3) ; do msg="$$msg pre_$${i}_post" ; done ;\
    msg="$$msg :footer" ;\
    echo msg=$$msg ;\
    }

How to serve an image using nodejs

This method works for me, it's not dynamic but straight to the point:

const fs      = require('fs');
const express = require('express');
const app     = express();

app.get( '/logo.gif', function( req, res ) {

  fs.readFile( 'logo.gif', function( err, data ) {

    if ( err ) {

      console.log( err );
      return;
    }

    res.write( data );
    return res.end();
  });

});

app.listen( 80 );

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

How do I update Anaconda?

If you have trouble to get e.g. from 3.3.x to 4.x (conda update conda "does not work" to get to the next version) than try it more specific like so:

conda install conda=4.0 (or conda install anaconda=4.0)

https://www.anaconda.com/blog/developer-blog/anaconda-4-release/

You should know what you do, because conda could break due to the forced installation. If you would like to get more flexibility/security you could use pkg-manager like nix(-pkgs) [with nix-shell] / NixOS.

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

How do I get client IP address in ASP.NET CORE?

Some fallback logic can be added to handle the presence of a Load Balancer.

Also, through inspection, the X-Forwarded-For header happens to be set anyway even without a Load Balancer (possibly because of additional Kestrel layer?):

public string GetRequestIP(bool tryUseXForwardHeader = true)
{
    string ip = null;

    // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For

    // X-Forwarded-For (csv list):  Using the First entry in the list seems to work
    // for 99% of cases however it has been suggested that a better (although tedious)
    // approach might be to read each IP from right to left and use the first public IP.
    // http://stackoverflow.com/a/43554000/538763
    //
    if (tryUseXForwardHeader)
        ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();

    // RemoteIpAddress is always null in DNX RC1 Update1 (bug).
    if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null)
        ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

    if (ip.IsNullOrWhitespace())
        ip = GetHeaderValueAs<string>("REMOTE_ADDR");

    // _httpContextAccessor.HttpContext?.Request?.Host this is the local host.

    if (ip.IsNullOrWhitespace())
        throw new Exception("Unable to determine caller's IP.");

    return ip;
}

public T GetHeaderValueAs<T>(string headerName)
{
    StringValues values;

    if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
    {
        string rawValues = values.ToString();   // writes out as Csv when there are multiple.

        if (!rawValues.IsNullOrWhitespace())
            return (T)Convert.ChangeType(values.ToString(), typeof(T));
    }
    return default(T);
}

public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
    if (string.IsNullOrWhiteSpace(csvList))
        return nullOrWhitespaceInputReturnsNull ? null : new List<string>();

    return csvList
        .TrimEnd(',')
        .Split(',')
        .AsEnumerable<string>()
        .Select(s => s.Trim())
        .ToList();
}

public static bool IsNullOrWhitespace(this string s)
{
    return String.IsNullOrWhiteSpace(s);
}

Assumes _httpContextAccessor was provided through DI.

Yahoo Finance API

Yahoo is very easy to use and provides customized data. Use the following page to learn more.

finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv

WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.

Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv

Casting objects in Java

Sometimes you will like to receive as argument a Parent reference and inside you probably want to do something specific of a child.

abstract class Animal{
 public abstract void move();
}
class Shark extends Animal{
 public void move(){
  swim();
 }
 public void swim(){}
 public void bite(){}
}
class Dog extends Animal{
 public void move(){
  run();
 }
 public void run(){}
 public void bark(){}
}

...

void somethingSpecific(Animal animal){
 // Here you don't know and may don't care which animal enters
 animal.move(); // You can call parent methods but you can't call bark or bite.
 if(animal instanceof Shark){
  Shark shark = (Shark)animal;
  shark.bite(); // Now you can call bite!
 }
 //doSomethingSharky(animal); // You cannot call this method.
}

...

In above's method you can pass either Shark or Dog, but what if you have something like this:

void doSomethingSharky(Shark shark){
 //Here you cannot receive an Animal reference
}

That method can only be called by passing shark references So if you have an Animal (and it is deeply a Shark) you can call it like this:

Animal animal...
doSomethingSharky((Shark) animal)

Bottom line, you can use Parent references and it is usually better when you don't care about the implementation of the parent and use casting to use the Child as an specific object, it will be exactly the same object, but your reference know it, if you don't cast it, your reference will point to the same object but cannot be sure what kind of Animal would it be, therefore will only allow you to call known methods.

CSS to stop text wrapping under image

setting display:flexfor the text worked for me.

Notification bar icon turns white in Android 5 Lollipop

I think it's too late to talk about API 21, but I found a easy way.

When using 'Custom Notification(custom layout)'s,

RemoteView's

setImageViewResource(int viewId, int srcId);

and

setImageViewUri(int viewId, Uri uri); 

makes those image white on Lollipop (API 21).

But when using

setImageViewBitmap(int viewId, Bitmap bitmap);

Image doesn't become white-masked!

How to force a view refresh without having it trigger automatically from an observable?

I have created a JSFiddle with my bindHTML knockout binding handler here: https://jsfiddle.net/glaivier/9859uq8t/

First, save the binding handler into its own (or a common) file and include after Knockout.

If you use this switch your bindings to this:

<div data-bind="bindHTML: htmlValue"></div>

OR

<!-- ko bindHTML: htmlValue --><!-- /ko -->

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

Convert java.time.LocalDate into java.util.Date type

java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

R - Markdown avoiding package loading messages

This is an old question, but here's another way to do it.

You can modify the R code itself instead of the chunk options, by wrapping the source call in suppressPackageStartupMessages(), suppressMessages(), and/or suppressWarnings(). E.g:

```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```

You can also put those functions around your library() calls inside the "source.R" script.

How to convert Django Model object to dict with its fields and values?

Lots of interesting solutions here. My solution was to add an as_dict method to my model with a dict comprehension.

def as_dict(self):
    return dict((f.name, getattr(self, f.name)) for f in self._meta.fields)

As a bonus, this solution paired with an list comprehension over a query makes for a nice solution if you want export your models to another library. For example, dumping your models into a pandas dataframe:

pandas_awesomeness = pd.DataFrame([m.as_dict() for m in SomeModel.objects.all()])

What is an NP-complete in computer science?

What is NP?

NP is the set of all decision problems (questions with a yes-or-no answer) for which the 'yes'-answers can be verified in polynomial time (O(nk) where n is the problem size, and k is a constant) by a deterministic Turing machine. Polynomial time is sometimes used as the definition of fast or quickly.

What is P?

P is the set of all decision problems which can be solved in polynomial time by a deterministic Turing machine. Since they can be solved in polynomial time, they can also be verified in polynomial time. Therefore P is a subset of NP.

What is NP-Complete?

A problem x that is in NP is also in NP-Complete if and only if every other problem in NP can be quickly (ie. in polynomial time) transformed into x.

In other words:

  1. x is in NP, and
  2. Every problem in NP is reducible to x

So, what makes NP-Complete so interesting is that if any one of the NP-Complete problems was to be solved quickly, then all NP problems can be solved quickly.

See also the post What's "P=NP?", and why is it such a famous question?

What is NP-Hard?

NP-Hard are problems that are at least as hard as the hardest problems in NP. Note that NP-Complete problems are also NP-hard. However not all NP-hard problems are NP (or even a decision problem), despite having NP as a prefix. That is the NP in NP-hard does not mean non-deterministic polynomial time. Yes, this is confusing, but its usage is entrenched and unlikely to change.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How to Create Multiple Where Clause Query Using Laravel Eloquent?

use whereIn condition and pass the array

$array = [1008,1009,1010];

User::whereIn('users.id', $array)->get();

"SSL certificate verify failed" using pip to install packages

If you're using python3, you can try this too:

python3 -m pip install --upgrade Scrapy --trusted-host pypi.org --trusted-host files.pythonhosted.org

How to make a div 100% height of the browser window

One of the options is using CSS table. It has great browser support and even works in Internet Explorer 8.

JSFiddle Example

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.container {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
.left, .right {_x000D_
  display: table-cell;_x000D_
  width: 50%;_x000D_
}_x000D_
.right {_x000D_
  background: grey;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left"></div>_x000D_
  <div class="right"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

Hot deploy on JBoss - how do I make JBoss "see" the change?

Solution for Netbeans 8.02 and 8.1 IDE and JBOSS EAP 6.4:

  1. From the services tab of Netbeans, add JBOSS server to your "servers" node.
  2. If you are using MAVEN, netbeans compiles files and maven copies files to ./target directory. You need to create a symbolic link from .\target to JBOSS_HOME\standalone\deployments. Under windows, an example command would be

    cd %JBOSS_HOME%\standalone\deployments mklink /d MyWebApplication.war %PROJECTS_HOME%\MyWebApplication\target\MyWebApplication-1.0.0

    The above creates a symbolic link from %JBOSS_HOME%\standalone\deployments\MyWebApplication.war to \target\MyWebApplication-1.0.0 which is where maven transfers all files after compilation, or after a jsp, html or any other file changes.

  3. Last think to do is to create a CentralManagement.war.dodeploy file in %JBOSS_HOME%\standalone\deployments. This file will tell JBOSS to deploy the war "file" as a web application

Class file for com.google.android.gms.internal.zzaja not found

If you use different version of play services libraries, you will get this error.

For example, below entries in build.gradle file cause the error as versions are different.

implementation 'com.google.android.gms:play-services-maps:11.4.2'
implementation 'com.google.android.gms:play-services-location:11.6.0'

To fix the issue use same versions.

implementation 'com.google.android.gms:play-services-maps:11.6.0'
implementation 'com.google.android.gms:play-services-location:11.6.0'

Passing parameters in rails redirect_to

Route your path, and take the params, and return:

redirect_to controller: "client", action: "get_name", params: request.query_parameters and return

What is an application binary interface (ABI)?

Linux shared library minimal runnable ABI example

In the context of shared libraries, the most important implication of "having a stable ABI" is that you don't need to recompile your programs after the library changes.

So for example:

  • if you are selling a shared library, you save your users the annoyance of recompiling everything that depends on your library for every new release

  • if you are selling closed source program that depends on a shared library present in the user's distribution, you could release and test less prebuilts if you are certain that ABI is stable across certain versions of the target OS.

    This is specially important in the case of the C standard library, which many many programs in your system link to.

Now I want to provide a minimal concrete runnable example of this.

main.c

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

#include "mylib.h"

int main(void) {
    mylib_mystruct *myobject = mylib_init(1);
    assert(myobject->old_field == 1);
    free(myobject);
    return EXIT_SUCCESS;
}

mylib.c

#include <stdlib.h>

#include "mylib.h"

mylib_mystruct* mylib_init(int old_field) {
    mylib_mystruct *myobject;
    myobject = malloc(sizeof(mylib_mystruct));
    myobject->old_field = old_field;
    return myobject;
}

mylib.h

#ifndef MYLIB_H
#define MYLIB_H

typedef struct {
    int old_field;
} mylib_mystruct;

mylib_mystruct* mylib_init(int old_field);

#endif

Compiles and runs fine with:

cc='gcc -pedantic-errors -std=c89 -Wall -Wextra'
$cc -fPIC -c -o mylib.o mylib.c
$cc -L . -shared -o libmylib.so mylib.o
$cc -L . -o main.out main.c -lmylib
LD_LIBRARY_PATH=. ./main.out

Now, suppose that for v2 of the library, we want to add a new field to mylib_mystruct called new_field.

If we added the field before old_field as in:

typedef struct {
    int new_field;
    int old_field;
} mylib_mystruct;

and rebuilt the library but not main.out, then the assert fails!

This is because the line:

myobject->old_field == 1

had generated assembly that is trying to access the very first int of the struct, which is now new_field instead of the expected old_field.

Therefore this change broke the ABI.

If, however, we add new_field after old_field:

typedef struct {
    int old_field;
    int new_field;
} mylib_mystruct;

then the old generated assembly still accesses the first int of the struct, and the program still works, because we kept the ABI stable.

Here is a fully automated version of this example on GitHub.

Another way to keep this ABI stable would have been to treat mylib_mystruct as an opaque struct, and only access its fields through method helpers. This makes it easier to keep the ABI stable, but would incur a performance overhead as we'd do more function calls.

API vs ABI

In the previous example, it is interesting to note that adding the new_field before old_field, only broke the ABI, but not the API.

What this means, is that if we had recompiled our main.c program against the library, it would have worked regardless.

We would also have broken the API however if we had changed for example the function signature:

mylib_mystruct* mylib_init(int old_field, int new_field);

since in that case, main.c would stop compiling altogether.

Semantic API vs Programming API

We can also classify API changes in a third type: semantic changes.

The semantic API, is usually a natural language description of what the API is supposed to do, usually included in the API documentation.

It is therefore possible to break the semantic API without breaking the program build itself.

For example, if we had modified

myobject->old_field = old_field;

to:

myobject->old_field = old_field + 1;

then this would have broken neither programming API, nor ABI, but main.c the semantic API would break.

There are two ways to programmatically check the contract API:

List of everything that breaks C / C++ shared library ABIs

TODO: find / create the ultimate list:

Java minimal runnable example

What is binary compatibility in Java?

Tested in Ubuntu 18.10, GCC 8.2.0.

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

Regular expression for matching HH:MM time format

check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to;

8:30-9:40
09:40-09 : 50
09 : 40-09 : 50
09:40 - 09 : 50
08:00to05:00
08 : 00to05 : 00
08:00 to 05:00
8am-09pm
08h00 till 17h00
8pm-5am
08h00,21h00
06pm untill 9am

It'll also pickup many more, as long as the times include digits

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Actual Swift 3 Answer

This is the ONLY function you need. You do not need CanEdit or CommitEditingStyle functions for custom actions.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let action1 = UITableViewRowAction(style: .default, title: "Action1", handler: {
        (action, indexPath) in
        print("Action1")
    })
    action1.backgroundColor = UIColor.lightGray
    let action2 = UITableViewRowAction(style: .default, title: "Action2", handler: {
        (action, indexPath) in
        print("Action2")
    })
    return [action1, action2]
}

scroll image with continuous scrolling using marquee tag

You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.

There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.

I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="assets/js/crawler.js" type="text/javascript" ></script>
</head>

<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
    <img src="assets/images/products/ie.png" />
    <img src="assets/images/products/browser.png" />
    <img src="assets/images/products/chrome.png" />
    <img src="assets/images/products/safari.png" />
</div>

Here is the plugin configration:

marqueeInit({
    uniqueid: 'mycrawler2',
    style: {
    },
    inc: 5, //speed - pixel increment for each iteration of this marquee's movement
    mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
    moveatleast: 2,
    neutral: 150,
    savedirection: true,
    random: true
});

Post an object as data using Jquery Ajax

I will leave my original answer in place but the below is how you need to approach it. (Forgive me but it is a long time since I have used regular asp.net / web services with jquery:)

You need to use the following js lib json2 library, you can then use the stringify method to ensure your json is in the correct format for the service.

var data0 = {numberId: "1", companyId : "531"};

var json = JSON2.stringify(data0 ); 

$.ajax({
 type: "POST",
 url: "TelephoneNumbers.aspx/DeleteNumber",
 data: json,
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function(msg) {
 alert('In Ajax');
 }
});

UPDATE: Same issue / answer here

Editor does not contain a main type in Eclipse

Create a source folder under Java Resources enter image description here

Query to list number of records in each table in a database

I think that the shortest, fastest and simplest way would be:

SELECT
    object_name(object_id) AS [Table],
    SUM(row_count) AS [Count]
FROM
    sys.dm_db_partition_stats
WHERE
    --object_schema_name(object_id) = 'dbo' AND 
    index_id < 2
GROUP BY
    object_id

C# Creating and using Functions

you have to make you're function static like this

namespace Add_Function
{
  class Program
  {
    public static void(string[] args)
    {
       int a;
       int b;
       int c;

       Console.WriteLine("Enter value of 'a':");
       a = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Enter value of 'b':");
       b = Convert.ToInt32(Console.ReadLine());

       //why can't I not use it this way?
       c = Add(a, b);
       Console.WriteLine("a + b = {0}", c);
    }
    public static int Add(int x, int y)
    {
        int result = x + y;
        return result;
     }
  }
}

you can do Program.Add instead of Add you also can make a new instance of Program by going like this

Program programinstance = new Program();

How to upgrade PowerShell version from 2.0 to 3.0

Download and install from http://www.microsoft.com/en-us/download/details.aspx?id=34595. You need Windows 7 SP1 though.

It's worth keeping in mind that PowerShell 3 on Windows 7 does not have all the cmdlets as PowerShell 3 on Windows 8. So you may still encounter cmdlets that are not present on your system.

How to render an array of objects in React?

You can do it in two ways:

First:

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);

    return (
      <div>
      {listItems }
      </div>
    );
  }

Second: Directly write the map function in the return

render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    return (
      <div>
      {data.map(function(d, idx){
         return (<li key={idx}>{d.name}</li>)
       })}
      </div>
    );
  }

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

Image is not showing in browser?

Your path should be like this : "http://websitedomain//folderpath/66.jpg">

<img  src="http://websitedomain/folderpath/66.jpg" width="400" height="400" ></img>

Nesting optgroups in a dropdownlist/select

Ok, if anyone ever reads this: the best option is to add four &nbsp;s at each extra level of indentation, it would seem!

so:

_x000D_
_x000D_
<select>_x000D_
 <optgroup label="Level One">_x000D_
  <option> A.1 </option>_x000D_
  <optgroup label="&nbsp;&nbsp;&nbsp;&nbsp;Level Two">_x000D_
   <option>&nbsp;&nbsp;&nbsp;&nbsp; A.B.1 </option>_x000D_
  </optgroup>_x000D_
  <option> A.2 </option>_x000D_
 </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Strtotime() doesn't work with dd/mm/YYYY format

{{ date('d F Y',strtotime($a->dates)) }}

alternative use laravel

\Carbon\Carbon::parse($a->dates)->format('d F Y') }}

How to import classes defined in __init__.py

You just put them in __init__.py.

So with test/classes.py being:

class A(object): pass
class B(object): pass

... and test/__init__.py being:

from classes import *

class Helper(object): pass

You can import test and have access to A, B and Helper

>>> import test
>>> test.A
<class 'test.classes.A'>
>>> test.B
<class 'test.classes.B'>
>>> test.Helper
<class 'test.Helper'>

Username and password in command for git push

Yes, you can do

git push https://username:[email protected]/file.git --all

in this case https://username:[email protected]/file.git replace the origin in git push origin --all

To see more options for git push, try git help push

How do you get the currently selected <option> in a <select> via JavaScript?

The .selectedIndex of the select object has an index; you can use that to index into the .options array.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

You should put your processing into the class constructor or an OnInit hook method.

Can't draw Histogram, 'x' must be numeric

Note that you could as well plot directly from ce (after the comma removing) using the column name :

hist(ce$Weight)

(As opposed to using hist(ce[1]), which would lead to the same "must be numeric" error.)

This also works for a database query result.

How stable is the git plugin for eclipse?

You can integrate Git-GUI with Eclipse as an alternative to EGit.

See this two part YouTube tutorial specific to Windows:
http://www.youtube.com/watch?v=DcM1xOiaidk
http://www.youtube.com/watch?v=1OrPJClD92s

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

Mobile Safari: Javascript focus() method on inputfield only works with click?

UPDATE

I also tried this, but to no avail:

$(document).ready(function() {
$('body :not(.wr-dropdown)').bind("click", function(e) {
    $('.test').focus();
})
$('.wr-dropdown').on('change', function(e) {
    if ($(".wr-dropdow option[value='/search']")) {
        setTimeout(function(e) {
            $('body :not(.wr-dropdown)').trigger("click");
        },3000)         
    } 
}); 

});

I am confused as to why you say this isn't working because your JSFiddle is working just fine, but here is my suggestion anyway...

Try this line of code in your SetTimeOut function on your click event:

document.myInput.focus();

myInput correlates to the name attribute of the input tag.

<input name="myInput">

And use this code to blur the field:

document.activeElement.blur();

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

I had this issue recently and I resolved it by simply rolling IE8 back to IE7.

My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.

FromBody string parameter is giving null

Finally got it working after 1 hour struggle.

This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .

For a new WebApi 2 application example:

Postman (looks exactly, like below):

POST    http://localhost:61402/api/values   [Send]
Body
     (*) raw             JSON (application/json) v
         "{  \"key1\": \"value1\" }"

The port 61402 or url /api/values above, may be different for you.

ValuesController.cs

using Newtonsoft.Json;
// ..

// POST api/values
[HttpPost]
public object Post([FromBody]string jsonString)
{
    // add reference to Newtonsoft.Json
    //  using Newtonsoft.Json;

    // jsonString to myJsonObj
    var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

    // value1 is myJsonObj[key1]
    var valueOfkey1 = myJsonObj["key1"];

    return myJsonObj;
}

All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.

javac is not recognized as an internal or external command, operable program or batch file

If java command is working and getting problem with javac. then first check in jdk's bin directory javac.exe file is there or not. If javac.exe file is exist then set JAVA_HOME as System variable.

How do I get the fragment identifier (value after hash #) from a URL?

I had the URL from run time, below gave the correct answer:

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

hope this helps

How do I find which process is leaking memory?

You can run the top command (to run non-interactively, type top -b -n 1). To see applications which are leaking memory, look at the following columns:

  • RPRVT - resident private address space size
  • RSHRD - resident shared address space size
  • RSIZE - resident memory size
  • VPRVT - private address space size
  • VSIZE - total memory size

How to deal with missing src/test/java source folder in Android/Maven project?

I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).

It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:

<classpathentry kind="src" output="bin/classes" path="src/test/java">
  <attributes>
    <attribute name="maven.pomderived" value="true"/>
  </attributes>
</classpathentry>

As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:

enter image description here

There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.

Accessing Object Memory Address

You could reimplement the default repr this way:

def __repr__(self):
    return '<%s.%s object at %s>' % (
        self.__class__.__module__,
        self.__class__.__name__,
        hex(id(self))
    )

How can I get a random number in Kotlin?

Below in Kotlin worked well for me:

(fromNumber.rangeTo(toNumber)).random()

Range of the numbers starts with variable fromNumber and ends with variable toNumber. fromNumber and toNumber will also be included in the random numbers generated out of this.

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

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

Here's a full listing of a program and its results.

The code:

using System;

namespace TimeZoneIds
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
            {
                Console.WriteLine(z.Id);
            }
        }
    }
}

The TimeZoneId results on my Windows 7 workstation:

Dateline Standard Time

UTC-11

Samoa Standard Time

Hawaiian Standard Time

Alaskan Standard Time

Pacific Standard Time (Mexico)

Pacific Standard Time

US Mountain Standard Time

Mountain Standard Time (Mexico)

Mountain Standard Time

Central America Standard Time

Central Standard Time

Central Standard Time (Mexico)

Canada Central Standard Time

SA Pacific Standard Time

Eastern Standard Time

US Eastern Standard Time

Venezuela Standard Time

Paraguay Standard Time

Atlantic Standard Time

Central Brazilian Standard Time

SA Western Standard Time

Pacific SA Standard Time

Newfoundland Standard Time

E. South America Standard Time

Argentina Standard Time

SA Eastern Standard Time

Greenland Standard Time

Montevideo Standard Time

UTC-02

Mid-Atlantic Standard Time

Azores Standard Time

Cape Verde Standard Time

Morocco Standard Time

UTC

GMT Standard Time

Greenwich Standard Time

W. Europe Standard Time

Central Europe Standard Time

Romance Standard Time

Central European Standard Time

W. Central Africa Standard Time

Namibia Standard Time

Jordan Standard Time

GTB Standard Time

Middle East Standard Time

Egypt Standard Time

Syria Standard Time

South Africa Standard Time

FLE Standard Time

Israel Standard Time

E. Europe Standard Time

Arabic Standard Time

Arab Standard Time

Russian Standard Time

E. Africa Standard Time

Iran Standard Time

Arabian Standard Time

Azerbaijan Standard Time

Mauritius Standard Time

Georgian Standard Time

Caucasus Standard Time

Afghanistan Standard Time

Ekaterinburg Standard Time

Pakistan Standard Time

West Asia Standard Time

India Standard Time

Sri Lanka Standard Time

Nepal Standard Time

Central Asia Standard Time

Bangladesh Standard Time

N. Central Asia Standard Time

Myanmar Standard Time

SE Asia Standard Time

North Asia Standard Time

China Standard Time

North Asia East Standard Time

Singapore Standard Time

W. Australia Standard Time

Taipei Standard Time

Ulaanbaatar Standard Time

Tokyo Standard Time

Korea Standard Time

Yakutsk Standard Time

Cen. Australia Standard Time

AUS Central Standard Time

E. Australia Standard Time

AUS Eastern Standard Time

West Pacific Standard Time

Tasmania Standard Time

Vladivostok Standard Time

Central Pacific Standard Time

New Zealand Standard Time

UTC+12

Fiji Standard Time

Kamchatka Standard Time

Tonga Standard Time

How to start Spyder IDE on Windows

I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.

I installed PyQt5 (pip install pyqt5) and Spyder (pip install spyder) which both installed w/out error and included all of the necessary dependencies.

To launch Spyder, I created a simple Python script (Spyder.py):

# Spyder Start Script
from spyder.app import start
start.main()

Then I created a Windows batch file (Spyder.bat):

@echo off
python c:\<path_to_Spyder_py>\Spyder.py

Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.

Works like a charm for me.

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

Creating a batch file, for simple javac and java command execution

Am i understanding your question only? You need .bat file to compile and execute java class files?

if its a .bat file. you can just double click.

and in your .bat file, you just need to javac Main.java ((make sure your bat has the path to ur Main.java) java Main

If you want to echo compilation warnings/statements, that would need something else. But since, you want that to be automated, maybe you eventually don't need that.

Is it possible to specify condition in Count()?

You can also use the Pivot Keyword if you are using SQL 2005 or above

more info and from Technet

SELECT *
FROM @Users
PIVOT (
    COUNT(Position)
    FOR Position
    IN (Manager, CEO, Employee)
) as p

Test Data Set

DECLARE @Users TABLE (Position VARCHAR(10))
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('Manager')
INSERT INTO @Users (Position) VALUES('CEO')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')
INSERT INTO @Users (Position) VALUES('Employee')

calling server side event from html button control

The easiest way to accomplish this is to override the RaisePostBackEvent method.

<input type="button" ID="btnRaisePostBack" runat="server" onclick="raisePostBack();" ... />

And in your JavaScript:

raisePostBack = function(){
    __doPostBack("<%=btnRaisePostBack.ClientID%>", "");
}

And in your code:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    if (source == btnRaisePostBack)
    {
         //do some logic
    }
}

How can I commit files with git?

in standart Vi editor in this situation you should

  1. press Esc
  2. type ":wq" (without quotes)
  3. Press Enter

How to add an image in the title bar using html?

According to wikipedia, the most browser-compatible incantation is:

<link rel="shortcut icon" href="favicon.ico" />

After that, you just need to worry about whether your browser is actually downloading the icon. What do the server logs say? Have you checked your browsers network debugging console?

Running Command Line in Java

import java.io.*;

Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

Consider the following if you run into any further problems, but I'm guessing that the above will work for you:

Problems with Runtime.exec()

Get Cell Value from a DataTable in C#

You probably need to reference it from the Rowsrather than as a cell:

var cellValue = dt.Rows[i][j];

How to add an object to an array

With push you can even add multiple objects to an array

  let myArray = [];

   myArray.push(
              {name:"James", dataType:TYPES.VarChar, Value: body.Name},
              {name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
              {name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
             );

JQuery - Storing ajax response into global variable

your problem might not be related to any local or global scope for that matter just the server delay between the "success" function executing and the time you are trying to take out data from your variable.

chances are you are trying to print the contents of the variable before the ajax "success" function fires.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

First prevent default actions on your entire document as usual:

$(document).bind('touchmove', function(e){
  e.preventDefault();           
});

Then stop your class of elements from propagating to the document level. This stops it from reaching the function above and thus e.preventDefault() is not initiated:

$('.scrollable').bind('touchmove', function(e){
  e.stopPropagation();
});

This system seems to be more natural and less intensive than calculating the class on all touch moves. Use .on() rather than .bind() for dynamically generated elements.

Also consider these meta tags to prevent unfortunate things from happening while using your scrollable div:

<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />

In HTML5, should the main navigation be inside or outside the <header> element?

It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

I was so confusing first time, but I propose you final working solution for Windows:

1) Open cmd and go to your Java/jdk/bin directory (just press cd .. to go one folder back and cd NAME_FOLDER to go one folder forward), in my case, final folder: C:\Program Files\Java\jdk1.8.0_73\bin> enter image description here

2) Now type this command keytool -list -v -keystore C:\Users\YOUR_WINDOWS_USER\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

As result you have to get something like this: enter image description here

The input is not a valid Base-64 string as it contains a non-base 64 character

We can remove unnecessary string input in front of the value.

string convert = hdnImage.Replace("data:image/png;base64,", String.Empty);

byte[] image64 = Convert.FromBase64String(convert);

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How to open a link in new tab (chrome) using Selenium WebDriver?

I have tried other techniques, but none of them worked, also no error produced, but when I have used the code below, it worked for me.

((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("http://google.com");

Inner text shadow with CSS

Here's a little trick I discovered using the :before and :after pseudo-elements:

.depth {
    color: black;
    position: relative;
}
.depth:before, .depth:after {
    content: attr(title);
    color: rgba(255,255,255,.1);
    position: absolute;
}
.depth:before { top: 1px; left: 1px }
.depth:after  { top: 2px; left: 2px }

The title attribute needs to be the same as the content. Demo: http://dabblet.com/gist/1609945

Check if a specific tab page is selected (active)

To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}

This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

ggplot combining two plots from different data.frames

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

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

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

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

Insert some string into given string at given index in Python

For the sake of future 'newbies' tackling this problem, I think a quick answer would be fitting to this thread.

Like bgporter said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.

In the following example I insert 'Fu' in to 'Kong Panda', to create 'Kong Fu Panda'

>>> line = 'Kong Panda'
>>> index = line.find('Panda')
>>> output_line = line[:index] + 'Fu ' + line[index:]
>>> output_line
'Kong Fu Panda'

In the example above, I used the index value to 'slice' the string in to 2 substrings: 1 containing the substring before the insertion index, and the other containing the rest. Then I simply add the desired string between the two and voilà, we have inserted a string inside another.

Python's slice notation has a great answer explaining the subject of string slicing.

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

How to use Sublime over SSH

There are three ways:

Also, in theory, you can install X11 on the remote server and run Sublime there over VNC or X11 forwarding, but there would be no point doing this.

What's the difference between a mock & stub?

A Stub is an object that implements an interface of a component, but instead of returning what the component would return when called, the stub can be configured to return a value that suits the test. Using stubs a unit test can test if a unit can handle various return values from its collaborator. Using a stub instead of a real collaborator in a unit test could be expressed like this:

unit test --> stub

unit test --> unit --> stub

unit test asserts on results and state of unit

First the unit test creates the stub and configures its return values. Then the unit test creates the unit and sets the stub on it. Now the unit test calls the unit which in turn calls the stub. Finally the unit test makes assertions about the results of the method calls on the unit.

A Mock is like a stub, only it also has methods that make it possible determine what methods where called on the Mock. Using a mock it is thus possible to both test if the unit can handle various return values correctly, and also if the unit uses the collaborator correctly. For instance, you cannot see by the value returned from a dao object whether the data was read from the database using a Statement or a PreparedStatement. Nor can you see if the connection.close() method was called before returning the value. This is possible with mocks. In other words, mocks makes it possible to test a units complete interaction with a collaborator. Not just the collaborator methods that return values used by the unit. Using a mock in a unit test could be expressed like this:

unit test --> mock

unit test --> unit --> mock

unit test asserts on result and state of unit

unit test asserts on the methods called on mock

More Detail >> Here

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Those error messages

CMake Error at ... (project):
    No CMAKE_C_COMPILER could be found.
-- Configuring incomplete, errors occurred!
See also ".../CMakeFiles/CMakeOutput.log".
See also ".../CMakeFiles/CMakeError.log".

or

CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.
Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
...
-- Configuring incomplete, errors occurred!

just mean that CMake was unable to find your C/CXX compiler to compile a simple test program (one of the first things CMake tries while detecting your build environment).

The steps to find your problem are dependent on the build environment you want to generate. The following tutorials are a collection of answers here on Stack Overflow and some of my own experiences with CMake on Microsoft Windows 7/8/10 and Ubuntu 14.04.

Preconditions

  • You have installed the compiler/IDE and it was able to once compile any other program (directly without CMake)
  • You have the latest CMake version
  • You have access rights on the drive you want CMake to generate your build environment
  • You have a clean build directory (because CMake does cache things from the last try) e.g. as sub-directory of your source tree

    Windows cmd.exe

    > rmdir /s /q VS2015
    > mkdir VS2015
    > cd VS2015
    

    Bash shell

    $ rm -rf MSYS
    $ mkdir MSYS
    $ cd MSYS
    

    and make sure your command shell points to your newly created binary output directory.

General things you can/should try

  1. Is CMake able find and run with any/your default compiler? Run without giving a generator

    > cmake ..
    -- Building for: Visual Studio 14 2015
    ...
    

    Perfect if it correctly determined the generator to use - like here Visual Studio 14 2015

  2. What was it that actually failed?

    In the previous build output directory look at CMakeFiles\CMakeError.log for any error message that make sense to you or try to open/compile the test project generated at CMakeFiles\[Version]\CompilerIdC|CompilerIdCXX directly from the command line (as found in the error log).

CMake can't find Visual Studio

  1. Try to select the correct generator version:

    > cmake --help
    > cmake -G "Visual Studio 14 2015" ..
    
  2. If that doesn't help, try to set the Visual Studio environment variables first (the path could vary):

    > "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
    > cmake ..
    

    or use the Developer Command Prompt for VS2015 short-cut in your Windows Start Menu under All Programs/Visual Studio 2015/Visual Studio Tools (thanks at @Antwane for the hint).

Background: CMake does support all Visual Studio releases and flavors (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate, etc.). To determine the location of the compiler it uses a combination of searching the registry (e.g. at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[Version];InstallDir), system environment variables and - if none of the others did come up with something - plainly try to call the compiler.

CMake can't find GCC (MinGW/MSys)

  1. You start the MSys bash shell with msys.bat and just try to directly call gcc

    $ gcc
    gcc.exe: fatal error: no input files
    compilation terminated.
    

    Here it did find gcc and is complaining that I didn't gave it any parameters to work with.

    So the following should work:

    $ cmake -G "MSYS Makefiles" ..
    -- The CXX compiler identification is GNU 4.8.1
    ...
    $ make
    

    If GCC was not found call export PATH=... to add your compilers path (see How to set PATH environment variable in CMake script?) and try again.

  2. If it's still not working, try to set the CXX compiler path directly by exporting it (path may vary)

    $ export CC=/c/MinGW/bin/gcc.exe
    $ export CXX=/c/MinGW/bin/g++.exe
    $ cmake -G "MinGW Makefiles" ..
    -- The CXX compiler identification is GNU 4.8.1
    ...
    $ mingw32-make
    

    For more details see How to specify new GCC path for CMake

    Note: When using the "MinGW Makefiles" generator you have to use the mingw32-make program distributed with MinGW

  3. Still not working? That's weird. Please make sure that the compiler is there and it has executable rights (see also preconditions chapter above).

    Otherwise the last resort of CMake is to not try any compiler search itself and set CMake's internal variables directly by

    $ cmake -DCMAKE_C_COMPILER=/c/MinGW/bin/gcc.exe -DCMAKE_CXX_COMPILER=/c/MinGW/bin/g++.exe ..
    

    For more details see Cmake doesn't honour -D CMAKE_CXX_COMPILER=g++ and Cmake error setting compiler

    Alternatively those variables can also be set via cmake-gui.exe on Windows. See Cmake cannot find compiler

Background: Much the same as with Visual Studio. CMake supports all sorts of GCC flavors. It searches the environment variables (CC, CXX, etc.) or simply tries to call the compiler. In addition it will detect any prefixes (when cross-compiling) and tries to add it to all binutils of the GNU compiler toolchain (ar, ranlib, strip, ld, nm, objdump, and objcopy).

Get index of array element faster than O(n)

Still I wonder if there's a more convenient way of finding index of en element without caching (or there's a good caching technique that will boost up the performance).

You can use binary search (if your array is ordered and the values you store in the array are comparable in some way). For that to work you need to be able to tell the binary search whether it should be looking "to the left" or "to the right" of the current element. But I believe there is nothing wrong with storing the index at insertion time and then using it if you are getting the element from the same array.

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

The original answer is no longer working as written:

<%=Html.TextBox("test", new { style="width:50px" })%> 

will get you a text box with "{ style="width:50px" }" as its text content.

To adjust this for the current release of MVC 1.0, use the following script (note the addition of the second parameter - I have mine starting as blank, adjust accordingly based on your needs):

<%=Html.TextBox("test", "", new { style="width:50px" })%> 

Eclipse : Failed to connect to remote VM. Connection refused.

I ran into this problem debugging play framework version 2.x, turned out the server hadn't been started even though the play debug run command was issued. After a first request to the webserver which caused the play framework to really start the application at port 9000, I was able to connect properly to the debug port 9999 from eclipse.

[info] play - Application started (Dev)

The text above was shown in the console when the message above appeared, indicating why eclipse couldn't connect before first http request.

increase the java heap size permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm 

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

jQuery Datepicker with text input that doesn't allow user input

Instead of using textbox you can use button also. Works best for me, where I don't want users to write date manually.

enter image description here

Turn a number into star rating display using jQuery and CSS

If you only have to support modern browsers, you can get away with:

  • No images;
  • Mostly static css;
  • Nearly no jQuery or Javascript;

You only need to convert the number to a class, e.g. class='stars-score-50'.

First a demo of "rendered" markup:

_x000D_
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
Within block level elements:_x000D_
_x000D_
<div><span class="stars-container stars-0">?????</span></div>_x000D_
<div><span class="stars-container stars-10">?????</span></div>_x000D_
<div><span class="stars-container stars-20">?????</span></div>_x000D_
<div><span class="stars-container stars-30">?????</span></div>_x000D_
<div><span class="stars-container stars-40">?????</span></div>_x000D_
<div><span class="stars-container stars-50">?????</span></div>_x000D_
<div><span class="stars-container stars-60">?????</span></div>_x000D_
<div><span class="stars-container stars-70">?????</span></div>_x000D_
<div><span class="stars-container stars-80">?????</span></div>_x000D_
<div><span class="stars-container stars-90">?????</span></div>_x000D_
<div><span class="stars-container stars-100">?????</span></div>_x000D_
_x000D_
<p>Or use it in a sentence: <span class="stars-container stars-70">?????</span> (cool, huh?).</p>
_x000D_
_x000D_
_x000D_

Then a demo that uses a wee bit of code:

_x000D_
_x000D_
$(function() {_x000D_
  function addScore(score, $domElement) {_x000D_
    $("<span class='stars-container'>")_x000D_
      .addClass("stars-" + score.toString())_x000D_
      .text("?????")_x000D_
      .appendTo($domElement);_x000D_
  }_x000D_
_x000D_
  addScore(70, $("#fixture"));_x000D_
});
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Generated: <div id="fixture"></div>
_x000D_
_x000D_
_x000D_

The biggest downsides of this solution are:

  1. You need the stars inside the element to generate correct width;
  2. There's no semantic markup, e.g. you'd prefer the score as text inside the element;
  3. It only allows for as many scores as you'll have classes (because we can't use Javascript to set a precise width on a pseudo-element).

To fix this the solution above can be easily tweaked. The :before and :after bits need to become actual elements in the DOM (so we need some JS for that).

The latter is left as an excercise for the reader.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The only solution that worked for me and $.each was definitely causing the error. so i used for loop and it's not throwing error anymore.

Example code

     $.ajax({
            type: 'GET',
            url: 'https://example.com/api',
            data: { get_param: 'value' },
            success: function (data) {
                for (var i = 0; i < data.length; ++i) {
                    console.log(data[i].NameGerman);
                }
            }
        });

How to select data of a table from another database in SQL Server?

Using Microsoft SQL Server Management Studio you can create Linked Server. First make connection to current (local) server, then go to Server Objects > Linked Servers > context menu > New Linked Server. In window New Linked Server you have to specify desired server name for remote server, real server name or IP address (Data Source) and credentials (Security page).

And further you can select data from linked server:

select * from [linked_server_name].[database].[schema].[table]

Table column sizing

Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

The table column size class has been changed from this

<th class="col-sm-3">3 columns wide</th>

to

<th class="col-3">3 columns wide</th>

link_to method and click event in Rails

just use

=link_to "link", "javascript:function()"

Creating a textarea with auto-resize

I have tested script in common browsers, and it failed in Chrome and Safari. It is because of constantly updatable scrollHeight variable.

I have applied DisgruntledGoat script using jQuery and added chrome fix

function fitToContent(/* JQuery */text, /* Number */maxHeight) {
    var adjustedHeight = text.height();
    var relative_error = parseInt(text.attr('relative_error'));
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
        if (maxHeight)
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ((adjustedHeight - relative_error) > text.height()) {
            text.css('height', (adjustedHeight - relative_error) + "px");
            // chrome fix
            if (text[0].scrollHeight != adjustedHeight) {
                var relative = text[0].scrollHeight - adjustedHeight;
                if (relative_error != relative) {
                    text.attr('relative_error', relative + relative_error);
                }
            }
        }
    }
}

function autoResizeText(/* Number */maxHeight) {
    var resize = function() {
        fitToContent($(this), maxHeight);
    };
    $("textarea").attr('relative_error', 0);
    $("textarea").each(resize);
    $("textarea").keyup(resize).keydown(resize);
}

Add & delete view from Layout

This is the best way

LinearLayout lp = new LinearLayout(this);
lp.addView(new Button(this));
lp.addView(new ImageButton(this));
// Now remove them 
lp.removeViewAt(0); // and so on

If you have xml layout then no need to add dynamically.just call

lp.removeViewAt(0);

Using an HTML button to call a JavaScript function

silly way:

onclick="javascript:CapacityChart();"

You should read about discrete javascript, and use a frameworks bind method to bind callbacks to dom events.

to remove first and last element in array

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

To remove first element from an array arr , use arr.shift()
To remove last element from an array arr , use arr.pop()

Git diff against a stash

If your working tree is dirty, you can compare it to a stash by first committing the dirty working tree, and then comparing it to the stash. Afterwards, you may undo the commit with the dirty working tree (since you might not want to have that dirty commit in your commit log).

You can also use the following approach to compare two stashes with each other (in which case you just pop one of the stashes at first).

  • Commit your dirty working tree:

    git add .
    git commit -m "Dirty commit"
    
  • Diff the stash with that commit:

    git diff HEAD stash@{0}
    
  • Then, afterwards, you may revert the commit, and put it back in the working dir:

    git reset --soft HEAD~1
    git reset .
    

Now you've diffed the dirty working tree with your stash, and are back to where you were initially.

Why do multiple-table joins produce duplicate rows?

When you have related tables you often have one-to-many or many-to-many relationships. So when you join to TableB each record in TableA many have multiple records in TableB. This is normal and expected.

Now at times you only need certain columns and those are all the same for all the records, then you would need to do some sort of group by or distinct to remove the duplicates. Let's look at an example:

TableA
Id Field1
1  test
2  another test

TableB
ID Field2 field3
1  Test1  something
1  test1  More something
2  Test2  Anything

So when you join them and select all the files you get:

select * 
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1        b.id   b.field2  b.field3
1    test            1      Test1     something
1    test            1      Test1     More something
2    another test 2  2      Test2     Anything

These are not duplicates because the values of Field3 are different even though there are repeated values in the earlier fields. Now when you only select certain columns the same number of records are being joined together but since the columns with the different information is not being displayed they look like duplicates.

select a.Id, a.Field1,  b.field2
from tableA a 
join tableb b on a.id = b.id

a.Id a.Field1       b.field2  
1    test           Test1     
1    test           Test1 
2    another test   Test2

This appears to be duplicates but it is not because of the multiple records in TableB.

You normally fix this by using aggregates and group by, by using distinct or by filtering in the where clause to remove duplicates. How you solve this depends on exactly what your business rule is and how your database is designed and what kind of data is in there.

Wait until all promises complete even if some rejected

I don't know which promise library you are using, but most have something like allSettled.

Edit: Ok since you want to use plain ES6 without external libraries, there is no such method.

In other words: You have to loop over your promises manually and resolve a new combined promise as soon as all promises are settled.

How can I pad a String in Java?

Apache StringUtils has several methods: leftPad, rightPad, center and repeat.

But please note that — as others have mentioned and demonstrated in this answerString.format() and the Formatter classes in the JDK are better options. Use them over the commons code.

How do I pass data to Angular routed components?

I this the other approach not good for this issue. I thing the best approach is Query-Parameter by Router angular that have 2 way:

Passing query parameter directly

With this code you can navigate to url by params in your html code:

<a [routerLink]="['customer-service']" [queryParams]="{ serviceId: 99 }"></a>

Passing query parameter by Router

You have to inject the router within your constructor like:

constructor(private router:Router){

}

Now use of that like:

goToPage(pageNum) {
    this.router.navigate(['/product-list'], { queryParams: { serviceId: serviceId} });
}

Now if you want to read from Router in another Component you have to use of ActivatedRoute like:

constructor(private activateRouter:ActivatedRouter){

}

and subscribe that:

  ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        // Defaults to 0 if no query param provided.
        this.page = +params['serviceId'] || 0;
      });
  }

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

decompiling DEX into Java sourcecode

It's easy

Get these tools:

  1. dex2jar to translate dex files to jar files

  2. jd-gui to view the java files in the jar

The source code is quite readable as dex2jar makes some optimizations.

Procedure:

And here's the procedure on how to decompile:

Step 1:

Convert classes.dex in test_apk-debug.apk to test_apk-debug_dex2jar.jar

d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk
d2j-dex2jar.sh -f -o output_jar.jar dex_to_decompile.dex

Note 1: In the Windows machines all the .sh scripts are replaced by .bat scripts

Note 2: On linux/mac don't forget about sh or bash. The full command should be:

sh d2j-dex2jar.sh -f -o output_jar.jar apk_to_decompile.apk 

Note 3: Also, remember to add execute permission to dex2jar-X.X directory e.g. sudo chmod -R +x dex2jar-2.0

dex2jar documentation

Step 2:

Open the jar in JD-GUI

The decompiled source

Restrict SQL Server Login access to only one database

For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:

USE master
go
DENY VIEW ANY DATABASE TO [user]
go

This will address exactly the requirement outlined above..

Calling a JavaScript function named in a variable

I'd avoid eval.

To solve this problem, you should know these things about JavaScript.

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

So, why not something like,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

What is the simplest and most robust way to get the user's current location on Android?

I am not sure if the Location-Based Services can get the location from other infrastructures other than GPS, but according to that article, it does seem possible:

Applications can call on any of several types of positioning methods.

Using the mobile phone network: The current cell ID can be used to identify the Base Transceiver Station (BTS) that the device is communicating with and the location of that BTS. Clearly, the accuracy of this method depends on the size of the cell, and can be quite inaccurate. A GSM cell may be anywhere from 2 to 20 kilometers in diameter. Other techniques used along with cell ID can achieve accuracy within 150 meters.

Using satellites: The Global Positioning System (GPS), controlled by the US Department of Defense, uses a constellation of 24 satellites orbiting the earth. GPS determines the device's position by calculating differences in the times signals from different satellites take to reach the receiver. GPS signals are encoded, so the mobile device must be equipped with a GPS receiver. GPS is potentially the most accurate method (between 4 and 40 meters if the GPS receiver has a clear view of the sky), but it has some drawbacks: The extra hardware can be costly, consumes battery while in use, and requires some warm-up after a cold start to get an initial fix on visible satellites. It also suffers from "canyon effects" in cities, where satellite visibility is intermittent.

Using short-range positioning beacons: In relatively small areas, such as a single building, a local area network can provide locations along with other services. For example, appropriately equipped devices can use Bluetooth for short-range positioning.

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

Getting String value from enum in Java

You can use values() method:

For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.

How to map a composite key with JPA and Hibernate?

Using hbm.xml

    <composite-id>

        <!--<key-many-to-one name="productId" class="databaselayer.users.UserDB" column="user_name"/>-->
        <key-property name="productId" column="PRODUCT_Product_ID" type="int"/>
        <key-property name="categoryId" column="categories_id" type="int" />
    </composite-id>  

Using Annotation

Composite Key Class

public  class PK implements Serializable{
    private int PRODUCT_Product_ID ;    
    private int categories_id ;

    public PK(int productId, int categoryId) {
        this.PRODUCT_Product_ID = productId;
        this.categories_id = categoryId;
    }

    public int getPRODUCT_Product_ID() {
        return PRODUCT_Product_ID;
    }

    public void setPRODUCT_Product_ID(int PRODUCT_Product_ID) {
        this.PRODUCT_Product_ID = PRODUCT_Product_ID;
    }

    public int getCategories_id() {
        return categories_id;
    }

    public void setCategories_id(int categories_id) {
        this.categories_id = categories_id;
    }

    private PK() { }

    @Override
    public boolean equals(Object o) {
        if ( this == o ) {
            return true;
        }

        if ( o == null || getClass() != o.getClass() ) {
            return false;
        }

        PK pk = (PK) o;
        return Objects.equals(PRODUCT_Product_ID, pk.PRODUCT_Product_ID ) &&
                Objects.equals(categories_id, pk.categories_id );
    }

    @Override
    public int hashCode() {
        return Objects.hash(PRODUCT_Product_ID, categories_id );
    }
}

Entity Class

@Entity(name = "product_category")
@IdClass( PK.class )
public  class ProductCategory implements Serializable {
    @Id    
    private int PRODUCT_Product_ID ;   

    @Id 
    private int categories_id ;

    public ProductCategory(int productId, int categoryId) {
        this.PRODUCT_Product_ID = productId ;
        this.categories_id = categoryId;
    }

    public ProductCategory() { }

    public int getPRODUCT_Product_ID() {
        return PRODUCT_Product_ID;
    }

    public void setPRODUCT_Product_ID(int PRODUCT_Product_ID) {
        this.PRODUCT_Product_ID = PRODUCT_Product_ID;
    }

    public int getCategories_id() {
        return categories_id;
    }

    public void setCategories_id(int categories_id) {
        this.categories_id = categories_id;
    }

    public void setId(PK id) {
        this.PRODUCT_Product_ID = id.getPRODUCT_Product_ID();
        this.categories_id = id.getCategories_id();
    }

    public PK getId() {
        return new PK(
            PRODUCT_Product_ID,
            categories_id
        );
    }    
}

jQuery send string as POST parameters

I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.

var bar = 'xyz';
var calibri = 'no$libri';

$.ajax({
   type: "POST",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   url: "http://nakolesah.ru/",
   data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
   success: function(msg){
       alert('wow'+msg);
   },
});

Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.

Why doesn't the height of a container element increase if it contains floated elements?

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

How to toggle font awesome icon on click?

Generally and simply it works like this:

_x000D_
_x000D_
<script>_x000D_
            $(document).ready(function () {_x000D_
                $('i').click(function () {_x000D_
                    $(this).toggleClass('fa-plus-square fa-minus-square');_x000D_
                });_x000D_
            });_x000D_
</script>
_x000D_
_x000D_
_x000D_

jQuery Form Validation before Ajax submit

Form native JavaScript checkValidity function is more then enough to trigger the HTML5 validation

$(document).ready(function() {
    $('#urlSubmit').click(function() {
        if($('#urlForm')[0].checkValidity()) {
            alert("form submitting");
        }
    });
});

Entity Framework rollback and remove bad migration

As of .NET Core 2.2, TargetMigration seems to be gone:

get-help Update-Database

NAME
    Update-Database

SYNOPSIS
    Updates the database to a specified migration.


SYNTAX
    Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]


DESCRIPTION
    Updates the database to a specified migration.


RELATED LINKS
    Script-Migration
    about_EntityFrameworkCore 

REMARKS
    To see the examples, type: "get-help Update-Database -examples".
    For more information, type: "get-help Update-Database -detailed".
    For technical information, type: "get-help Update-Database -full".
    For online help, type: "get-help Update-Database -online"

So this works for me now:

Update-Database -Migration 20180906131107_xxxx_xxxx

As well as (no -Migration switch):

Update-Database 20180906131107_xxxx_xxxx

On an added note, you can no longer cleanly delete migration folders without putting your Model Snapshot out of sync. So if you learn this the hard way and wind up with an empty migration where you know there should be changes, you can run (no switches needed for the last migration):

Remove-migration

It will clean up the mess and put you back where you need to be, even though the last migration folder was deleted manually.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

This solved my problem: Kotlin Code:

val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()

How is commitAllowingStateLoss() is different than commit() ?

As per documentation:

Like commit() but allows the commit to be executed after an activity's state is saved. https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()

P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

How to read text files with ANSI encoding and non-English letters?

You get the question-mark-diamond characters when your textfile uses high-ANSI encoding -- meaning it uses characters between 127 and 255. Those characters have the eighth (i.e. the most significant) bit set. When ASP.NET reads the textfile it assumes UTF-8 encoding, and that most significant bit has a special meaning.

You must force ASP.NET to interpret the textfile as high-ANSI encoding, by telling it the codepage is 1252:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML

How to get the unix timestamp in C#

As of .NET 4.6, there is DateTimeOffset.ToUnixTimeSeconds.


This is an instance method, so you are expected to call it on an instance of DateTimeOffset. You can also cast any instance of DateTime, though beware the timezone. To get the current timestamp:

DateTimeOffset.Now.ToUnixTimeSeconds()

To get the timestamp from a DateTime:

DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();

How to replace multiple patterns at once with sed?

I believe this should solve your problem. I may be missing a few edge cases, please comment if you notice one.

You need a way to exclude previous substitutions from future patterns, which really means making outputs distinguishable, as well as excluding these outputs from your searches, and finally making outputs indistinguishable again. This is very similar to the quoting/escaping process, so I'll draw from it.

  • s/\\/\\\\/g escapes all existing backslashes
  • s/ab/\\b\\c/g substitutes raw ab for escaped bc
  • s/bc/\\a\\b/g substitutes raw bc for escaped ab
  • s/\\\(.\)/\1/g substitutes all escaped X for raw X

I have not accounted for backslashes in ab or bc, but intuitively, I would escape the search and replace terms the same way - \ now matches \\, and substituted \\ will appear as \.

Until now I have been using backslashes as the escape character, but it's not necessarily the best choice. Almost any character should work, but be careful with the characters that need escaping in your environment, sed, etc. depending on how you intend to use the results.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

<Django object > is not JSON serializable

simplejson and json don't work with django objects well.

Django's built-in serializers can only serialize querysets filled with django objects:

data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")

In your case, self.get_queryset() contains a mix of django objects and dicts inside.

One option is to get rid of model instances in the self.get_queryset() and replace them with dicts using model_to_dict:

from django.forms.models import model_to_dict

data = self.get_queryset()

for item in data:
   item['product'] = model_to_dict(item['product'])

return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")

Hope that helps.

How to run a program automatically as admin on Windows 7 at startup?

I think that using the task scheduler to autostart programs is not very user friendly, and sometimes it has had side effects for me (e.g. tray icon for a program is not added).

To remedy this, I have made a program called Elevated Startup that first relaunches itself with administrator privileges, then it launches all files in a directory. Since Elevated Startup is now elevated, all the programs it then launches is also given administrator privileges. The directory is on the start menu next to the classic Startup directory, and works very much the same.

You may encounter one UAC dialog when the program relaunches itself, depending on your UAC settings.

You can get the program here: https://stefansundin.github.io/elevatedstartup/