Programs & Examples On #Shockwave

Shockwave is a technology developed by Macromedia, Inc. that enables Web pages to include multimedia objects. Shockwave supports audio, animation, video and even processes user actions such as mouse clicks.

Can a website detect when you are using Selenium with chromedriver?

The bot detection I've seen seems more sophisticated or at least different than what I've read through in the answers below.

EXPERIMENT 1:

  1. I open a browser and web page with Selenium from a Python console.
  2. The mouse is already at a specific location where I know a link will appear once the page loads. I never move the mouse.
  3. I press the left mouse button once (this is necessary to take focus from the console where Python is running to the browser).
  4. I press the left mouse button again (remember, cursor is above a given link).
  5. The link opens normally, as it should.

EXPERIMENT 2:

  1. As before, I open a browser and the web page with Selenium from a Python console.

  2. This time around, instead of clicking with the mouse, I use Selenium (in the Python console) to click the same element with a random offset.

  3. The link doesn't open, but I am taken to a sign up page.

IMPLICATIONS:

  • opening a web browser via Selenium doesn't preclude me from appearing human
  • moving the mouse like a human is not necessary to be classified as human
  • clicking something via Selenium with an offset still raises the alarm

Seems mysterious, but I guess they can just determine whether an action originates from Selenium or not, while they don't care whether the browser itself was opened via Selenium or not. Or can they determine if the window has focus? Would be interesting to hear if anyone has any insights.

HTML5 Video not working in IE 11

I used MP4Box to decode the atom tags in the mp4. (MP4Box -v myfile.mp4) I also used ffmpeg to convert the mp41 to mp42. After comparing the differences and experimenting, I found that IE11 did not like that my original mp4 had two avC1 atoms inside stsd.

After deleting the duplicate avC1 in my original mp41 mp4, IE11 would play the mp4.

HTML5 video won't play in Chrome only

With some help from another person, we figured out it was an issue of ordering the source files within the HTML file. I learned that browsers accept the first usable format, and their seems to be an issue with the .m4v file, so I started with the .mp4, then .webm. Here's the order that works in Safari (even on my iPhone 5), Firefox, and Chrome:

<video width="100%" height="400" poster="assets/img/myVideo.jpg" controls="controls" preload="none">
      <!-- MP4 for Safari, IE9, iPhone, iPad, Android, and Windows Phone 7 -->
      <source type="video/mp4" src="assets/vid/PhysicsEtoys.mp4" />
      <!-- WebM/VP8 for Firefox4, Opera, and Chrome -->
      <source type="video/webm" src="assets/vid/PhysicsEtoys.webm" />
       <!-- M4V for Apple -->
      <source type="video/mp4" src="assets/vid/PhysicsEtoys.m4v" />
      <!-- Ogg/Vorbis for older Firefox and Opera versions -->
      <source type="video/ogg" src="assets/vid/PhysicsEtoys.ogv" />
      <!-- Subtitles -->
      <track kind="subtitles" src="assets/vid/subtitles.srt" srclang="en" />
      <track kind="subtitles" src="assets/vid/subtitles.vtt" srclang="en" />
      <!-- Flash fallback for non-HTML5 browsers without JavaScript -->
      <object width="100%" height="400" type="application/x-shockwave-flash" data="flashmediaelement.swf">
          <param name="movie" value="flashmediaelement.swf" />
          <param name="flashvars" value="controls=true&file=assets/vid/PhysicsEtoys.mp4" />
          <!-- Image as a last resort -->
          <img src="assets/img/myVideo.jpg" width="320" height="240" title="No video playback capabilities" />
      </object>
  </video>

Now, I'll have to re-check the encoding on the m4v file (perhaps an issue of Baseline vs Main, High, etc.).

Getting an Embedded YouTube Video to Auto Play and Loop

Here is the full list of YouTube embedded player parameters.

Relevant info:

autoplay (supported players: AS3, AS2, HTML5) Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

loop (supported players: AS3, HTML5) Values: 0 or 1. Default is 0. In the case of a single video player, a setting of 1 will cause the player to play the initial video again and again. In the case of a playlist player (or custom player), the player will play the entire playlist and then start again at the first video.

Note: This parameter has limited support in the AS3 player and in IFrame embeds, which could load either the AS3 or HTML5 player. Currently, the loop parameter only works in the AS3 player when used in conjunction with the playlist parameter. To loop a single video, set the loop parameter value to 1 and set the playlist parameter value to the same video ID already specified in the Player API URL:

http://www.youtube.com/v/VIDEO_ID?version=3&loop=1&playlist=VIDEO_ID

Use the URL above in your embed code (append other parameters too).

How can I embed a YouTube video on GitHub wiki pages?

Complete Example

Expanding on @MGA's Answer

While it's not possible to embed a video in Markdown you can "fake it" by including a valid linked image in your markup file, using this format:

[![IMAGE ALT TEXT](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE "Video Title")

Explanation of the Markdown

If this markup snippet looks complicated, break it down into two parts:

an image
![image alt text](https://example.com/link-to-image)
wrapped in a link
[link text](https://example.com/my-link "link title")

Example using Valid Markdown and YouTube Thumbnail:

Everything Is AWESOME

We are sourcing the thumbnail image directly from YouTube and linking to the actual video, so when the person clicks the image/thumbnail they will be taken to the video.

Code:

[![Everything Is AWESOME](https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

OR If you want to give readers a visual cue that the image/thumbnail is actually a playable video, take your own screenshot of the video in YouTube and use that as the thumbnail instead.

Example using Screenshot with Video Controls as Visual Cue:

Everything Is AWESOME

Code:

[![Everything Is AWESOME](http://i.imgur.com/Ot5DWAW.png)](https://youtu.be/StTqXEQ2l-Y?t=35s "Everything Is AWESOME")

 Clear Advantages

While this requires a couple of extra steps (a) taking the screenshot of the video and (b) uploading it so you can use the image as your thumbnail it does have 3 clear advantages:

  1. The person reading your markdown (or resulting html page) has a visual cue telling them they can watch the video (video controls encourage clicking)
  2. You can chose a specific frame in the video to use as the thumbnail (thus making your content more engaging)
  3. You can link to a specific time in the video from which play will start when the linked-image is clicked. (in our case from 35 seconds)

Taking and uploading a screenshot takes a few seconds but has a big payoff.

Works Everywhere!

Since this is standard markdown, it works everywhere. try it on GitHub, Reddit, Ghost, and here on Stack Overflow.

Vimeo

This approach also works with Vimeo videos

Example

Little red riding hood

Code

[![Little red riding hood](http://i.imgur.com/7YTMFQp.png)](https://vimeo.com/3514904 "Little red riding hood - Click to Watch!")

Notes:

changing source on html5 video tag

I have a similar web app and am not facing that sort of problem at all. What i do is something like this:

var sources = new Array();

sources[0] = /path/to/file.mp4
sources[1] = /path/to/another/file.ogg
etc..

then when i want to change the sources i have a function that does something like this:

this.loadTrack = function(track){
var mediaSource = document.getElementsByTagName('source')[0];
mediaSource.src = sources[track];

    var player = document.getElementsByTagName('video')[0];
    player.load();

}

I do this so that the user can make their way through a playlist, but you could check for userAgent and then load the appropriate file that way. I tried using multiple source tags like everyone on the internet suggested, but i found it much cleaner, and much more reliable to manipulate the src attribute of a single source tag. The code above was written from memory, so i may have glossed over some of hte details, but the general idea is to dynamically change the src attribute of the source tag using javascript, when appropriate.

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

How to make an embedded video not autoplay

Try adding these after <Playlist>

<AutoLoad>false</AutoLoad>
<AutoPlay>false</AutoPlay>

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

Organizing a multiple-file Go project

Keep the files in the same directory and use package main in all files.

myproj/
   your-program/
      main.go
      lib.go

Then run:

~/myproj/your-program$ go build && ./your-program

How to reshape data from long to wide format

Using reshape function:

reshape(dat1, idvar = "name", timevar = "numbers", direction = "wide")

PHP array() to javascript array()

 <script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
 $(function() {
     function disableRangeOfDays(d) {

in the above assign array to javascript variable "disableDaysRange"

$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
 $disallowDates .= "'".$disableDates."',";
}

echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";

so your javascript var diableDateRange shoudl be 

var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];

Maintain model of scope when changing between views in AngularJS

Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons

UI Router & UI Router Extras

These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.

Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.

C++ deprecated conversion from string constant to 'char*'

As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:

void foo(char* str);
foo("hello");

However, if you want to keep your code warning-free as well then just make respective change in your code:

void foo(char* str);
foo((char *)"hello");

That is, simply cast the string constant to (char *).

Timestamp Difference In Hours for PostgreSQL

extract(hour from age(now(),links.created)) gives you a floor-rounded count of the hour difference.

Test or check if sheet exists

As checking for members of a collection is a general problem, here is an abstracted version of Tim's answer:

Function Contains(objCollection As Object, strName as String) As Boolean
    Dim o as Object
    On Error Resume Next
    set o = objCollection(strName)
    Contains = (Err.Number = 0)
    Err.Clear
 End Function

This function can be used with any collection like object (Shapes, Range, Names, Workbooks, etc.).

To check for the existence of a sheet, use If Contains(Sheets, "SheetName") ...

Difference between <input type='submit' /> and <button type='submit'>text</button>

In summary :

<input type="submit">

<button type="submit"> Submit </button>

Both by default will visually draw a button that performs the same action (submit the form).

However, it is recommended to use <button type="submit"> because it has better semantics, better ARIA support and it is easier to style.

Create a simple 10 second countdown

_x000D_
_x000D_
var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');_x000D_
    var total_timers = seconds_inputs.length;_x000D_
    for ( var i = 0; i < total_timers; i++){_x000D_
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';_x000D_
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
        var cal_seconds = seconds_inputs[i].getAttribute('value');_x000D_
_x000D_
        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');_x000D_
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');_x000D_
    }_x000D_
    function timer() {_x000D_
        for ( var i = 0; i < total_timers; i++) {_x000D_
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
_x000D_
            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);_x000D_
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));_x000D_
            var hours = Math.floor(hoursLeft / 3600);_x000D_
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));_x000D_
            var minutes = Math.floor(minutesLeft / 60);_x000D_
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;_x000D_
_x000D_
            function pad(n) {_x000D_
                return (n < 10 ? "0" + n : n);_x000D_
            }_x000D_
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);_x000D_
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);_x000D_
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);_x000D_
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);_x000D_
_x000D_
            if (eval('seconds_'+ seconds_prod_id) == 0) {_x000D_
                clearInterval(countdownTimer);_x000D_
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);_x000D_
            } else {_x000D_
                var value = eval('seconds_'+seconds_prod_id);_x000D_
                value--;_x000D_
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
_x000D_
    var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">_x000D_
<div class="box-wrapper">_x000D_
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper hidden-md">_x000D_
    <div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to negate a method reference predicate

If you're using Spring Boot (2.0.0+) you can use:

import org.springframework.util.StringUtils;

...
.filter(StringUtils::hasLength)
...

Which does: return (str != null && !str.isEmpty());

So it will have the required negation effect for isEmpty

How to make multiple divs display in one line but still retain width?

You can float your column divs using float: left; and give them widths.

And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.

Hope this helps.

Resizing an image in an HTML5 canvas

This is a javascript function adapted from @Telanor's code. When passing a image base64 as first argument to the function, it returns the base64 of the resized image. maxWidth and maxHeight are optional.

function thumbnail(base64, maxWidth, maxHeight) {

  // Max size for thumbnail
  if(typeof(maxWidth) === 'undefined') var maxWidth = 500;
  if(typeof(maxHeight) === 'undefined') var maxHeight = 500;

  // Create and initialize two canvas
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  var canvasCopy = document.createElement("canvas");
  var copyContext = canvasCopy.getContext("2d");

  // Create original image
  var img = new Image();
  img.src = base64;

  // Determine new ratio based on max size
  var ratio = 1;
  if(img.width > maxWidth)
    ratio = maxWidth / img.width;
  else if(img.height > maxHeight)
    ratio = maxHeight / img.height;

  // Draw original image in second canvas
  canvasCopy.width = img.width;
  canvasCopy.height = img.height;
  copyContext.drawImage(img, 0, 0);

  // Copy and resize second canvas to first canvas
  canvas.width = img.width * ratio;
  canvas.height = img.height * ratio;
  ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

  return canvas.toDataURL();

}

How to use BigInteger?

BigInteger is immutable. The javadocs states that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum, you need to reassign the result of the add method to sum variable.

sum = sum.add(BigInteger.valueOf(i));

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

java.net.SocketTimeoutException: Read timed out under Tomcat

Here are the basic instructions:-

  1. Locate the "server.xml" file in the "conf" folder beneath Tomcat's base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out - this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.
  5. Restart Tomcat

Best /Fastest way to read an Excel Sheet into a DataTable?

Here is another way of doing it

public DataSet CreateTable(string source)
{
    using (var connection = new OleDbConnection(GetConnectionString(source, true)))
    {
        var dataSet = new DataSet();
        connection.Open();
        var schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (schemaTable == null)
            return dataSet;

        var sheetName = "";
        foreach (DataRow row in schemaTable.Rows)
        {
            sheetName = row["TABLE_NAME"].ToString();
            break;
        }

        var command = string.Format("SELECT * FROM [{0}$]", sheetName);
        var adapter = new OleDbDataAdapter(command, connection);
        adapter.TableMappings.Add("TABLE", "TestTable");
        adapter.Fill(dataSet);
        connection.Close();

        return dataSet;
    }
}

//

private string GetConnectionString(string source, bool hasHeader)
{
    return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
    Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", source, (hasHeader ? "YES" : "NO"));
}

How do I compare two variables containing strings in JavaScript?

You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.

<script>
    var to_check=$(this).val();
    var cur_string=$("#0").text();
    var to_chk = "that";
    var cur_str= "that";
    if(to_chk.localeCompare(cur_str) == 0){
        alert("both are equal");
        $("#0").attr("class","correct");    
    } else {
        alert("both are not equal");
        $("#0").attr("class","incorrect");
    }
</script>

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

What are Bearer Tokens and token_type in OAuth 2?

token_type is a parameter in Access Token generate call to Authorization server, which essentially represents how an access_token will be generated and presented for resource access calls. You provide token_type in the access token generation call to an authorization server.

If you choose Bearer (default on most implementation), an access_token is generated and sent back to you. Bearer can be simply understood as "give access to the bearer of this token." One valid token and no question asked. On the other hand, if you choose Mac and sign_type (default hmac-sha-1 on most implementation), the access token is generated and kept as secret in Key Manager as an attribute, and an encrypted secret is sent back as access_token.

Yes, you can use your own implementation of token_type, but that might not make much sense as developers will need to follow your process rather than standard implementations of OAuth.

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

Due to controversial votes on this answer (+4/-4 as of this edit), PLEASE LOOK AT THE OTHER ANSWERS FIRST AND USE THIS ONLY AS A LAST RESORT. I only used this once for a networking app that runs as root and I agree with the general opinion that this solution should not be used under normal circumstances.

Original answer below:

The other answers are all correct, but I'd like to point out that another way to get around this is to ask user to disable battery optimizations for your app (this isn't usually a good idea unless your app is system related). See this answer for how to request to opt out of battery optimizations without getting your app banned in Google Play.

You should also check whether battery optimizations are turned off in your receiver to prevent crashes via:

if (Build.VERSION.SDK_INT < 26 || getSystemService<PowerManager>()
        ?.isIgnoringBatteryOptimizations(packageName) != false) {
    startService(Intent(context, MyService::class.java))
} // else calling startService will result in crash

Moment.js with ReactJS (ES6)

 import moment from 'moment';
 .....

  render() {
   return (
    <div>
        { 
        this.props.data.map((post,key) => 
            <div key={key} className="post-detail">
                <h1>{post.title}</h1>
                <p>{moment(post.date).calendar()}</p>
                <p dangerouslySetInnerHTML={{__html: post.content}}></p>
                <hr />
            </div>
        )}
    </div>
   );
  }

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

Kill server.pid by using command:

kill -9 `cat /root/myapp/tmp/pids/server.pid`

Note: Use your server.pid path which display in console/terminal.

Thank you.

How to center and crop an image to always appear in square shape with CSS?

object-fit property does the magic. On JsFiddle.

CSS

.image {
  width: 160px;
  height: 160px;
}

.object-fit_fill {
  object-fit: fill
}

.object-fit_contain {
  object-fit: contain
}

.object-fit_cover {
  object-fit: cover
}

.object-fit_none {
  object-fit: none
}

.object-fit_scale-down {
  object-fit: scale-down
}

HTML

<div class="original-image">
  <p>original image</p>
  <img src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: fill</p>
  <img class="object-fit_fill" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: contain</p>
  <img class="object-fit_contain" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: cover</p>
  <img class="object-fit_cover" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: none</p>
  <img class="object-fit_none" src="http://lorempixel.com/500/200">
</div>

<div class="image">
  <p>object-fit: scale-down</p>
  <img class="object-fit_scale-down" src="http://lorempixel.com/500/200">
</div>

Result

How the rendered images look (in a browser that supports <code>object-fit</code>)

SUM of grouped COUNT in SQL Query

Try this:

SELECT  ISNULL(Name,'SUM'), count(*) as Count
FROM table_name
Group By Name
WITH ROLLUP

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

How to get previous page url using jquery

Use can use one of below this

history.back();     // equivalent to clicking back button
history.go(-1);     // equivalent to history.back();

I am using as below for back button

<a class="btn btn-info float-right" onclick="history.back();" >Back</a>

Disabled UIButton not faded or grey

In Swift:

previousCustomButton.enabled = false
previousCustomButton.alpha = 0.5

or

nextCustomButton.enabled = true
nextCustomButton.alpha = 1.0

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

Install lxml from http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml for your python version. It's a precompiled WHL with required modules/dependencies.

The site lists several packages, when e.g. using Win32 Python 3.9, use lxml-4.5.2-cp39-cp39-win32.whl.

Download the file, and then install with:

pip install C:\path\to\downloaded\file\lxml-4.5.2-cp39-cp39-win32.whl

Override browser form-filling and input highlighting with HTML/CSS

<form autocomplete="off">

Pretty much all modern browsers will respect that.

Backup a single table with its data from a database in sql server 2008

Another approach you can take if you need to back up a single table out of multiple tables in a database is:

  1. Generate script of specific table(s) from a database (Right-click database, click Task > Generate Scripts...

  2. Run the script in the query editor. You must change/add the first line (USE DatabaseName) in the script to a new database, to avoid getting the "Database already exists" error.

  3. Right-click on the newly created database, and click on Task > Back Up... The backup will contain the selected table(s) from the original database.

How to get phpmyadmin username and password

If you don't remember your password, then run this command in the Shell:

mysqladmin.exe -u root password NewPassword

where 'NewPassword' is your new password.

How to split data into 3 sets (train, validation and test)?

In the case of supervised learning, you may want to split both X and y (where X is your input and y the ground truth output). You just have to pay attention to shuffle X and y the same way before splitting.

Here, either X and y are in the same dataframe, so we shuffle them, separate them and apply the split for each (just like in chosen answer), or X and y are in two different dataframes, so we shuffle X, reorder y the same way as the shuffled X and apply the split to each.

# 1st case: df contains X and y (where y is the "target" column of df)
df_shuffled = df.sample(frac=1)
X_shuffled = df_shuffled.drop("target", axis = 1)
y_shuffled = df_shuffled["target"]

# 2nd case: X and y are two separated dataframes
X_shuffled = X.sample(frac=1)
y_shuffled = y[X_shuffled.index]

# We do the split as in the chosen answer
X_train, X_validation, X_test = np.split(X_shuffled, [int(0.6*len(X)),int(0.8*len(X))])
y_train, y_validation, y_test = np.split(y_shuffled, [int(0.6*len(X)),int(0.8*len(X))])

How do I view an older version of an SVN file?

You can update to an older revision:

svn update -r 666 file

Or you can just view the file directly:

svn cat -r 666 file | less

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

How to check a Long for null in java

You can check Long object for null value with longValue == null , you can use longValue == 0L for long (primitive), because default value of long is 0L, but it's result will be true if longValue is zero too

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Inspired by TheIT, I just got this to work by manipulating the manifest file but in a slightly different fashion. Set the icon in the application setting so that the majority of the activities get the icon. On the activity where you want to show the logo, add the android:logo attribute to the activity declaration. In the following example, only LogoActivity should have the logo, while the others will default to icon.

<application
    android:name="com.your.app"
    android:icon="@drawable/your_icon"
    android:label="@string/app_name">

    <activity
        android:name="com.your.app.LogoActivity"
        android:logo="@drawable/your_logo"
        android:label="Logo Activity" >

    <activity
        android:name="com.your.app.IconActivity1"
        android:label="Icon Activity 1" >

    <activity
        android:name="com.your.app.IconActivity2"
        android:label="Icon Activity 2" >

</application>

Hope this helps someone else out!

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Switch statement for greater-than/less-than

This is another option:

     switch (true) {
         case (value > 100):
             //do stuff
             break;
         case (value <= 100)&&(value > 75):
             //do stuff
             break;
         case (value < 50):
            //do stuff
             break;
     }

How to analyze disk usage of a Docker container

I use docker stats $(docker ps --format={{.Names}}) --no-stream to get :

  1. CPU usage,
  2. Mem usage/Total mem allocated to container (can be allocate with docker run command)
  3. Mem %
  4. Block I/O
  5. Net I/O

Can you pass parameters to an AngularJS controller on creation?

It looks like the best solution for you is actually a directive. This allows you to still have your controller, but define custom properties for it.

Use this if you need access to variables in the wrapping scope:

angular.module('myModule').directive('user', function ($filter) {
  return {
    link: function (scope, element, attrs) {
      $scope.connection = $resource('api.com/user/' + attrs.userId);
    }
  };
});

<user user-id="{% id %}"></user>

Use this if you don't need access to variables in the wrapping scope:

angular.module('myModule').directive('user', function ($filter) {
  return {
    scope: {
      userId: '@'
    },
    link: function (scope, element, attrs) {
      $scope.connection = $resource('api.com/user/' + scope.userId);
    }
  };
});

<user user-id="{% id %}"></user>

How do I find out my MySQL URL, host, port and username?

mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+---------------+-----------+
| Variable_name | Value     |
+---------------+-----------+
| hostname      | karola-pc |
+---------------+-----------+
1 row in set (0.00 sec)

For Example in my case : karola-pc is the host name of the box where my mysql is running. And it my local PC host name.

If it is romote box than you can ping that host directly if, If you are in network with that box you should be able to ping that host.

If it UNIX or Linux you can run "hostname" command in terminal to check the host name. if it is windows you can see same value in MyComputer-> right click -> properties ->Computer Name you can see ( i.e System Properties)

Hope it will answer your Q.

What is the preferred Bash shebang?

#!/bin/sh

as most scripts do not need specific bash feature and should be written for sh.

Also, this makes scripts work on the BSDs, which do not have bash per default.

Format Date time in AngularJS

Simplly if you want to output like "Jan 30, 2017 4:31:20 PM" then follow to simple step

step1- Declare following variable in js controller

$scope.current_time = new Date();

step2- display in html page like

{{current_time | date:'medium'}}

Anaconda / Python: Change Anaconda Prompt User Path

If you want to access folder you specified using Anaconda Prompt, try typing

cd C:\Users\u354590

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

In IDEA 13 this seems to no longer be an issue, you just have to have the Lombok plugin installed.

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

How do I add PHP code/file to HTML(.html) files?

By default you can't use PHP in HTML pages.

To do that, modify your .htacccess file with the following:

AddType application/x-httpd-php .html

Inserting data into a temporary table

After you create the temp table you would just do a normal INSERT INTO () SELECT FROM

INSERT INTO #TempTable (id, Date, Name)
SELECT t.id, t.Date, t.Name
FROM yourTable t

Classpath including JAR within a JAR

If you are building with ant (I am using ant from eclipse), you can just add the extra jar files by saying to ant to add them... Not necessarily the best method if you have a project maintained by multiple people but it works for one person project and is easy.

for example my target that was building the .jar file was:

<jar destfile="${plugin.jar}" basedir="${plugin.build.dir}">
    <manifest>
        <attribute name="Author" value="ntg"/>
        ................................
        <attribute name="Plugin-Version" value="${version.entry.commit.revision}"/>
    </manifest>
</jar>

I just added one line to make it:

<jar ....">
    <zipgroupfileset dir="${external-lib-dir}" includes="*.jar"/>
    <manifest>
        ................................
    </manifest>
</jar>

where

<property name="external-lib-dir" 
          value="C:\...\eclipseWorkspace\Filter\external\...\lib" />

was the dir with the external jars. And that's it...

Bootstrap modal - close modal when "call to action" button is clicked

Remove your script, and change the HTML:

<a id="closemodal" href="https://www.google.com" class="btn btn-primary close" data-dismiss="modal" target="_blank">Launch google.com</a>

EDIT: Please note that currently this will not work as this functionality does not yet exist in bootstrap. See issue here.

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

As a windows user, run an Admin powershell and launch :

python -m pip install --upgrade pip

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

I think, the reason of the error from JDBC driver, you should get suitable JDBC driver for your Oracle db. You can get it from

http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html

Change select box option background color

Another option is to use Javascript:

if (document.getElementById('selectID').value == '1') {
       document.getElementById('optionID').style.color = '#000';

(Not as clean as the CSS attribute selector, but more powerful)

How to use a table type in a SELECT FROM statement?

In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this

create type exch_row as object (
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);

create type exch_tbl as table of exch_row;

And then you can use it in SQL with TABLE operator, for example:

declare
   l_row     exch_row;
   exch_rt   exch_tbl;
begin
   l_row := exch_row('PLN', 100, 100);
   exch_rt  := exch_tbl(l_row);

   for r in (select i.*
               from item i, TABLE(exch_rt) rt
              where i.currency = rt.currency_cd) loop
      -- your code here
   end loop;
end;
/

Android Stop Emulator from Command Line

To stop all running emulators we use this command:

adb devices | grep emulator | cut -f1 | while read line; do adb -s $line emu kill; done

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

How can I sort generic list DESC and ASC?

Very simple way to sort List with int values in Descending order:

li.Sort((a,b)=> b-a);

Hope that this helps!

"The Controls collection cannot be modified because the control contains code blocks"

The "<%#" databinding technique will not directly work inside <link> tags in the <head> tag:

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# My.Constants.CSS_VERSION %>" />

</head>

The above code will evaluate to

<head>

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=&lt;%# My.Constants.CSS_VERSION %>" />

</head>

Instead, you should do the following (note the two double quotes inside):

<head runat="server">

  <link rel="stylesheet" type="text/css" 
        href="css/style.css?v=<%# "" + My.Constants.CSS_VERSION %>" />

</head>

And you will get the desired result:

<head>

  <link rel="stylesheet" type="text/css" href="css/style.css?v=1.5" />

</head>

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

What's the difference between REST & RESTful

A service based on REST is called a "RESTful service".

Source I rely on posting that: Dr.Dobbs Archive

Getting individual colors from a color map in matplotlib

In order to get rgba integer value instead of float value, we can do

rgba = cmap(0.5,bytes=True)

So to simplify the code based on answer from Ffisegydd, the code would be like this:

#import colormap
from matplotlib import cm

#normalize item number values to colormap
norm = matplotlib.colors.Normalize(vmin=0, vmax=1000)

#colormap possible values = viridis, jet, spectral
rgba_color = cm.jet(norm(400),bytes=True) 

#400 is one of value between 0 and 1000

Running a cron job at 2:30 AM everyday

crontab -e

add:

30 2 * * * /your/command

Share Text on Facebook from Android App via ACTION_SEND

It appears that it's a bug in the Facebook app that was reported in April 2011 and has still yet to be fixed by the Android Facebook developers.

The only work around for the moment is to use their SDK.

Convert a number range to another range, maintaining ratio

C++ Variant

I found PenguinTD's Solution usefull, so i ported it to C++ if anyone needs it:

float remap(float x, float oMin, float oMax, float nMin, float nMax ){

//range check
if( oMin == oMax) {
    //std::cout<< "Warning: Zero input range";
    return -1;    }

if( nMin == nMax){
    //std::cout<<"Warning: Zero output range";
    return -1;        }

//check reversed input range
bool reverseInput = false;
float oldMin = min( oMin, oMax );
float oldMax = max( oMin, oMax );
if (oldMin == oMin)
    reverseInput = true;

//check reversed output range
bool reverseOutput = false;  
float newMin = min( nMin, nMax );
float newMax = max( nMin, nMax );
if (newMin == nMin)
    reverseOutput = true;

float portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin);
if (reverseInput)
    portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);

float result = portion + newMin;
if (reverseOutput)
    result = newMax - portion;

return result; }

Using Tkinter in python to edit the title bar

If you don't create a root window, Tkinter will create one for you when you try to create any other widget. Thus, in your __init__, because you haven't yet created a root window when you initialize the frame, Tkinter will create one for you. Then, you call make_widgets which creates a second root window. That is why you are seeing two windows.

A well-written Tkinter program should always explicitly create a root window before creating any other widgets.

When you modify your code to explicitly create the root window, you'll end up with one window with the expected title.

Example:

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self,parent=None):
        Frame.__init__(self,parent)
        self.parent = parent
        self.pack()
        self.make_widgets()

    def make_widgets(self):
        # don't assume that self.parent is a root window.
        # instead, call `winfo_toplevel to get the root window
        self.winfo_toplevel().title("Simple Prog")

        # this adds something to the frame, otherwise the default
        # size of the window will be very small
        label = Entry(self)
        label.pack(side="top", fill="x")

root = Tk()
abc = ABC(root)
root.mainloop()

Also note the use of self.make_widgets() rather than ABC.make_widgets(self). While both end up doing the same thing, the former is the proper way to call the function.

How do I escape a single quote in SQL Server?

Double quotes option helped me

SET QUOTED_IDENTIFIER OFF;
insert into my_table values("hi, my name's tim.");
SET QUOTED_IDENTIFIER ON;

Javascript get Object property Name

If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA

Ignore outliers in ggplot2 boxplot

The "coef" option of the geom_boxplot function allows to change the outlier cutoff in terms of interquartile ranges. This option is documented for the function stat_boxplot. To deactivate outliers (in other words they are treated as regular data), one can instead of using the default value of 1.5 specify a very high cutoff value:

library(ggplot2)
# generate data with outliers:
df = data.frame(x=1, y = c(-10, rnorm(100), 10)) 
# generate plot with increased cutoff for outliers:
ggplot(df, aes(x, y)) + geom_boxplot(coef=1e30)

How to write to the Output window in Visual Studio?

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

wstring outputMe = L"can" + L" concatenate\n";
OutputDebugString(outputMe.c_str());

Difference between private, public, and protected inheritance

Limiting the visibility of inheritance will make code not able to see that some class inherits another class: Implicit conversions from the derived to the base won't work, and static_cast from the base to the derived won't work either.

Only members/friends of a class can see private inheritance, and only members/friends and derived classes can see protected inheritance.

public inheritance

  1. IS-A inheritance. A button is-a window, and anywhere where a window is needed, a button can be passed too.

    class button : public window { };
    

protected inheritance

  1. Protected implemented-in-terms-of. Rarely useful. Used in boost::compressed_pair to derive from empty classes and save memory using empty base class optimization (example below doesn't use template to keep being at the point):

    struct empty_pair_impl : protected empty_class_1 
    { non_empty_class_2 second; };
    
    struct pair : private empty_pair_impl {
      non_empty_class_2 &second() {
        return this->second;
      }
    
      empty_class_1 &first() {
        return *this; // notice we return *this!
      }
    };
    

private inheritance

  1. Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here

    template<typename StorageModel>
    struct string : private StorageModel {
    public:
      void realloc() {
        // uses inherited function
        StorageModel::realloc();
      }
    };
    

public member

  1. Aggregate

    class pair {
    public:
      First first;
      Second second;
    };
    
  2. Accessors

    class window {
    public:
        int getWidth() const;
    };
    

protected member

  1. Providing enhanced access for derived classes

    class stack {
    protected:
      vector<element> c;
    };
    
    class window {
    protected:
      void registerClass(window_descriptor w);
    };
    

private member

  1. Keep implementation details

    class window {
    private:
      int width;
    };
    

Note that C-style casts purposely allows casting a derived class to a protected or private base class in a defined and safe manner and to cast into the other direction too. This should be avoided at all costs, because it can make code dependent on implementation details - but if necessary, you can make use of this technique.

SVG fill color transparency / alpha?

fill="#044B9466"

This is an RGBA color in hex notation inside the SVG, defined with hex values. This is valid, but not all programs can display it properly...

You can find the browser support for this syntax here: https://caniuse.com/#feat=css-rrggbbaa

As of August 2017: RGBA fill colors will display properly on Mozilla Firefox (54), Apple Safari (10.1) and Mac OS X Finder's "Quick View". However Google Chrome did not support this syntax until version 62 (was previously supported from version 54 with the Experimental Platform Features flag enabled).

VB.NET - Click Submit Button on Webbrowser page

You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.

How to declare a type as nullable in TypeScript?

All fields in JavaScript (and in TypeScript) can have the value null or undefined.

You can make the field optional which is different from nullable.

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

Compare with:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

Performing a Stress Test on Web Application?

I've used The Grinder. It's open source, pretty easy to use, and very configurable. It is Java based and uses Jython for the scripts. We ran it against a .NET web application, so don't think it's a Java only tool (by their nature, any web stress tool should not be tied to the platform it uses).

We did some neat stuff with it... we were a web based telecom application, so one cool use I set up was to mimick dialing a number through our web application, then used an auto answer tool we had (which was basically a tutorial app from Microsoft to connect to their RTC LCS server... which is what Microsoft Office Communicator connects to on a local network... then modified to just pick up calls automatically). This then allowed us to use this instead of an expensive telephony tool called The Hammer (or something like that).

Anyways, we also used the tool to see how our application held up under high load, and it was very effective in finding bottlenecks. The tool has built in reporting to show how long requests are taking, but we never used it. The logs can also store all the responses and whatnot, or custom logging.

I highly recommend this tool, very useful for the price... but expect to do some custom setup with it (it has a built in proxy to record a script, but it may need customization for capturing something like sessions... I know I had to customize it to utilize a unique session per thread).

How do I change the default location for Git Bash on Windows?

Add this line to your .bashrc file:

cd C:/xampp/htdocs/<name of your project>;

If the .bashrc file doesn't exist, create one in your root folder. For me it is: C:\Users\tapas\

Save .bashrc and open Git Bash. That's it!

How to set 24-hours format for date on java?

Try this...

Calendar calendar = Calendar.getInstance();
String currentDate24Hrs = (String) DateFormat.format(
            "MM/dd/yyyy kk:mm:ss", calendar.getTime());
Log.i("DEBUG_TAG", "24Hrs format date: " + currentDate24Hrs);

Adding data attribute to DOM

 $(document.createElement("img")).attr({
                src: 'https://graph.facebook.com/'+friend.id+'/picture',
                title: friend.name ,
                'data-friend-id':friend.id,
                'data-friend-name':friend.name
            }).appendTo(divContainer);

A regular expression to exclude a word/string

As you want to exclude both words, you need a conjuction:

^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$

Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.

Adding class to element using Angular JS

try this code

<script>
       angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>

click the link and understand more

Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()

Setting environment variables for accessing in PHP when using Apache

Something along the lines:

<VirtualHost hostname:80>
   ...
   SetEnv VARIABLE_NAME variable_value
   ...
</VirtualHost>

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

and tests whether both expressions are logically True while & (when used with True/False values) tests if both are True.

In Python, empty built-in objects are typically treated as logically False while non-empty built-ins are logically True. This facilitates the common use case where you want to do something if a list is empty and something else if the list is not. Note that this means that the list [False] is logically True:

>>> if [False]:
...    print 'True'
...
True

So in Example 1, the first list is non-empty and therefore logically True, so the truth value of the and is the same as that of the second list. (In our case, the second list is non-empty and therefore logically True, but identifying that would require an unnecessary step of calculation.)

For example 2, lists cannot meaningfully be combined in a bitwise fashion because they can contain arbitrary unlike elements. Things that can be combined bitwise include: Trues and Falses, integers.

NumPy objects, by contrast, support vectorized calculations. That is, they let you perform the same operations on multiple pieces of data.

Example 3 fails because NumPy arrays (of length > 1) have no truth value as this prevents vector-based logic confusion.

Example 4 is simply a vectorized bit and operation.

Bottom Line

  • If you are not dealing with arrays and are not performing math manipulations of integers, you probably want and.

  • If you have vectors of truth values that you wish to combine, use numpy with &.

Pandas dataframe fillna() only some columns in place

Sometimes this syntax wont work:

df[['col1','col2']] = df[['col1','col2']].fillna()

Use the following instead:

df['col1','col2']

Gridview row editing - dynamic binding to a DropDownList

 <asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
            AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
            BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
            OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting">
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <Columns>
            <asp:TemplateField HeaderText="SerialNo">
            <ItemTemplate>
            <%# Container .DataItemIndex+1 %>.&nbsp
            </ItemTemplate>
            </asp:TemplateField>
                <asp:TemplateField HeaderText="RollNo">
                    <ItemTemplate>
                        <%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SName">
                    <ItemTemplate>
                    <%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="C">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
                        <asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cpp">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
                       <asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Java">
                    <ItemTemplate>
                       <%--  <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
                        <asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
                            CommandName="Update"></asp:LinkButton>
                        <asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
                            CommandName="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
                            Text="Edit"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
                <asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
            </Columns>
        </asp:GridView>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
                    <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
                    <asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
                    <asp:TextBox ID="txtc" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
                    <asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
                    <asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
                    <asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
                </td>
            </tr>
        </table>

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Implicit wait --

Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).

Explicit wait--

Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling WebDriver at the max it is to wait for X units of time before it gives up.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

UPDATE: this is not the solution but it's a workaround for a problem that can cause the exception presented in the question.

I've solved changing from Release Configuration to Debug Configuration.

Why can't I shrink a transaction log file, even after backup?

Put the DB back into Full mode, run the transaction log backup (not just a full backup) and then the shrink.

After it's shrunk, you can put the DB back into simple mode and it txn log will stay the same size.

prevent iphone default keyboard when focusing an <input>

Best way to solve this as per my opinion is Using "ignoreReadonly".

First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show.

$('#txtStartDate').datetimepicker({
            locale: "da",
            format: "DD/MM/YYYY",
            ignoreReadonly: true
        });
        $('#txtEndDate').datetimepicker({
            locale: "da",
            useCurrent: false,
            format: "DD/MM/YYYY",
            ignoreReadonly: true
        });
});

How to force page refreshes or reloads in jQuery?

Replace that line with:

$("#someElement").click(function() {
    window.location.href = window.location.href;
});

or:

$("#someElement").click(function() {
    window.location.reload();
});

Node.js: Gzip compression?

Node v0.6.x has a stable zlib module in core now - there are some examples on how to use it server-side in the docs too.

An example (taken from the docs):

// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
  var raw = fs.createReadStream('index.html');
  var acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';
  }

  // Note: this is not a conformant accept-encoding parser.
  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  if (acceptEncoding.match(/\bdeflate\b/)) {
    response.writeHead(200, { 'content-encoding': 'deflate' });
    raw.pipe(zlib.createDeflate()).pipe(response);
  } else if (acceptEncoding.match(/\bgzip\b/)) {
    response.writeHead(200, { 'content-encoding': 'gzip' });
    raw.pipe(zlib.createGzip()).pipe(response);
  } else {
    response.writeHead(200, {});
    raw.pipe(response);
  }
}).listen(1337);

Remove directory which is not empty

There is a module for this called rimraf (https://npmjs.org/package/rimraf). It provides the same functionality as rm -Rf

Async usage:

var rimraf = require("rimraf");
rimraf("/some/directory", function () { console.log("done"); });

Sync usage:

rimraf.sync("/some/directory");

how to use json file in html code

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

Javascript - How to extract filename from a file input control

I assume you want to strip all extensions, i.e. /tmp/test/somefile.tar.gz to somefile.

Direct approach with regex:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

Alternative approach with regex and array operation:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Java socket API: How to tell if a connection has been closed?

As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.
This is a simple example that shows how to know the socket is closed by the server:

sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
socket = new Socket();
timeout = 5000;
socket.connect(sockAdr, timeout);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
while ((data = reader.readLine())!=null) 
      log.e(TAG, "received -> " + data);
log.e(TAG, "Socket closed !");

View tabular file such as CSV from command line

You can also use this:

column -s, -t < somefile.csv | less -#2 -N -S

column is a standard unix program that is very convenient -- it finds the appropriate width of each column, and displays the text as a nicely formatted table.

Note: whenever you have empty fields, you need to put some kind of placeholder in it, otherwise the column gets merged with following columns. The following example demonstrates how to use sed to insert a placeholder:

$ cat data.csv
1,2,3,4,5
1,,,,5
$ sed 's/,,/, ,/g;s/,,/, ,/g' data.csv | column -s, -t
1  2  3  4  5
1           5
$ cat data.csv
1,2,3,4,5
1,,,,5
$ column -s, -t < data.csv
1  2  3  4  5
1  5
$ sed 's/,,/, ,/g;s/,,/, ,/g' data.csv | column -s, -t
1  2  3  4  5
1           5

Note that the substitution of ,, for , , is done twice. If you do it only once, 1,,,4 will become 1, ,,4 since the second comma is matched already.

Nginx location priority

It fires in this order.

  1. = (exactly)

    location = /path

  2. ^~ (forward match)

    location ^~ /path

  3. ~ (regular expression case sensitive)

    location ~ /path/

  4. ~* (regular expression case insensitive)

    location ~* .(jpg|png|bmp)

  5. /

    location /path

Expression ___ has changed after it was checked

I got similar error while working with datatable. What happens is when you use *ngFor inside another *ngFor datatable throw this error as it interepts angular change cycle. SO instead of using datatable inside datatable use one regular table or replace mf.data with the array name. This works fine.

When should you use constexpr capability in C++11?

Have just started switching over a project to c++11 and came across a perfectly good situation for constexpr which cleans up alternative methods of performing the same operation. The key point here is that you can only place the function into the array size declaration when it is declared constexpr. There are a number of situations where I can see this being very useful moving forward with the area of code that I am involved in.

constexpr size_t GetMaxIPV4StringLength()
{
    return ( sizeof( "255.255.255.255" ) );
}

void SomeIPFunction()
{
    char szIPAddress[ GetMaxIPV4StringLength() ];
    SomeIPGetFunction( szIPAddress );
}

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

How to keep the header static, always on top while scrolling?

I personally needed a table with both the left and top headers visible at all times. Inspired by several articles, I think I have a good solution that you may find helpful. This version does not have the wrapping problem that other soltions have with floating divs or flexible/auto sizing of columns and rows.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script language="javascript" type="text/javascript" src="/Scripts/jquery-1.7.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        // Handler for scrolling events
        function scrollFixedHeaderTable() {
            var outerPanel = $("#_outerPanel");
            var cloneLeft = $("#_cloneLeft");
            var cloneTop = $("#_cloneTop");
            cloneLeft.css({ 'margin-top': -outerPanel.scrollTop() });
            cloneTop.css({ 'margin-left': -outerPanel.scrollLeft() });
        }

        function initFixedHeaderTable() {
            var outerPanel = $("#_outerPanel");
            var innerPanel = $("#_innerPanel");
            var clonePanel = $("#_clonePanel");
            var table = $("#_table");
            // We will clone the table 2 times: For the top rowq and the left column. 
            var cloneLeft = $("#_cloneLeft");
            var cloneTop = $("#_cloneTop");
            var cloneTop = $("#_cloneTopLeft");
            // Time to create the table clones
            cloneLeft = table.clone();
            cloneTop = table.clone();
            cloneTopLeft = table.clone();
            cloneLeft.attr('id', '_cloneLeft');
            cloneTop.attr('id', '_cloneTop');
            cloneTopLeft.attr('id', '_cloneTopLeft');
            cloneLeft.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 1 // keep lower than top-left below
            });
            cloneTop.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 1 // keep lower than top-left below
            });
            cloneTopLeft.css({
                position: 'fixed',
                'pointer-events': 'none',
                top: outerPanel.offset().top,
                'z-index': 2 // higher z-index than the left and top to make the top-left header cell logical
            });
            // Add the controls to the control-tree
            clonePanel.append(cloneLeft);
            clonePanel.append(cloneTop);
            clonePanel.append(cloneTopLeft);
            // Keep all hidden: We will make the individual header cells visible in a moment
            cloneLeft.css({ visibility: 'hidden' });
            cloneTop.css({ visibility: 'hidden' });
            cloneTopLeft.css({ visibility: 'hidden' });
            // Make the lef column header cells visible in the left clone
            $("#_cloneLeft td._hdr.__row").css({
                visibility: 'visible',
            });
            // Make the top row header cells visible in the top clone
            $("#_cloneTop td._hdr.__col").css({
                visibility: 'visible',
            });
            // Make the top-left cell visible in the top-left clone
            $("#_cloneTopLeft td._hdr.__col.__row").css({
                visibility: 'visible',
            });
            // Clipping. First get the inner width/height by measuring it (normal innerWidth did not work for me)
            var helperDiv = $('<div style="positions: absolute; top: 0; right: 0; bottom: 0; left: 0; height: 100%;"></div>');
            outerPanel.append(helperDiv);
            var innerWidth = helperDiv.width();
            var innerHeight = helperDiv.height();
            helperDiv.remove(); // because we dont need it anymore, do we?
            // Make sure all the panels are clipped, or the clones will extend beyond them
            outerPanel.css({ clip: 'rect(0px,' + String(outerPanel.width()) + 'px,' + String(outerPanel.height()) + 'px,0px)' });
            // Clone panel clipping to prevent the clones from covering the outerPanel's scrollbars (this is why we use a separate div for this)
            clonePanel.css({ clip: 'rect(0px,' + String(innerWidth) + 'px,' + String(innerHeight) + 'px,0px)'   });
            // Subscribe the scrolling of the outer panel to our own handler function to move the clones as needed.
            $("#_outerPanel").scroll(scrollFixedHeaderTable);
        }


        $(document).ready(function () {
            initFixedHeaderTable();
        });

    </script>
    <style type="text/css">
        * {
            clip: rect font-family: Arial;
            font-size: 16px;
            margin: 0;
            padding: 0;
        }

        #_outerPanel {
            margin: 0px;
            padding: 0px;
            position: absolute;
            left: 50px;
            top: 50px;
            right: 50px;
            bottom: 50px;
            overflow: auto;
            z-index: 1000;
        }

        #_innerPanel {
            overflow: visible;
            position: absolute;
        }

        #_clonePanel {
            overflow: visible;
            position: fixed;
        }

        table {
        }

        td {
            white-space: nowrap;
            border-right: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 2px 2px 2px 2px;
        }

        td._hdr {
            color: Blue;
            font-weight: bold;
        }
        td._hdr.__row {
            background-color: #eee;
            border-left: 1px solid #000;
        }
        td._hdr.__col {
            background-color: #ddd;
            border-top: 1px solid #000;
        }
    </style>
</head>
<body>
    <div id="_outerPanel">
        <div id="_innerPanel">
            <div id="_clonePanel"></div>
            <table id="_table" border="0" cellpadding="0" cellspacing="0">
                <thead id="_topHeader" style="background-color: White;">
                    <tr class="row">
                        <td class="_hdr __col __row">
                            &nbsp;
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                        <td class="_hdr __col">
                            TOP HEADER
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr class="row">
                        <td class="_hdr __row">
                            MY HEADER COLUMN:
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                    </tr>
                    <tr class="row">
                        <td class="_hdr __row">
                            MY HEADER COLUMN:
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                        <td class="col">
                            The quick brown fox jumps over the lazy dog.
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div id="_bottomAnchor">
        </div>
    </div>
</body>
</html>

Using GSON to parse a JSON array

public static <T> List<T> toList(String json, Class<T> clazz) {
    if (null == json) {
        return null;
    }
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>(){}.getType());
}

sample call:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

What is the difference between "INNER JOIN" and "OUTER JOIN"?

Joins are more easily explained with an example:

enter image description here

To simulate persons and emails stored in separate tables,

Table A and Table B are joined by Table_A.id = Table_B.name_id

Inner Join

enter image description here

Only matched ids' rows are shown.

Outer Joins

enter image description here

Matched ids and not matched rows for Table A are shown.

enter image description here

Matched ids and not matched rows for Table B are shown.

enter image description here Matched ids and not matched rows from both Tables are shown.

Note: Full outer join is not available on MySQL

mean() warning: argument is not numeric or logical: returning NA

If you just want to know the mean, you can use

summary(results)

It will give you more information than expected.

ex) Mininum value, 1st Qu., Median, Mean, 3rd Qu. Maxinum value, number of NAs.

Furthermore, If you want to get mean values of each column, you can simply use the method below.

mean(results$columnName, na.rm = TRUE)

That will return mean value. (you have to change 'columnName' to your variable name

How to send 500 Internal Server Error error from a PHP script

Your code should look like:

<?php
if ( that_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

if ( something_else_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// the script can also fail on the above line
// e.g. a mysql error occurred


header('HTTP/1.1 200 OK');
?>

I assume you stop execution if something goes wrong.

How can I compare time in SQL Server?

I am assuming your startHour column and @startHour variable are both DATETIME; In that case, you should be converting to a string:

SELECT timeEvent
FROM tbEvents
WHERE convert(VARCHAR(8), startHour, 8) >= convert(VARCHAR(8), @startHour, 8)

Is optimisation level -O3 dangerous in g++?

Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.

Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

JavaScript: clone a function

Being curious but still unable to find the answer to the performance topic of the question above, I wrote this gist for nodejs to test both the performance and reliability of all presented (and scored) solutions.

I've compared the wall times of a clone function creation and the execution of a clone. The results together with assertion errors are included in the gist's comment.

Plus my two cents (based on the author's suggestion):

clone0 cent (faster but uglier):

Function.prototype.clone = function() {
  var newfun;
  eval('newfun=' + this.toString());
  for (var key in this)
    newfun[key] = this[key];
  return newfun;
};

clone4 cent (slower but for those who dislike eval() for purposes known only to them and their ancestors):

Function.prototype.clone = function() {
  var newfun = new Function('return ' + this.toString())();
  for (var key in this)
    newfun[key] = this[key];
  return newfun;
};

As for the performance, if eval/new Function is slower than wrapper solution (and it really depends on the function body size), it gives you bare function clone (and I mean the true shallow clone with properties but unshared state) without unnecessary fuzz with hidden properties, wrapper functions and problems with stack.

Plus there is always one important factor you need to take into consideration: the less code, the less places for mistakes.

The downside of using the eval/new Function is that the clone and the original function will operate in different scopes. It won't work well with functions that are using scoped variables. The solutions using bind-like wrapping are scope independent.

Gradient borders

Try this, works fine on web-kit

_x000D_
_x000D_
.border { _x000D_
    width: 400px;_x000D_
    padding: 20px;_x000D_
    border-top: 10px solid #FFFF00;_x000D_
    border-bottom:10px solid #FF0000;_x000D_
    background-image: _x000D_
        linear-gradient(#FFFF00, #FF0000),_x000D_
        linear-gradient(#FFFF00, #FF0000)_x000D_
    ;_x000D_
    background-size:10px 100%;_x000D_
    background-position:0 0, 100% 0;_x000D_
    background-repeat:no-repeat;_x000D_
}
_x000D_
<div class="border">Hello!</div>
_x000D_
_x000D_
_x000D_

jQuery not working with IE 11

For me the issue turned out to be I was using es6's right arrow functions => as opposed to function ().

Replacing => with function () resolved for me.

I had assumed it was a jQuery issue.

Enable/Disable Anchor Tags using AngularJS

Make a toggle function in the respective scope to grey out the link.

First,create the following CSS classes in your .css file.

.disabled {
    pointer-events: none;
    cursor: default;
}

.enabled {
    pointer-events: visible;
    cursor: auto;
}

Add a $scope.state and $scope.toggle variable. Edit your controller in the JS file like:

    $scope.state='on';
    $scope.toggle='enabled';
    $scope.changeState = function () {
                $scope.state = $scope.state === 'on' ? 'off' : 'on';
                $scope.toggleEdit();
            };
    $scope.toggleEdit = function () {
            if ($scope.state === 'on')
                $scope.toggle = 'enabled';
            else
                $scope.toggle = 'disabled';
        };

Now,in the HTML a tags edit as:

<a href="#" ng-click="create()" class="{{toggle}}">CREATE</a><br/>
<a href="#" ng-click="edit()" class="{{toggle}}">EDIT</a><br/>
<a href="#" ng-click="delete()" class="{{toggle}}">DELETE</a>

To avoid the problem of the link disabling itself, change the DOM CSS class at the end of the function.

document.getElementById("create").className = "enabled";

PHP code is not being executed, instead code shows on the page

I think the problem that it is showing code instead of the result is that it is not going to local host . recheck what address u r going in. are u going to a local file directory or to the local host.

from the screenshot u sent it is going to ur computer not to the localhost.

"file:/// " it should be "localhost/"

Convert string to a variable name

The function you are looking for is get():

assign ("abc",5)
get("abc")

Confirming that the memory address is identical:

getabc <- get("abc")
pryr::address(abc) == pryr::address(getabc)
# [1] TRUE

Reference: R FAQ 7.21 How can I turn a string into a variable?

Get a substring of a char*

Use char* strncpy(char* dest, char* src, int n) from <cstring>. In your case you will need to use the following code:

char* substr = malloc(4);
strncpy(substr, buff+10, 4);

Full documentation on the strncpy function here.

Sending data back to the Main Activity in Android

Another way of achieving the desired result which may be better depending on your situation is to create a listener interface.

By making the parent activity listen to an interface that get triggered by the child activity while passing the required data as a parameter can create a similar set of circumstance

get dataframe row count based on conditions

In Pandas, I like to use the shape attribute to get number of rows.

df[df.A > 0].shape[0]

gives the number of rows matching the condition A > 0, as desired.

Pretty Printing JSON with React

Here is a demo react_hooks_debug_print.html in react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>

    <script type="text/babel">

let styles = {
  root: { backgroundColor: '#1f4662', color: '#fff', fontSize: '12px', },
  header: { backgroundColor: '#193549', padding: '5px 10px', fontFamily: 'monospace', color: '#ffc600', },
  pre: { display: 'block', padding: '10px 30px', margin: '0', overflow: 'scroll', }
}

let data = {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

const DebugPrint = () => {
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} style={styles.root}>
    <div style={styles.header} onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre style={styles.pre}>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

ReactDOM.render(
  <DebugPrint data={data} />, 
  document.getElementById('root')
);

    </script>

  </body>
</html>

Or in the following way, add the style into header:

    <style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
    </style>

And replace DebugPrint with the follows:

const DebugPrint = () => {
  // https://stackoverflow.com/questions/30765163/pretty-printing-json-with-react
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} className='root'>
    <div className='header' onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre className='pre'>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

If '<selector>' is an Angular component, then verify that it is part of this module

Check which module the parent component is being declared in...

If your parent component is defined in the shared module, so must your child module.

The parent component could be declared in a shared module and not the module that is logical based on the file directory structure / naming, even the Angular CLI added it into the wrong module in my case.

Switch case on type c#

Update C# 7

Yes: Source

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Prior to C# 7

No.

http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx

We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:

switch typeof(e) { 
        case int:    ... break; 
        case string: ... break; 
        case double: ... break; 
        default:     ... break; 
}

This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"

Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:

class C {}
interface I {}
class D : C, I {}

switch typeof(e) {
case C: … break;
case I: … break;
default: … break;
}

Link: https://blogs.msdn.microsoft.com/peterhal/2005/07/05/many-questions-switch-on-type/

How do I create ColorStateList programmatically?

Bouncing off the answer by Jonathan Ellis, in Kotlin you can define a helper function to make the code a bit more idiomatic and easier to read, so you can write this instead:

val colorList = colorStateListOf(
    intArrayOf(-android.R.attr.state_enabled) to Color.BLACK,
    intArrayOf(android.R.attr.state_enabled) to Color.RED,
)

colorStateListOf can be implemented like this:

fun colorStateListOf(vararg mapping: Pair<IntArray, Int>): ColorStateList {
    val (states, colors) = mapping.unzip()
    return ColorStateList(states.toTypedArray(), colors.toIntArray())
}

I also have:

fun colorStateListOf(@ColorInt color: Int): ColorStateList {
    return ColorStateList.valueOf(color)
}

So that I can call the same function name, no matter if it's a selector or single color.

How to add an image to the emulator gallery in android studio?

It's a very old question but I will answer this for future references.

To add any file to emulator just drag and drop the file.

The file will be copied to downloads folder of internal storage.

To access the file

Go to settings

Click On Storage & USB

Click On Internal Storage

Click On Explore (at the end)

and you got it in the downloads folder

now you will get notification to setup virtual SD card, follow the setup. after the successful setup you will be able to see pictures in gallery.

Slick Carousel Uncaught TypeError: $(...).slick is not a function

I've had the same problem before recognized that I've put the code after closing the body tag. After moving it into tag, it's OK now

<body>
$(document).ready(function(){
    $('.multiple-items').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 3
    });
});
</body>

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

Read a plain text file with php

$filename = "fille.txt";
$fp = fopen($filename, "r");

$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
fclose($fp);
print_r($lines);

In this code full content of the file is copied to the variable $content and then split it into an array with each newline character in the file.

How to install pip with Python 3?

To install pip, securely download get-pip.py.

Then run the following:

python get-pip.py

Be cautious if you're using a Python install that's managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.

Refer: PIP Installation

How to have Java method return generic list of any type?

Something like this

publi? <T> List<T> magicalListGetter(Class<T> clazz) {
    List list = doMagicalVooDooHere();
    return list;
}

How to set an environment variable in a running docker container

Here's how you can modify a running container to update its environment variables. This assumes you're running on Linux. I tested it with Docker 19.03.8

Live Restore

First, ensure that your Docker daemon is set to leave containers running when it's shut down. Edit your /etc/docker/daemon.json, and add "live-restore": true as a top-level key.

sudo vim /etc/docker/daemon.json

My file looks like this:

{
    "default-runtime": "nvidia",
    "runtimes": {
        "nvidia": {
            "path": "nvidia-container-runtime",
            "runtimeArgs": []
        }
    },
    "live-restore": true
}

Taken from here.

Get the Container ID

Save the ID of the container you want to edit for easier access to the files.

export CONTAINER_ID=`docker inspect --format="{{.Id}}" <YOUR CONTAINER NAME>`

Edit Container Configuration

Edit the configuration file, go to the "Env" section, and add your key.

sudo vim /var/lib/docker/containers/$CONTAINER_ID/config.v2.json

My file looks like this:

...,"Env":["TEST=1",...

Stop and Start Docker

I found that restarting Docker didn't work, I had to stop and then start Docker with two separate commands.

sudo systemctl stop docker
sudo systemctl start docker

Because of live-restore, your containers should stay up.

Verify That It Worked

docker exec <YOUR CONTAINER NAME> bash -c 'echo $TEST'

Single quotes are important here.

You can also verify that the uptime of your container hasn't changed:

docker ps

How to force a component's re-rendering in Angular 2?

ChangeDetectorRef.detectChanges() is usually the most focused way of doing this. ApplicationRef.tick() is usually too much of a sledgehammer approach.

To use ChangeDetectorRef.detectChanges(), you'll need this at the top of your component:

import {  ChangeDetectorRef } from '@angular/core';

... then, usually you alias that when you inject it in your constructor like this:

constructor( private cdr: ChangeDetectorRef ) { ... }

Then, in the appropriate place, you call it like this:

this.cdr.detectChanges();

Where you call ChangeDetectorRef.detectChanges() can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges() appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).

Why should I use an IDE?

A very good reason for using IDEs is that they are the accepted way of producing modern software. If you do not use one, then you likely use "old fashioned" stuff like vi and emacs. This can lead people to conclude - possibly wrongly - that you are stuck in your ways and unable to adapt to new ways of working. In an industry such as software development - where ideas can be out of date in mere months - this is a dangerous state to get into. It could seriously damage your future job prospects...

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just use the interface provided by MySql's GUI Tool (SQLyog):

Click on User manager: enter image description here

Now, if you want to grant access FOR ANY OTHER REMOTE PC, just make sure that, just like in the underneath picture, the Host field value is % (which is the wildcard)

enter image description here

Making custom right-click context menus for my web-app

I have a nice and easy implementation using bootstrap as follows.

<select class="custom-select" id="list" multiple></select>

<div class="dropdown-menu" id="menu-right-click" style=>
    <h6 class="dropdown-header">Actions</h6>
    <a class="dropdown-item" href="" onclick="option1();">Option 1</a>
    <a class="dropdown-item" href="" onclick="option2();">Option 2</a>
</div>

<script>
    $("#menu-right-click").hide();

    $(document).on("contextmenu", "#list", function (e) {
        $("#menu-right-click")
            .css({
                position: 'absolute',
                left: e.pageX,
                top: e.pageY,
                display: 'block'
            })
        return false;
    });

    function option1() {
        // something you want...
        $("#menu-right-click").hide();
    }

    function option2() {
        // something else 
        $("#menu-right-click").hide();
    }
</script>

How can I check if a string is null or empty in PowerShell?

# cases
$x = null
$x = ''
$x = ' '

# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}

How to get bitmap from a url in android?

This should do the trick:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

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

In my case it was due to the Access Protection feature of my anti-virus (McAfee). It was obviously blocking access to this file, as of such the error.

I disabled it and the solution ran. You might want to check any utility application you might have running that could be affecting access to some files.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

It's possible that the HTML5 Doctype is causing you problems with those older browsers. It could also be down to something funky related to the HTML5 shiv.

You could try switching to one of the XHTML doctypes and changing your markup accordingly, at least temporarily. This might allow you to narrow the problem down.

Is your design breaking when those IEs switch to quirks mode? If it's your CSS causing things to display strangely, it might be worth working on the CSS so the site looks the same even when the browsers switch modes.

android View not attached to window manager

when you declare activity in the manifest you need android:configChanges="orientation"

example:

<activity android:theme="@android:style/Theme.Light.NoTitleBar" android:configChanges="orientation"  android:label="traducción" android:name=".PantallaTraductorAppActivity"></activity>

Count number of rows by group using dplyr

I think what you are looking for is as follows.

cars_by_cylinders_gears <- mtcars %>%
  group_by(cyl, gear) %>%
  summarise(count = n())

This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

Not including the action attribute opens the page up to iframe clickjacking attacks, which involve a few simple steps:

  • An attacker wraps your page in an iframe
  • The iframe URL includes a query param with the same name as a form field
  • When the form is submitted, the query value is inserted into the database
  • The user's identifying information (email, address, etc) has been compromised

References

jQuery Popup Bubble/Tooltip

ColorTip is the most beautiful i've ever seen

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

On Mac it works for below command. (hope your .Dockerfile is in your root directory).

docker build -t docker-whale -f .Dockerfile .

Errors in pom.xml with dependencies (Missing artifact...)

It means maven is not able to download artifacts from repository. Following steps will help you:

  1. Go to repository browser and check if artifact exist.
  2. Check settings.xml to see if proper respository is specified.
  3. Check proxy settings.

What is "export default" in JavaScript?

In my opinion, the important thing about the default export is that it can be imported with any name!

If there is a file, foo.js, which exports default:

_x000D_
_x000D_
export default function foo(){}
_x000D_
_x000D_
_x000D_

it can be imported in bar.js using:

_x000D_
_x000D_
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
_x000D_
_x000D_

IF...THEN...ELSE using XML

<IF id="if-1">
   <TIME from="5pm" to="9pm" />
<ELSE>
   <something else />
</ELSE>
</IF>

I don't know if this makes any sense to anyone else or it is actually usable in your program, but I would do it like this.

My point of view: You need to have everything related to your "IF" inside your IF-tag, otherwise you won't know what ELSE belongs to what IF. Secondly, I'd skip the THEN tag because it always follows an IF.

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

Remove a file from a Git repository without deleting it from the local filesystem

To remove an entire folder from the repo (like Resharper files), do this:

git rm -r --cached folderName

I had committed some resharper files, and did not want those to persist for other project users.

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

How do you get assembler output from C/C++ source in gcc?

I don't see this possibility among answers, probably because the question is from 2008, but in 2018 you can use Matt Goldbolt's online website https://godbolt.org

You can also locally git clone and run his project https://github.com/mattgodbolt/compiler-explorer

Comparing floating point number to zero

You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

bool isNearlyEqual(double a, double b)
{
  int factor = /* a fixed factor of epsilon */;

  double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
  double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;

  return min_a <= b && max_a >= b;
}

Adding minutes to date time in PHP

PHP's DateTime class has a useful modify method which takes in easy-to-understand text.

$dateTime = new DateTime('2011-11-17 05:05');
$dateTime->modify('+5 minutes');

You could also use string interpolation or concatenation to parameterize it:

$dateTime = new DateTime('2011-11-17 05:05');
$minutesToAdd = 5;
$dateTime->modify("+{$minutesToAdd} minutes");

How to get the absolute coordinates of a view

Use This code to find exact X and Y cordinates :

int[] array = new int[2];
ViewForWhichLocationIsToBeFound.getLocationOnScreen(array);
if (AppConstants.DEBUG)
    Log.d(AppConstants.TAG, "array  X = " + array[0] + ", Y = " + array[1]);
ViewWhichToBeMovedOnFoundLocation.setTranslationX(array[0] + 21);
ViewWhichToBeMovedOnFoundLocation.setTranslationY(array[1] - 165);

I have added/subtracted some values to adjust my view. Please do these lines only after whole view has been inflated.

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

hey I think that you just copy your compiled class files and copy the jre folder and make the following as the content of the batch file and save all together any windows machine and just double click

@echo
setpath d:\jre
d:
cd myprogfolder
java myprogram

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Using #!/usr/bin/env NAME makes the shell search for the first match of NAME in the $PATH environment variable. It can be useful if you aren't aware of the absolute path or don't want to search for it.

How can I initialise a static Map?

Here is the code by AbacusUtil

Map<Integer, String> map = N.asMap(1, "one", 2, "two");
// Or for Immutable map 
ImmutableMap<Integer, String> = ImmutableMap.of(1, "one", 2, "two");

Declaration: I'm the developer of AbacusUtil.

How do I change the data type for a column in MySQL?

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

ALTER TABLE tablename MODIFY columnname INTEGER;

This will change the datatype of given column

Depending on how many columns you wish to modify it might be best to generate a script, or use some kind of mysql client GUI

javascript regex - look behind alternative?

EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.

In previous versions, you can do this:

^(?:(?!filename\.js$).)*\.js$

This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.

^                 # Start of string
(?:               # Try to match the following:
 (?!              # First assert that we can't match the following:
  filename\.js    # filename.js 
  $               # and end-of-string
 )                # End of negative lookahead
 .                # Match any character
)*                # Repeat as needed
\.js              # Match .js
$                 # End of string

Another edit:

It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:

^(?!.*filename\.js$).*\.js$

works just as well:

^                 # Start of string
(?!               # Assert that we can't match the following:
 .*               # any string, 
  filename\.js    # followed by filename.js
  $               # and end-of-string
)                 # End of negative lookahead
.*                # Match any string
\.js              # Match .js
$                 # End of string

New features in java 7

The following list contains links to the the enhancements pages in the Java SE 7.

Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
    Requesting and Customizing Applet Decoration in Dragg able Applets
    Embedding JNLP File in Applet Tag
    Deploying without Codebase
    Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
    Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
    Binary Literals
    Strings in switch Statements
    The try-with-resources Statement
    Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    Underscores in Numeric Literals
    Type Inference for Generic Instance Creation
    Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
    Java Virtual Machine Support for Non-Java Languages
    Garbage-First Collector
    Java HotSpot Virtual Machine Performance Enhancements
JDBC

Reference 1 Reference 2

Calling virtual functions inside constructors

As a supplement, calling a virtual function of an object that has not yet completed construction will face the same problem.

For example, start a new thread in the constructor of an object, and pass the object to the new thread, if the new thread calling the virtual function of that object before the object completed construction will cause unexpected result.

For example:

#include <thread>
#include <string>
#include <iostream>
#include <chrono>

class Base
{
public:
  Base()
  {
    std::thread worker([this] {
      // This will print "Base" rather than "Sub".
      this->Print();
    });
    worker.detach();
    // Try comment out this code to see different output.
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
  virtual void Print()
  {
    std::cout << "Base" << std::endl;
  }
};

class Sub : public Base
{
public:
  void Print() override
  {
    std::cout << "Sub" << std::endl;
  }
};

int main()
{
  Sub sub;
  sub.Print();
  getchar();
  return 0;
}

This will output:

Base
Sub

Is it ok to run docker from inside docker?

I answered a similar question before on how to run a Docker container inside Docker.

To run docker inside docker is definitely possible. The main thing is that you run the outer container with extra privileges (starting with --privileged=true) and then install docker in that container.

Check this blog post for more info: Docker-in-Docker.

One potential use case for this is described in this entry. The blog describes how to build docker containers within a Jenkins docker container.

However, Docker inside Docker it is not the recommended approach to solve this type of problems. Instead, the recommended approach is to create "sibling" containers as described in this post

So, running Docker inside Docker was by many considered as a good type of solution for this type of problems. Now, the trend is to use "sibling" containers instead. See the answer by @predmijat on this page for more info.

Trying to check if username already exists in MySQL database using PHP

Try this:

$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")

Don't add $con to mysql_query() function.

Disclaimer: using the username variable in the string passed to mysql_query, as shown above, is a trivial SQL injection attack vector in so far the username depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.

Find the item with maximum occurrences in a list

A simple way without any libraries or sets

def mcount(l):
  n = []                  #To store count of each elements
  for x in l:
      count = 0
      for i in range(len(l)):
          if x == l[i]:
              count+=1
      n.append(count)
  a = max(n)              #largest in counts list
  for i in range(len(n)):
      if n[i] == a:
          return(l[i],a)  #element,frequency
  return                  #if something goes wrong

Getting permission denied (public key) on gitlab

Nothing worked for me on Windows 10 using Pageant as SSH agent, except adding a enviroment variable to windows (translated from german Windows 10, so the naming may differ):

  1. Search for "variables"
  2. Open System Enviroment Variables
  3. Click Enviroment Variables button at the bottom
  4. Add a new key named "GIT_SSH" and the value "C:\Program Files\PuTTY\plink.exe", to the top section "User Variables xxx"
  5. And you're done.

All thanks go to Benjamin Bortels, source: https://bortels.io/blog/git-in-vs-code-unter-windows-richtig-einstellen

Text file in VBA: Open/Find Replace/SaveAs/Close File

Guess I'm too late...

Came across the same problem today; here is my solution using FileSystemObject:

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

How can I expose more than 1 port with Docker?

Use this as an example:

docker create --name new_ubuntu -it -p 8080:8080 -p  15672:15672 -p 5432:5432   ubuntu:latest bash

look what you've created(and copy its CONTAINER ID xxxxx):

docker ps -a 

now write the miracle maker word(start):

docker start xxxxx

good luck

API pagination best practices

I've thought long and hard about this and finally ended up with the solution I'll describe below. It's a pretty big step up in complexity but if you do make this step, you'll end up with what you are really after, which is deterministic results for future requests.

Your example of an item being deleted is only the tip of the iceberg. What if you are filtering by color=blue but someone changes item colors in between requests? Fetching all items in a paged manner reliably is impossible... unless... we implement revision history.

I've implemented it and it's actually less difficult than I expected. Here's what I did:

  • I created a single table changelogs with an auto-increment ID column
  • My entities have an id field, but this is not the primary key
  • The entities have a changeId field which is both the primary key as well as a foreign key to changelogs.
  • Whenever a user creates, updates or deletes a record, the system inserts a new record in changelogs, grabs the id and assigns it to a new version of the entity, which it then inserts in the DB
  • My queries select the maximum changeId (grouped by id) and self-join that to get the most recent versions of all records.
  • Filters are applied to the most recent records
  • A state field keeps track of whether an item is deleted
  • The max changeId is returned to the client and added as a query parameter in subsequent requests
  • Because only new changes are created, every single changeId represents a unique snapshot of the underlying data at the moment the change was created.
  • This means that you can cache the results of requests that have the parameter changeId in them forever. The results will never expire because they will never change.
  • This also opens up exciting feature such as rollback / revert, synching client cache etc. Any features that benefit from change history.

Create a Date with a set timezone without using a string representation

I used the timezone-js package.

var timezoneJS  = require('timezone-js');
var tzdata = require('tzdata');

createDate(dateObj) {
    if ( dateObj == null ) {
        return null;
    }
    var nativeTimezoneOffset = new Date().getTimezoneOffset();
    var offset = this.getTimeZoneOffset();

    // use the native Date object if the timezone matches
    if ( offset == -1 * nativeTimezoneOffset ) {
        return dateObj;
    }

    this.loadTimeZones();

    // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
    //        tried jquery $.extend
    //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
    return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},

How to set image for bar button with swift?

Here's a simple extension on UIBarButtonItem:

extension UIBarButtonItem {
    class func itemWith(colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
        let button = UIButton(type: .custom)
        button.setImage(colorfulImage, for: .normal)
        button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
        button.addTarget(target, action: action, for: .touchUpInside)

        let barButtonItem = UIBarButtonItem(customView: button)
        return barButtonItem
    }
}

Fastest way to check if string contains only digits

Here's some benchmarks based on 1000000 parses of the same string:

Updated for release stats:

IsDigitsOnly: 384588
TryParse:     639583
Regex:        1329571

Here's the code, looks like IsDigitsOnly is faster:

class Program
{
    private static Regex regex = new Regex("^[0-9]+$", RegexOptions.Compiled);

    static void Main(string[] args)
    {
        Stopwatch watch = new Stopwatch();
        string test = int.MaxValue.ToString();
        int value;

        watch.Start();
        for(int i=0; i< 1000000; i++)
        {
            int.TryParse(test, out value);
        }
        watch.Stop();
        Console.WriteLine("TryParse: "+watch.ElapsedTicks);

        watch.Reset();
        watch.Start();
        for (int i = 0; i < 1000000; i++)
        {
            IsDigitsOnly(test);
        }
        watch.Stop();
        Console.WriteLine("IsDigitsOnly: " + watch.ElapsedTicks);

        watch.Reset();
        watch.Start();
        for (int i = 0; i < 1000000; i++)
        {
            regex.IsMatch(test);
        }
        watch.Stop();
        Console.WriteLine("Regex: " + watch.ElapsedTicks);

        Console.ReadLine();
    }

    static bool IsDigitsOnly(string str)
    {
        foreach (char c in str)
        {
            if (c < '0' || c > '9')
                return false;
        }

        return true;
    }
}

Of course it's worth noting that TryParse does allow leading/trailing whitespace as well as culture specific symbols. It's also limited on length of string.

check if variable empty

To check for null values you can use is_null() as is demonstrated below.

if (is_null($value)) {
   $value = "MY TEXT"; //define to suit
}

Javascript: How to loop through ALL DOM elements on a page?

Andy E. gave a good answer.

I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.

For an example, I needed to just parse "visual" part of the web page, so I just made this

var visualDomElts = document.body.getElementsByTagName('*');

This will never take in consideration the head part.

How to retrieve images from MySQL database and display in an html tag

You need to retrieve and disect the information into what you need.

while($row = mysql_fetch_array($result)) {
 echo "img src='",$row['filename'],"' width='175' height='200' />";
}

How to enable external request in IIS Express?

This is insanely awesome and even covers HTTPS with pretty domain names:

http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx

The really awesome parts I couldn't find anywhere else on SO in case the above link ever goes away:

> C:\Program Files (x86)\IIS Express>IisExpressAdminCmd.exe Usage:
> iisexpressadmincmd.exe <command> <parameters> Supported commands:
>       setupFriendlyHostnameUrl -url:<url>
>       deleteFriendlyHostnameUrl -url:<url>
>       setupUrl -url:<url>
>       deleteUrl -url:<url>
>       setupSslUrl -url:<url> -CertHash:<value>
>       setupSslUrl -url:<url> -UseSelfSigned
>       deleteSslUrl -url:<url>
> 
> Examples: 1) Configure "http.sys" and "hosts" file for friendly
> hostname "contoso": iisexpressadmincmd setupFriendlyHostnameUrl
> -url:http://contoso:80/ 2) Remove "http.sys" configuration and "hosts" file entry for the friendly  hostname "contoso": iisexpressadmincmd
> deleteFriendlyHostnameUrl -url:http://contoso:80/

The above utility will register the SSL certificate for you! If you use the -UseSelfSigned option, it's super easy.

If you want to do things the hard way, the non-obvious part is you need to tell HTTP.SYS what certificate to use, like this:

netsh http add sslcert ipport=0.0.0.0:443 appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certhash=YOURCERTHASHHERE

Certhash is the "Thumbprint" you can get from the certificate properties in MMC.

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

Using 2to3 utility.

$ cat try.py
import SimpleHTTPServer

$ 2to3 try.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored try.py
--- try.py  (original)
+++ try.py  (refactored)
@@ -1 +1 @@
-import SimpleHTTPServer
+import http.server
RefactoringTool: Files that need to be modified:
RefactoringTool: try.py

Like many *nix utils, 2to3 accepts stdin if the argument passed is -. Therefore, you can test without creating any files like so:

$ 2to3 - <<< "import SimpleHTTPServer"

Split string based on a regular expression

Its very simple actually. Try this:

str1="a    b     c      d"
splitStr1 = str1.split()
print splitStr1

How to override Bootstrap's Panel heading background color?

I tried using custom panel class but it didn't work. So for those who are struggling just like me, you can use inline CSS and it works fine for me.

Here is what my code looks like :

<div class="panel-heading" style="background-image:none;background: #a4c6ff;">

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

How to show the text on a ImageButton?

It is technically possible to put a caption on an ImageButton if you really want to do it. Just put a TextView over the ImageButton using FrameLayout. Just remember to not make the Textview clickable.

Example:

<FrameLayout>
    <ImageButton
        android:id="@+id/button_x"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@null"
        android:scaleType="fitXY"
        android:src="@drawable/button_graphic" >
    </ImageButton>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clickable="false"
        android:text="TEST TEST" >
    </TextView>
</FrameLayout>

Algorithm to compare two images

These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this!

Before you begin

Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results.

Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on.

Matlab is an excellent tool for testing and evaluating images.

Testing the algorithms

You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms.

The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world.

It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us!

You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project.

Colour Buckets

With two pictures, scan each pixel and count the colours. For example you might have the 'buckets':

white
red
blue
green
black

(Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate.

Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches.

Edge detection

How about using Edge Detection. alt text
(source: wikimedia.org)

With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint.

Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied Gabor Filter (a type of edge detection) in various rotations.

alt text

Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves.

Regions of Interest

Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example:

alt text
(source: meetthegimp.org)

The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set.

If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example:

alt text
(source: per2000.eu)

We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels.

Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches.

It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably designed to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge.

Morphing

Morphing two images is the process of turning one image into the other through a set of steps:

alt text

Note, this is different to fading one image into another!

There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result.

Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm.

In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other.

This technique could work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results.

Zipping

Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons.

One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into.

Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about how compression works will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point.

Transparency

Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency.

Inverting Signals

An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out.

alt text
(source: themotorreport.com.au)

Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match.

However, consider two images that are equal, except one of them has a brighten effect applied to it:

alt text
(source: mcburrz.com)

Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two.

I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique.

Tree Data structures

At first these don't seem to fit for the problem, but I think they could work.

You could think about extracting certain properties of an image (for example colour bins) and generate a huffman tree or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work.

This probably wouldn't work, but it's an idea. The trie datastructure is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains:

FFFFFF|000000|FDFD44|FFFFFF

We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results.

Comparing trie trees should be reasonably easy, and could possible provide effective results.

More ideas

I stumbled accross an interesting paper breif about classification of satellite imagery, it outlines:

Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification.

It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set.

Other things to consider

There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve.

Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set.

Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results.

If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another.

Be careful to not fall into attempting to complete the never ending project, good luck!

Fix CSS hover on iPhone/iPad/iPod

I know it's an old post, already answered, but I found another solution without adding css classes or doing too much javascript than really needed, and I want to share it, hoping can help someone.

I found that to enable :hover effect on every kind of elements on a Touch enabled browser, you need to tell him that your elements are clickable. To do so you can simply add an empty handler to the click function with jQuery or javascript.

$('.need-hover').on('click', function(){ });

It's better if you do so only on Mobile enabled browsers with this snippet:

// check for css :hover supports and save in a variable
var supportsTouch = (typeof Touch == "object");

if(supportsTouch){ 
    // not supports :hover
    $('.need-hover').on('click', function(){ });
}

Use RSA private key to generate public key?

My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.

To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.

To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:

ciphertext = ( plaintext^e ) mod n

To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:

plaintext = ( ciphertext^d ) mod n

To generate private (d,n) key using openssl you can use the following command:

openssl genrsa -out private.pem 1024

To generate public (e,n) key from the private key using openssl you can use the following command:

openssl rsa -in private.pem -out public.pem -pubout

To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):

openssl rsa -in private.pem -text -noout | less

modulus         - n
privateExponent - d
publicExponent  - e
prime1          - p
prime2          - q
exponent1       - d mod (p-1)
exponent2       - d mod (q-1)
coefficient     - (q^-1) mod p

Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.

Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:

# Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der

# Print private.der private key contents as binary stream
xxd -p private.der

# Now compare the output of the above command with output 
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less

This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.

To see the contents of the public.pem public RSA key run the following (output truncated to labels here):

openssl rsa -in public.pem -text -pubin -noout

Modulus             - n
Exponent (public)   - e

No surprises here. It's just (n, e) pair, as promised.

Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.

jQuery Datepicker onchange event issue

On jQueryUi 1.9 I've managed to get it to work through an additional data value and a combination of beforeShow and onSelect functions:

$( ".datepicker" ).datepicker({
    beforeShow: function( el ){
        // set the current value before showing the widget
        $(this).data('previous', $(el).val() );
    },

    onSelect: function( newText ){
        // compare the new value to the previous one
        if( $(this).data('previous') != newText ){
            // do whatever has to be done, e.g. log it to console
            console.log( 'changed to: ' + newText );
        }
    }
});

Works for me :)

Is Task.Result the same as .GetAwaiter.GetResult()?

I checked the source code of TaskOfResult.cs (Source code of TaskOfResult.cs):

If Task is not completed, Task.Result will call Task.Wait() method in getter.

public TResult Result
{
    get
    {
        // If the result has not been calculated yet, wait for it.
        if (!IsCompleted)
        {
            // We call NOCTD for two reasons: 
            //    1. If the task runs on another thread, then we definitely need to notify that thread-slipping is required.
            //    2. If the task runs inline but takes some time to complete, it will suffer ThreadAbort with possible state corruption.
            //         - it is best to prevent this unless the user explicitly asks to view the value with thread-slipping enabled.
            //#if !PFX_LEGACY_3_5
            //                    Debugger.NotifyOfCrossThreadDependency();  
            //#endif
            Wait();
        }

        // Throw an exception if appropriate.
        ThrowIfExceptional(!m_resultWasSet);

        // We shouldn't be here if the result has not been set.
        Contract.Assert(m_resultWasSet, "Task<T>.Result getter: Expected result to have been set.");

        return m_result;
    }
    internal set
    {
        Contract.Assert(m_valueSelector == null, "Task<T>.Result_set: m_valueSelector != null");

        if (!TrySetResult(value))
        {
            throw new InvalidOperationException(Strings.TaskT_TransitionToFinal_AlreadyCompleted);
        }
    }
}

If We call GetAwaiter method of Task, Task will wrapped TaskAwaiter<TResult> (Source code of GetAwaiter()), (Source code of TaskAwaiter) :

public TaskAwaiter GetAwaiter()
{
    return new TaskAwaiter(this);
}

And If We call GetResult() method of TaskAwaiter<TResult>, it will call Task.Result property, that Task.Result will call Wait() method of Task ( Source code of GetResult()):

public TResult GetResult()
{
    TaskAwaiter.ValidateEnd(m_task);
    return m_task.Result;
}

It is source code of ValidateEnd(Task task) ( Source code of ValidateEnd(Task task) ):

internal static void ValidateEnd(Task task)
{
    if (task.Status != TaskStatus.RanToCompletion)
         HandleNonSuccess(task);
}

private static void HandleNonSuccess(Task task)
{
    if (!task.IsCompleted)
    {
        try { task.Wait(); }
        catch { }
    }
    if (task.Status != TaskStatus.RanToCompletion)
    {
        ThrowForNonSuccess(task);
    }
}

This is my conclusion:

As can be seen GetResult() is calling TaskAwaiter.ValidateEnd(...), therefore Task.Result is not same GetAwaiter.GetResult().

I think GetAwaiter().GetResult() is a beter choice instead of .Result because it don't wrap exceptions.

I read this at page 582 in C# 7 in a Nutshell (Joseph Albahari & Ben Albahari) book

If an antecedent task faults, the exception is re-thrown when the continuation code calls awaiter.GetResult() . Rather than calling GetResult , we could simply access the Result property of the antecedent. The benefit of calling GetResult is that if the antecedent faults, the exception is thrown directly without being wrapped in AggregateException , allowing for simpler and cleaner catch blocks.

Source: C# 7 in a Nutshell's page 582

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Clearing localStorage in javascript?

Use this to clear localStorage:

localStorage.clear();

How do I center text vertically and horizontally in Flutter?

maybe u want to provide the same width and height for 2 container

Container(
            width: size.width * 0.30, height: size.height * 0.4,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6)
            ),
            child: Center(
              child: Text(categoryName, textAlign: TextAlign.center, style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 17,
                color: Colors.white,
              ),),
            ),

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

What is the difference between a static method and a non-static method?

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.

i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.

Notice that static vars can also be used to share information across all instances

How to get the current time in milliseconds from C in Linux?

This version need not math library and checked the return value of clock_gettime().

#include <time.h>
#include <stdlib.h>
#include <stdint.h>

/**
 * @return milliseconds
 */
uint64_t get_now_time() {
  struct timespec spec;
  if (clock_gettime(1, &spec) == -1) { /* 1 is CLOCK_MONOTONIC */
    abort();
  }

  return spec.tv_sec * 1000 + spec.tv_nsec / 1e6;
}

Making a div vertically scrollable using CSS

You can use overflow-y: scroll for vertical scrolling.

_x000D_
_x000D_
<div  style="overflow-y:scroll; height:400px; background:gray">_x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
  _x000D_
 </div>
_x000D_
_x000D_
_x000D_