Programs & Examples On #Html5 video

HTML5 video is an element introduced in the HTML5 draft specification for the purpose of creating a standards-compliant, plugin-free way for playing videos and movies, partially replacing the object element.

Wait until an HTML5 video loads

In response to the final part of your question, which is still unanswered... When you write $('#video').duration, you're asking for the duration property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.

Here's one:

// get the native element directly
document.getElementById('video').duration

Here's another:

// get it out of the jQuery object
$('#video').get(0).duration

And another:

// use the event object
v.bind('loadeddata', function(e) {
  console.log(e.target.duration);
});

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

How to set the thumbnail image on HTML5 video?

Display Your Video First Frame as Thumbnail:

Add preload="metadata" to your video tag and the second of the first frame #t=0.5 to your video source:

_x000D_
_x000D_
<video width="400" controls="controls" preload="metadata">_x000D_
  <source src="https://www.w3schools.com/html/mov_bbb.mp4#t=0.5" type="video/mp4">_x000D_
</video>
_x000D_
_x000D_
_x000D_

HTML5 Video Autoplay not working correctly

Try autoplay="autoplay" instead of the "true" value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.

Video 100% width and height

Easiest & Responsive.

<video src="full.mp4" autoplay muted loop></video>

<style>
    video {
        height: 100vh;
        width: 100%;
        object-fit: fill; // use "cover" to avoid distortion
        position: absolute;
    }
</style>

HTML5 Video tag not working in Safari , iPhone and iPad

Your web server might not support HTTP byte-range requests. This is the case with the web server I'm using, and the result is that the video widget loads and a play button appears, but clicking the button has no effect. — The video works in FF and Chrome, but not iPhone or iPad.

Read more here on mobiforge.com about byte-range requests, in Appendix A: Streaming for Apple iPhone:

First, the Safari Web Browser requests the content, and if it's an audio or video file it opens it's media player. The media player then requests the first 2 bytes of the content, to ensure that the Webserver supports byte-range requests. Then, if it supports them, the iPhone's media player requests the rest of the content by byte-ranges and plays it.

You might want to search the web for "iphone mp4 byte-range".

current/duration time of html5 video?

I am assuming you want to display this as part of the player.

This site breaks down how to get both the current and total time regardless of how you want to display it though using jQuery:

http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/

This will also cover how to set it to a specific div. As philip has already mentioned, .currentTime will give you where you are in the video.

HTML5 video won't play in Chrome only

To all of you who got here and did not found the right solution, i found out that the mp4 video needs to fit a specific format.

My Problem was that i got an 1920x1080 video which wont load under Chrome (under Firefox it worked like a charm). After hours of searching i finaly managed to get hang of the problem, the first few streams where 1912x1088 so Chrome wont play it ( i got the exact stream size from the tool MediaInfo). So to fix it i just resized it to 1920x1080 and it worked.

How to change the playing speed of videos in HTML5?

According to this site, this is supported in the playbackRate and defaultPlaybackRate attributes, accessible via the DOM. Example:

/* play video twice as fast */
document.querySelector('video').defaultPlaybackRate = 2.0;
document.querySelector('video').play();

/* now play three times as fast just for the heck of it */
document.querySelector('video').playbackRate = 3.0;

The above works on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.

Start HTML5 video at a particular position when loading?

adjust video start and end time when using the video tag in html5;

http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15

where left of comma is start time in seconds, right of comma is end time in seconds. drop the comma and end time to effect the start time only.

Overlaying a DIV On Top Of HTML 5 Video

<div id="video_box">
  <div id="video_overlays"></div>
  <div>
    <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
  </div>
</div>

for this you need to just add css like this:

#video_overlays {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.46);
  z-index: 2;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
#video_box{position: relative;}

What is a blob URL and why it is used?

What is blob url? Why it is used?

BLOB is just byte sequence. Browser recognize it as byte stream. It is used to get byte stream from source.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Can i make my own blob url on a server?

Yes you can there are serveral ways to do so for example try http://php.net/manual/en/function.ibase-blob-echo.php

Read more on

Play infinitely looping video on-load in HTML5

As of April 2018, Chrome (along with several other major browsers) now require the muted attribute too.

Therefore, you should use

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

HTML5 live streaming

A possible alternative for that:

  1. Use an encoder (e.g. VLC or FFmpeg) into packetize your input stream to OGG format. For example, in this case I used VLC to packetize screen capture device with this code:

    C:\Program Files\VideoLAN\VLC\vlc.exe -I dummy screen:// :screen-fps=16.000000 :screen-caching=100 :sout=#transcode{vcodec=theo,vb=800,scale=1,width=600,height=480,acodec=mp3}:http{mux=ogg,dst=127.0.0.1:8080/desktop.ogg} :no-sout-rtp-sap :no-sout-standard-sap :ttl=1 :sout-keep

  2. Embed this code into a <video> tag in your HTML page like that:

    <video id="video" src="http://localhost:8080/desktop.ogg" autoplay="autoplay" />

This should do the trick. However it's kind of poor performance and AFAIK MP4 container type should have a better support among browsers than OGG.

Play/pause HTML 5 video using JQuery

Sorry for my other answer. No-one liked it, but I have found another way that you can do it.

You can use Video.js! You can find the documentation and how-to's here.

Javascript to stop HTML5 video playback on modal window close

Have a try:

_x000D_
_x000D_
function stop(){_x000D_
    var video = document.getElementById("video");_x000D_
    video.load();_x000D_
}
_x000D_
_x000D_
_x000D_

HTML5 Video Stop onClose

To save hours of coding time, use a jquery plug-in already optimized for embedded video iframes.

I spent a couple days trying to integrate Vimeo's moogaloop API with jquery tools unsuccessfully. See this list for a handful of easier options.

Detect when an HTML5 video finishes

Have a look at this Everything You Need to Know About HTML5 Video and Audio post at the Opera Dev site under the "I want to roll my own controls" section.

This is the pertinent section:

<video src="video.ogv">
     video not supported
</video>

then you can use:

<script>
    var video = document.getElementsByTagName('video')[0];

    video.onended = function(e) {
      /*Do things here!*/
    };
</script>

onended is a HTML5 standard event on all media elements, see the HTML5 media element (video/audio) events documentation.

.mp4 file not playing in chrome

After running into the same issue - here're some of my thoughts:

  • due to Chrome removing support for h264, on some machines, mp4 videos encoded with it will either not work (throwing an Parser error when viewing under Firebug/Network tab - consistent with issue submitted here), or crash the browser, depending upon the encoding settings
  • it isn't consistent - it entirely depends upon the codecs installed on the computer - while I didn't encounter this issue on my machine, we did have one in the office where the issue occurred (and thus we used this one for testing)
  • it might to do with Quicktime / divX settings (the machine in question had an older version of Quicktime than my native one - we didn't want to loose our testing pc though, so we didn't update it).

As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:

for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:

if (window.chrome)
    $("[type=video\\\/mp4]").each(function()
    {
        $(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
    });

Unfortunately it's a bad Chrome hack, but hey, at least it works.

Source: user: eithedog

This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec

Also check your version of crome here: html5test

Make HTML5 video poster be same size as video itself

I had a similar issue and just fixed it by creating an image with the same aspect ratio as my video (16:9). My width is set to 100% on the video tag and now the image (320 x 180) fits perfectly. Hope that helps!

Detect if HTML5 Video element is playing

Add eventlisteners to your media element. Possible events that can be triggered are: Audio and video media events

_x000D_
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<head>  _x000D_
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> _x000D_
<title>Html5 media events</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head> _x000D_
<body >_x000D_
    <div id="output"></div>_x000D_
    <video id="myVideo" width="320" height="176" controls autoplay>_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">_x000D_
        <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">_x000D_
    </video>_x000D_
    <script>_x000D_
        var media = document.getElementById('myVideo');_x000D_
_x000D_
        // Playing event_x000D_
        media.addEventListener("playing", function() {_x000D_
            $("#output").html("Playing event triggered");_x000D_
        });_x000D_
   _x000D_
        // Pause event_x000D_
        media.addEventListener("pause", function() { _x000D_
            $("#output").html("Pause event triggered"); _x000D_
        });_x000D_
_x000D_
        // Seeking event_x000D_
        media.addEventListener("seeking", function() { _x000D_
            $("#output").html("Seeking event triggered"); _x000D_
        });_x000D_
_x000D_
        // Volume changed event_x000D_
        media.addEventListener("volumechange", function(e) { _x000D_
            $("#output").html("Volumechange event triggered"); _x000D_
        });_x000D_
_x000D_
    </script>   _x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_

Prevent HTML5 video from being downloaded (right-click saved)?

You can't. That's because that's what browsers were designed to do: Serve content. But you can make it harder to download.

First thing's first, you could disable the contextmenu event, aka "the right click". That would prevent your regular skiddie from blatantly ripping your video by right clicking and Save As. But then they could just disable JS and get around this or find the video source via the browser's debugger. Plus this is bad UX. There are lots of legitimate things in a context menu than just Save As.

You could also use custom video player libraries. Most of them implement video players that customize the context menu to your liking. So you don't get the default browser context menu. And if ever they do serve a menu item similar to Save As, you can disable it. But again, this is a JS workaround. Weaknesses are similar to the previous option.

Another way to do it is to serve the video using HTTP Live Streaming. What it essentially does is chop up the video into chunks and serve it one after the other. This is how most streaming sites serve video. So even if you manage to Save As, you only save a chunk, not the whole video. It would take a bit more effort to gather all the chunks and stitch them using some dedicated software.

Another technique is to paint <video> on <canvas>. In this technique, with a bit of JavaScript, what you see on the page is a <canvas> element rendering frames from a hidden <video>. And because it's a <canvas>, the context menu will use an <img>'s menu, not a <video>'s. You'll get a Save Image As instead of a Save Video As.

You could also use CSRF tokens to your advantage. You'd have your sever send down a token on the page. You then use that token to fetch your video. Your server checks to see if it's a valid token before it serves the video, or get an HTTP 401. The idea is that you can only ever get a video by having a token which you can only ever get if you came from the page, not directly visiting the video url.

At the end of the day, I'd just upload my video to a third-party video site, like YouTube or Vimeo. They have good video management tools, optimizes playback to the device, and they make efforts in preventing their videos from being ripped with zero effort on your end.

HTML5 - mp4 video does not play in IE9

Dan has one of the best answers up there and I'd suggest you use html5test.com on your target browsers to see the video formats that are supported.

As stated above, no single format works and what I use is MP4 encoded to H.264, WebM, and a flash fallback. This let's me show video on the following:

Win 7 - IE9, Chrome, Firefox, Safari, Opera

Win XP - IE7, IE8, Chrome, Firefox, Safari, Opera

MacBook OS X - Chrome, Firefox, Safari, Opera

iPad 2, iPad 3

Linux - Android 2.3, Android 3

<video width="980" height="540" controls>
        <source src="images/placeholdername.mp4" type="video/mp4" />
        <source src="images/placeholdername.webm" type="video/webm" />
        <embed src="images/placeholdername.mp4" type="application/x-shockwave-flash" width="980" height="570" allowscriptaccess="always" allowfullscreen="true" autoplay="false"></embed>  <!--IE 8 - add 25-30 pixels to vid height to allow QT player controls-->    
    </video>

Note: The .mp4 video should be coded in h264 basic profile, so that it plays on all mobile devices.

Update: added autoplay="false" to the Flash fallback. This prevents the MP4 from starting to play right away when the page loads on IE8, it will start to play once the play button is pushed.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

For me (in Angular project) this code helped:

In HTML you should add autoplay muted

In JS/TS

playVideo() {
    const media = this.videoplayer.nativeElement;
    media.muted = true; // without this line it's not working although I have "muted" in HTML
    media.play();
}

use video as background for div

Why not fix a <video> and use z-index:-1 to put it behind all other elements?

html, body { width:100%; height:100%; margin:0; padding:0; }

<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
    <video id="video" style="width:100%; height:100%">
        ....
    </video>
</div>
<div class='content'>
    ....

Demo

If you want it within a container you have to add a container element and a little more CSS

/* HTML */
<div class='vidContain'>
    <div class='vid'>
        <video> ... </video>
    </div>
    <div class='content'> ... The rest of your content ... </div>
</div>

/* CSS */
.vidContain {
    width:300px; height:200px;
    position:relative;
    display:inline-block;
    margin:10px;
}
.vid {
    position: absolute; 
    top: 0; left:0;
    width: 100%; height: 100%; 
    z-index: -1;
}    
.content {
    position:absolute;
    top:0; left:0;
    background: black;
    color:white;
}

Demo

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

Play local (hard-drive) video file with HTML5 video tag?

Ran in to this problem a while ago. Website couldn't access video file on local PC due to security settings (understandable really) ONLY way I could get around it was to run a webserver on the local PC (server2Go) and all references to the video file from the web were to the localhost/video.mp4

<div id="videoDiv">
     <video id="video" src="http://127.0.0.1:4001/videos/<?php $videoFileName?>" width="70%" controls>
    </div>
<!--End videoDiv-->

Not an ideal solution but worked for me.

Can you display HTML5 <video> as a full screen background?

Just a comment on this - I've used HTML5 video for a full-screen background and it works a treat - but make sure to use either Height:100% and width:auto or the other way around - to ensure you keep aspect ratio.

As for Ipads -you can (apparently) do this, by having a hidden and then forcing the click event to fire, and having the function of the click event kick off the Load/Play().

P.s - this shouldn't require any plugins and can be done with minimal JS - If you're targeting any mobile device (I would assume you might be..) staying away from any such framework is the way forward.

HTML 5 Video "autoplay" not automatically starting in CHROME

Try this:

<video src="{{ asset('path/to/your_video.mp4' )}}" muted autoplay loop playsinline></video>

And put this js after that:

window.addEventListener('load', async () => {
  let video = document.querySelector('video[muted][autoplay]');
  try {
    await video.play();
  } catch (err) {
    video.controls = true;
  }
});

How to open .mov format video in HTML video Tag?

in the video source change the type to "video/quicktime"

<video width="400" controls Autoplay=autoplay>
  <source src="D:/mov1.mov" type="video/quicktime">
</video>

HTML5 video - show/hide controls programmatically

CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

In HTML,

<div id="hideme">
    <audio id="audioTag" controls>
        <source src="/path/to/audio.mp3">
    </audio>
</div>

with JS

<script type="text/javascript">
window.onload = function() {
    var audioEl = document.getElementById("audioTag");
    audioEl.load();
    audioEl.play();
};
</script>

In CSS,

#hideme {display: none;}

Playing HTML5 video on fullscreen in android webview

Just set
mWebView.setWebChromeClient(new WebChromeClient());

and video plays as normally wont need any custom view.

Can I have a video with transparent background using HTML5 video tag?

These days, if you use two different video formats (WebM and HEVC), you can have a transparent video that works in all of the major browsers except Internet Explorer with a simple <video> tag:

<video>
  <source src="video.webm" type="video/webm">
  <source src="video.mov" type="video/quicktime">
</video>

Here's a demo you can test with

Is there a way to make HTML5 video fullscreen?

Most of the answers here are outdated.

It's now possible to bring any element into fullscreen using the Fullscreen API, although it's still quite a mess because you can't just call div.requestFullScreen() in all browsers, but have to use browser specific prefixed methods.

I've created a simple wrapper screenfull.js that makes it easier to use the Fullscreen API.

Current browser support is:

  • Chrome 15+
  • Firefox 10+
  • Safari 5.1+

Note that many mobile browsers don't seem to support a full screen option yet.

video as site background? HTML 5

Take a look at my jquery videoBG plugin

http://syddev.com/jquery.videoBG/

Make any HTML5 video a site background... has an image fallback for browsers that don't support html5

Really easy to use

Let me know if you need any help.

How to autoplay HTML5 mp4 video on Android?

I simplified the Javascript to trigger the video to start.

_x000D_
_x000D_
 var bg = document.getElementById ("bg"); _x000D_
 function playbg() {_x000D_
   bg.play(); _x000D_
 }
_x000D_
<video id="bg" style="min-width:100%; min-height:100%;"  playsinline autoplay loop muted onload="playbg(); "><source src="Files/snow.mp4" type="video/mp4"></video>_x000D_
</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

*"Files/snow.mp4" is just sample url

In Chrome 55, prevent showing Download button for HTML 5 video

This can hide download button on Chrome when HTML5 Audio is used.

_x000D_
_x000D_
 #aPlayer > audio { width: 100% }_x000D_
/* Chrome 29+ */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0)_x000D_
  and (min-resolution:.001dpcm) {_x000D_
     /* HIDE DOWNLOAD AUDIO BUTTON */_x000D_
     #aPlayer {_x000D_
           overflow: hidden;width: 390px; _x000D_
    }_x000D_
_x000D_
    #aPlayer > audio { _x000D_
      width: 420px; _x000D_
    }_x000D_
}_x000D_
_x000D_
/* Chrome 22-28 */_x000D_
@media screen and(-webkit-min-device-pixel-ratio:0) {_x000D_
    _x000D_
      #aPlayer {_x000D_
           overflow: hidden;width: 390px; _x000D_
        }_x000D_
_x000D_
    #aPlayer > audio { width: 420px; }_x000D_
}
_x000D_
<div id="aPlayer">_x000D_
 <audio autoplay="autoplay" controls="controls">_x000D_
  <source src="http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2012.mp3" type="audio/mpeg" />_x000D_
 </audio>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Click here to see the screenshot

Correct mime type for .mp4

video/mp4should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4. Also, as a server, you should try to include the codecs or profiles parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Since you need the tracks to close the streaming, and you need the stream boject to get to the tracks, the code I have used with the help of the Muaz Khan's answer above is as follows:

if (navigator.getUserMedia) {
    navigator.getUserMedia(constraints, function (stream) {
        videoEl.src = stream;
        videoEl.play();
        document.getElementById('close').addEventListener('click', function () {
            stopStream(stream);
        });
    }, errBack);

function stopStream(stream) {
console.log('stop called');
stream.getVideoTracks().forEach(function (track) {
    track.stop();
});

Of course this will close all the active video tracks. If you have multiple, you should select accordingly.

How to remove all whitespace from a string?

Please note that soultions written above removes only space. If you want also to remove tab or new line use stri_replace_all_charclass from stringi package.

library(stringi)
stri_replace_all_charclass("   ala \t  ma \n kota  ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"

Latex Remove Spaces Between Items in List

This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:

\newenvironment{myitemize}
{ \begin{itemize}
    \setlength{\itemsep}{0pt}
    \setlength{\parskip}{0pt}
    \setlength{\parsep}{0pt}     }
{ \end{itemize}                  } 

Which should be used like this:

\begin{myitemize} 
  \item one 
  \item two 
  \item three 
\end{myitemize}

Source: https://tex.stackexchange.com/a/136050/12065

Printing the value of a variable in SQL Developer

SQL Developer seems to only output the DBMS_OUTPUT text when you have explicitly turned on the DBMS_OUTPUT window pane.

Go to (Menu) VIEW -> Dbms_output to invoke the pane.

Click on the Green Plus sign to enable output for your connection and then run the code.

EDIT: Don't forget to set the buffer size according to the amount of output you are expecting.

Run Batch File On Start-up

Go to Run (WINDOWS + R) and Type shell:startup, paste your .bat file there !

Deserialize JSON with C#

You need to create a structure like this:

public class Friends
{

    public List<FacebookFriend> data {get; set;}
}

public class FacebookFriend
{

    public string id {get; set;}
    public string name {get; set;}
}

Then you should be able to do:

Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);

The names of my classes are just an example. You should use proper names.

Adding a sample test:

string json =
    @"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";

Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);

foreach(var item in facebookFriends.data)
{
    Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}

Produces:

id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft

JSON.NET Error Self referencing loop detected for type

Fix 1: Ignoring circular reference globally

(I have chosen/tried this one, as have many others)

The json.net serializer has an option to ignore circular references. Put the following code in WebApiConfig.cs file:

 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
= Newtonsoft.Json.ReferenceLoopHandling.Ignore; 

The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:

  • The data loses the looping reference information
  • The fix only applies to JSON.net
  • The level of references can't be controlled if there is a deep reference chain

If you want to use this fix in a non-api ASP.NET project, you can add the above line to Global.asax.cs, but first add:

var config = GlobalConfiguration.Configuration;

If you want to use this in .Net Core project, you can change Startup.cs as:

  var mvc = services.AddMvc(options =>
        {
           ...
        })
        .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

Fix 2: Preserving circular reference globally

This second fix is similar to the first. Just change the code to:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
     = Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
     = Newtonsoft.Json.PreserveReferencesHandling.Objects;

The data shape will be changed after applying this setting.

[
   {
      "$id":"1",
      "Category":{
         "$id":"2",
         "Products":[
            {
               "$id":"3",
               "Category":{
                  "$ref":"2"
               },
               "Id":2,
               "Name":"Yogurt"
            },
            {
               "$ref":"1"
            }
         ],
         "Id":1,
         "Name":"Diary"
      },
      "Id":1,
      "Name":"Whole Milk"
   },
   {
      "$ref":"3"
   }
]

The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.

Fix 3: Ignore and preserve reference attributes

This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:

 public class Category 
    { 
        public int Id { get; set; } 
        public string Name { get; set; } 
       
        [JsonIgnore] 
        [IgnoreDataMember] 
        public virtual ICollection<Product> Products { get; set; } 
    } 

JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:

 // Fix 3 
        [JsonObject(IsReference = true)] 
        public class Category 
        { 
            public int Id { get; set; } 
            public string Name { get; set; } 
         
           // Fix 3 
           //[JsonIgnore] 
           //[IgnoreDataMember] 
           public virtual ICollection<Product> Products { get; set; } 
       } 
        
       [DataContract(IsReference = true)] 
       public class Product 
       { 
           [Key] 
           public int Id { get; set; } 
        
           [DataMember] 
           public string Name { get; set; } 
        
           [DataMember] 
           public virtual Category Category { get; set; } 
       }

JsonObject(IsReference = true)] is for JSON.NET and [DataContract(IsReference = true)] is for XmlDCSerializer. Note that: after applying DataContract on class, you need to add DataMember to properties that you want to serialize.

The attributes can be applied on both json and xml serializer and gives more controls on model class.

How to check that an element is in a std::set?

I use

if(!my_set.count(that_element)) //Element is present...
;

But it is not as efficient as

if(my_set.find(that_element)!=my_set.end()) ....;

My version only saves my time in writing the code. I prefer it this way for competitive coding.

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

If it is not Oracle's Java, you may not be able to tell. When I install Oracle Java 64-bit, the files go into C:\Program Files\Java, but when I install a 32-bit version, they default to C:\Program Files (x86)\Java instead. Of course, the person who installed Java could have overridden those defaults.

Android fastboot waiting for devices

Just use sudo, fast boot needs Root Permission

C - reading command line parameters

There's also a C standard built-in library to get command line arguments: getopt

You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

Regular expression to match characters at beginning of line only

Try ^CTR.\*, which literally means start of line, CTR, anything.

This will be case-sensitive, and setting non-case-sensitivity will depend on your programming language, or use ^[Cc][Tt][Rr].\* if cross-environment case-insensitivity matters.

Select parent element of known element in Selenium

Let's consider your DOM as

<a>
    <!-- some other icons and texts -->
    <span>Close</span>
</a>

Now that you need to select parent tag 'a' based on <span> text, then use

driver.findElement(By.xpath("//a[.//span[text()='Close']]"));

Explanation: Select the node based on its child node's value

Split an integer into digits to compute an ISBN checksum

Use the body of this loop to do whatever you want to with the digits

for digit in map(int, str(my_number)):

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

You can do by xlwings as well

import xlwings as xw
for book in xlwings.books:
    print(book)

How do I disable the resizable property of a textarea?

In reactjs, you can disable the resize widget using style props.

<textarea id={"multiline-id"} ref={'my-ref'} style={{resize: "none"}} className="text-area-additional-styles" />

How to have an automatic timestamp in SQLite?

If you use the SQLite DB-Browser you can change the default value in this way:

  1. Choose database structure
  2. select the table
  3. modify table
  4. in your column put under 'default value' the value: =(datetime('now','localtime'))

I recommend to make an update of your database before, because a wrong format in the value can lead to problems in the SQLLite Browser.

How to ignore parent css style

If I understood the question correctly: you can use auto in the CSS like this width: auto; and it will go back to default settings.

Angular 2 router no base href set

I had faced similar issue with Angular4 and Jasmine unit tests; below given solution worked for me

Add below import statement

import { APP_BASE_HREF } from '@angular/common';

Add below statement for TestBed configuration:

TestBed.configureTestingModule({
    providers: [
        { provide: APP_BASE_HREF, useValue : '/' }
    ]
})

Combine or merge JSON on node.js without jQuery

There is an easy way of doing it in Node.js

var object1 = {name: "John"};
var object2 = {location: "San Jose"};

To combine/extend this we can use ... operator in ECMA6

_x000D_
_x000D_
var object1 = {name: "John"};_x000D_
var object2 = {location: "San Jose"};_x000D_
_x000D_
var result = {_x000D_
  ...object1,_x000D_
  ...object2_x000D_
}_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Notification bar icon turns white in Android 5 Lollipop

Post android Lollipop release android has changed the guidelines for displaying notification icons in the Notification bar. The official documentation says "Update or remove assets that involve color. The system ignores all non-alpha channels in action icons and in the main notification icon. You should assume that these icons will be alpha-only. The system draws notification icons in white and action icons in dark gray.” Now what that means in lay man terms is "Convert all parts of the image that you don’t want to show to transparent pixels. All colors and non transparent pixels are displayed in white"

You can see how to do this in detail with screenshots here https://blog.clevertap.com/fixing-notification-icon-for-android-lollipop-and-above/

Hope that helps

How to change an Android app's name?

This is a simple thing in Android Studio,

go to: res folder -> values -> strings.xml

change the app_name (in the bellow example:MitsuhoSdn Bhd) to any new name you want.

<string name="app_name">MitsuhoSdn Bhd</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

Convert DateTime to String PHP

You can use the format method of the DateTime class:

$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

If format fails for some reason, it will return FALSE. In some applications, it might make sense to handle the failing case:

if ($result) {
  echo $result;
} else { // format failed
  echo "Unknown Time";
}

Using :before CSS pseudo element to add image to modal

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

.Modal:before{
  content: '';
  background:url('blackCarrot.png');
  width: /* width of the image */;
  height: /* height of the image */;
  display: block;
}

How do I write data to csv file in columns and rows from a list in python?

Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' ', you are not really producing a CSV file. You should simply construct csv.writer with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):

example = csv.writer(open("test.csv", "wb"), dialect="excel")

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Convert character to ASCII code in JavaScript

str.charCodeAt(index)

Using charCodeAt() The following example returns 65, the Unicode value for A.

'ABC'.charCodeAt(0) // returns 65

Getting Access Denied when calling the PutObject operation with bucket-level permission

Error : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I solved the issue by passing Extra Args parameter as PutObjectAcl is disabled by company policy.

s3_client.upload_file('./local_file.csv', 'bucket-name', 'path', ExtraArgs={'ServerSideEncryption': 'AES256'})

Using android.support.v7.widget.CardView in my project (Eclipse)

You need to add this in your build.gradle:

dependencies {
    ...
    compile 'com.android.support:cardview-v7:+'
}

And then Sync Project with Gradle Files. Finally, you can use CardView as it's described here.

PHP - Notice: Undefined index:

For starters,

mysql_connect() should not have a $ accompanying it; it is not a variable, it is a predefined function. Remove the $ to properly connect to the database.

Why do you have an XML tag at the top of this document? This is HTML/PHP - a HTML doctype should suffice.

From line 215, update:

if (isset($_POST)) {
    $Name = $_POST['Name'];
    $Surname = $_POST['Surname'];

    $Username = $_POST['Username'];

    $Email = $_POST['Email'];
    $C_Email = $_POST['C_Email'];

    $Password = $_POST['password'];
    $C_Password = $_POST['c_password'];

    $SecQ = $_POST['SecQ'];
    $SecA = $_POST['SecA'];
}

POST variables are coming from your form, and you have to check whether they exist or not, else PHP will give you a NOTICE error. You can disable these notices by placing error_reporting(0); at the top of your document. It's best to keep these visible for development purposes.

You should only be interacting with the database (inserting, checking) under the condition that the form has been submitted. If you do not, PHP will run all of these operations without any input from the user. Its best to use an IF statement, like so:

if (isset($_POST['submit']) {
// blah blah
// check if user exists, check if fields are blank
// insert the user if all of this stuff checks out..
} else {
// just display the form
}

Awesome form tutorial: http://php.about.com/od/learnphp/ss/php_forms.htm

UL list style not applying

Make sure you have no display property set in the li tag in my case I had a display: flex property on my li tag for some reason.

Styling text input caret

It is enough to use color property alongside with -webkit-text-fill-color this way:

_x000D_
_x000D_
    input {_x000D_
        color: red; /* color of caret */_x000D_
        -webkit-text-fill-color: black; /* color of text */_x000D_
    }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.

The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN

So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.

Tuples( or arrays ) as Dictionary keys in C#

Between tuple and nested dictionaries based approaches, it's almost always better to go for tuple based.

From maintainability point of view,

  • its much easier to implement a functionality that looks like:

    var myDict = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
    

    than

    var myDict = new Dictionary<TypeA, Dictionary<TypeB, Dictionary<TypeC, string>>>();
    

    from the callee side. In the second case each addition, lookup, removal etc require action on more than one dictionary.

  • Furthermore, if your composite key require one more (or less) field in future, you will need to change code a significant lot in the second case (nested dictionary) since you have to add further nested dictionaries and subsequent checks.

From performance perspective, the best conclusion you can reach is by measuring it yourself. But there are a few theoretical limitations which you can consider beforehand:

  • In the nested dictionary case, having an additional dictionary for every keys (outer and inner) will have some memory overhead (more than what creating a tuple would have).

  • In the nested dictionary case, every basic action like addition, updation, lookup, removal etc need to be carried out in two dictionaries. Now there is a case where nested dictionary approach can be faster, i.e., when the data being looked up is absent, since the intermediate dictionaries can bypass the full hash code computation & comparison, but then again it should be timed to be sure. In presence of data, it should be slower since lookups should be performed twice (or thrice depending on nesting).

  • Regarding tuple approach, .NET tuples are not the most performant when they're meant to be used as keys in sets since its Equals and GetHashCode implementation causes boxing for value types.

I would go with tuple based dictionary, but if I want more performance, I would use my own tuple with better implementation.


On a side note, few cosmetics can make the dictionary cool:

  1. Indexer style calls can be a lot cleaner and intuitive. For eg,

    string foo = dict[a, b, c]; //lookup
    dict[a, b, c] = ""; //update/insertion
    

    So expose necessary indexers in your dictionary class which internally handles the insertions and lookups.

  2. Also, implement a suitable IEnumerable interface and provide an Add(TypeA, TypeB, TypeC, string) method which would give you collection initializer syntax, like:

    new MultiKeyDictionary<TypeA, TypeB, TypeC, string> 
    { 
        { a, b, c, null }, 
        ...
    };
    

What are the correct version numbers for C#?

  • C# 1.0 with Visual Studio.NET

  • C# 2.0 with Visual Studio 2005

  • C# 3.0 with Visual Studio 2008

  • C# 4.0 with Visual Studio 2010

  • C# 5.0 with Visual Studio 2012

  • C# 6.0 with Visual Studio 2015

  • C# 7.0 with Visual Studio 2017

  • C# 8.0 with Visual Studio 2019

android: how to change layout on button click?

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

How do I multiply each element in a list by a number?

from functools import partial as p
from operator import mul
map(p(mul,5),my_list)

is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

Reset local repository branch to be just like remote repository HEAD

Here is a script that automates what the most popular answer suggests ... See https://stackoverflow.com/a/13308579/1497139 for an improved version that supports branches

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# see https://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  git branch "auto-save-at-$timestamp" 
fi
git fetch origin
git reset --hard origin/master

AttributeError: 'DataFrame' object has no attribute

value_counts is a Series method rather than a DataFrame method (and you are trying to use it on a DataFrame, clean). You need to perform this on a specific column:

clean[column_name].value_counts()

It doesn't usually make sense to perform value_counts on a DataFrame, though I suppose you could apply it to every entry by flattening the underlying values array:

pd.value_counts(df.values.flatten())

How do I check if I'm running on Windows in Python?

in sys too:

import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')

ETag vs Header Expires

Expires and Cache-Control are "strong caching headers"

Last-Modified and ETag are "weak caching headers"

First the browser check Expires/Cache-Control to determine whether or not to make a request to the server

If have to make a request, it will send Last-Modified/ETag in the HTTP request. If the Etag value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.

Determining the last row in a single column

Update 2021 - Considers also empty cells

The accepted answer as well as most of the answers (if not all of them) have one common limitation which might not be the case for the owner of the question (they have contiguous data) but for future readers.

  • Namely, if the selected column contains empty cells in between, the accepted answer would give the wrong result.

For example, consider this very simple scenario:

enter image description here

the accepted solution would give 4 while the correct answer is 6.

Solution:

Find the index of first non-empty value starting from the end of the array by using the reverse method.

const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1')
const lrow = sh.getLastRow();
const Avals = sh.getRange("A1:A"+lrow).getValues();
const Alast  = lrow - Avals.reverse().findIndex(c=>c[0]!='');

How to convert a single char into an int

Any problems with the following way of doing it?

int CharToInt(const char c)
{
    switch (c)
    {
    case '0':
        return 0;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    case '6':
        return 6;
    case '7':
        return 7;
    case '8':
        return 8;
    case '9':
        return 9;
    default:
        return 0;
    }
}

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

How do I read configuration settings from Symfony2 config.yml?

Rather than defining contact_email within app.config, define it in a parameters entry:

parameters:
    contact_email: [email protected]

You should find the call you are making within your controller now works.

window.onload vs document.onload

In short

  • window.onload is not supported by IE 6-8
  • document.onload is not supported by any modern browser (event is never fired)

_x000D_
_x000D_
window.onload   = () => console.log('window.onload works');   // fired
document.onload = () => console.log('document.onload works'); // not fired
_x000D_
_x000D_
_x000D_

Iterating through all nodes in XML file

To iterate through all elements

XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
    Console.WriteLine(element.Name);
}

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

How to get annotations of a member variable?

You have to use reflection to get all the member fields of User class, iterate through them and find their annotations

something like this:

public void getAnnotations(Class clazz){
    for(Field field : clazz.getDeclaredFields()){
        Class type = field.getType();
        String name = field.getName();
        field.getDeclaredAnnotations(); //do something to these
    }
}

How to get UTC timestamp in Ruby?

Time.utc(2010, 05, 17)

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

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

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

Best design for a changelog / auditing database table?

In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:

event ID
event date/time
event type
user ID
description

The idea was the same: to keep things simple.

However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this:

Who the heck created/updated/deleted a record 
with ID=X in the table Foo and when?

So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table

object type (or table name)
object ID

That's when design of our audit log really stabilized (for a few years now).

Of course, the last "improvement" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key!

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

As it allows to install more than one version of java, I had install many 3 versions unknowingly but it was point to latest version "11.0.2"

I could able to solve this issue with below steps to move to "1.8"

$java -version

openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

cd /Library/Java/JavaVirtualMachines
ls

jdk1.8.0_201.jdk jdk1.8.0_202.jdk openjdk-11.0.2.jdk

sudo rm -rf openjdk-11.0.2.jdk
sudo rm -rf jdk1.8.0_201.jdk
ls

jdk1.8.0_202.jdk

java -version

java version "1.8.0_202-ea" Java(TM) SE Runtime Environment (build 1.8.0_202-ea-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b03, mixed mode)

How do I convert a String to a BigInteger?

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

CMake: How to build external projects and include their targets

cmake's ExternalProject_Add indeed can used, but what I did not like about it - is that it performs something during build, continuous poll, etc... I would prefer to build project during build phase, nothing else. I have tried to override ExternalProject_Add in several attempts, unfortunately without success.

Then I have tried also to add git submodule, but that drags whole git repository, while in certain cases I need only subset of whole git repository. What I have checked - it's indeed possible to perform sparse git checkout, but that require separate function, which I wrote below.

#-----------------------------------------------------------------------------
#
# Performs sparse (partial) git checkout
#
#   into ${checkoutDir} from ${url} of ${branch}
#
# List of folders and files to pull can be specified after that.
#-----------------------------------------------------------------------------
function (SparseGitCheckout checkoutDir url branch)
    if(EXISTS ${checkoutDir})
        return()
    endif()

    message("-------------------------------------------------------------------")
    message("sparse git checkout to ${checkoutDir}...")
    message("-------------------------------------------------------------------")

    file(MAKE_DIRECTORY ${checkoutDir})

    set(cmds "git init")
    set(cmds ${cmds} "git remote add -f origin --no-tags -t master ${url}")
    set(cmds ${cmds} "git config core.sparseCheckout true")

    # This command is executed via file WRITE
    # echo <file or folder> >> .git/info/sparse-checkout")

    set(cmds ${cmds} "git pull --depth=1 origin ${branch}")

    # message("In directory: ${checkoutDir}")

    foreach( cmd ${cmds})
        message("- ${cmd}")
        string(REPLACE " " ";" cmdList ${cmd})

        #message("Outfile: ${outFile}")
        #message("Final command: ${cmdList}")

        if(pull IN_LIST cmdList)
            string (REPLACE ";" "\n" FILES "${ARGN}")
            file(WRITE ${checkoutDir}/.git/info/sparse-checkout ${FILES} )
        endif()

        execute_process(
            COMMAND ${cmdList}
            WORKING_DIRECTORY ${checkoutDir}
            RESULT_VARIABLE ret
        )

        if(NOT ret EQUAL "0")
            message("error: previous command failed, see explanation above")
            file(REMOVE_RECURSE ${checkoutDir})
            break()
        endif()
    endforeach()

endfunction()


SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_197 https://github.com/catchorg/Catch2.git v1.9.7 single_include)
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_master https://github.com/catchorg/Catch2.git master single_include)

I have added two function calls below just to illustrate how to use the function.

Someone might not like to checkout master / trunk, as that one might be broken - then it's always possible to specify specific tag.

Checkout will be performed only once, until you clear the cache folder.

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

const * char is invalid C code and is meaningless. Perhaps you meant to ask the difference between a const char * and a char const *, or possibly the difference between a const char * and a char * const?

See also:

Comparing date part only without comparing time in JavaScript

Simply compare using .toDateString like below:

new Date().toDateString();

This will return you date part only and not time or timezone, like this:

"Fri Feb 03 2017"

Hence both date can be compared in this format likewise without time part of it.

Could not install packages due to an EnvironmentError: [Errno 13]

I also had the same problem, I tried many different command lines, this one worked for me:

Try:

    conda install py-xgboost

That's what I got:

Collecting package metadata: done
Solving environment: done

## Package Plan ##

  environment location: /home/simplonco/anaconda3

  added / updated specs:
    - py-xgboost


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    _py-xgboost-mutex-2.0      |            cpu_0           9 KB
    ca-certificates-2019.1.23  |                0         126 KB
    certifi-2018.11.29         |           py37_0         146 KB
    conda-4.6.2                |           py37_0         1.7 MB
    libxgboost-0.80            |       he6710b0_0         3.7 MB
    mkl-2019.1                 |              144       204.6 MB
    mkl_fft-1.0.10             |   py37ha843d7b_0         169 KB
    mkl_random-1.0.2           |   py37hd81dba3_0         405 KB
    numpy-1.15.4               |   py37h7e9f1db_0          47 KB
    numpy-base-1.15.4          |   py37hde5b4d6_0         4.2 MB
    py-xgboost-0.80            |   py37he6710b0_0         1.7 MB
    scikit-learn-0.20.2        |   py37hd81dba3_0         5.7 MB
    scipy-1.2.0                |   py37h7c811a0_0        17.7 MB
    ------------------------------------------------------------
                                           Total:       240.0 MB

The following NEW packages will be INSTALLED:

  _py-xgboost-mutex  pkgs/main/linux-64::_py-xgboost-mutex-2.0-cpu_0
  libxgboost         pkgs/main/linux-64::libxgboost-0.80-he6710b0_0
  py-xgboost         pkgs/main/linux-64::py-xgboost-0.80-py37he6710b0_0

The following packages will be UPDATED:

  ca-certificates     anaconda::ca-certificates-2018.12.5-0 --> pkgs/main::ca-certificates-2019.1.23-0
  mkl                                            2019.0-118 --> 2019.1-144
  mkl_fft                              1.0.4-py37h4414c95_1 --> 1.0.10-py37ha843d7b_0
  mkl_random                           1.0.1-py37h4414c95_1 --> 1.0.2-py37hd81dba3_0
  numpy                               1.15.1-py37h1d66e8a_0 --> 1.15.4-py37h7e9f1db_0
  numpy-base                          1.15.1-py37h81de0dd_0 --> 1.15.4-py37hde5b4d6_0
  scikit-learn                        0.19.2-py37h4989274_0 --> 0.20.2-py37hd81dba3_0
  scipy                                1.1.0-py37hfa4b5c9_1 --> 1.2.0-py37h7c811a0_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi                                          anaconda --> pkgs/main
  conda                                            anaconda --> pkgs/main
  openssl                anaconda::openssl-1.1.1-h7b6447c_0 --> pkgs/main::openssl-1.1.1a-h7b6447c_0


Proceed ([y]/n)? y


Downloading and Extracting Packages
libxgboost-0.80      | 3.7 MB    | ##################################### | 100% 
mkl_random-1.0.2     | 405 KB    | ##################################### | 100% 
certifi-2018.11.29   | 146 KB    | ##################################### | 100% 
ca-certificates-2019 | 126 KB    | ##################################### | 100% 
conda-4.6.2          | 1.7 MB    | ##################################### | 100% 
mkl-2019.1           | 204.6 MB  | ##################################### | 100% 
mkl_fft-1.0.10       | 169 KB    | ##################################### | 100% 
numpy-1.15.4         | 47 KB     | ##################################### | 100% 
scipy-1.2.0          | 17.7 MB   | ##################################### | 100% 
scikit-learn-0.20.2  | 5.7 MB    | ##################################### | 100% 
py-xgboost-0.80      | 1.7 MB    | ##################################### | 100% 
_py-xgboost-mutex-2. | 9 KB      | ##################################### | 100% 
numpy-base-1.15.4    | 4.2 MB    | ##################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done

Extract part of a regex match

Try:

title = re.search('<title>(.*)</title>', html, re.IGNORECASE).group(1)

Check empty string in Swift?

I am completely rewriting my answer (again). This time it is because I have become a fan of the guard statement and early return. It makes for much cleaner code.

Non-Optional String

Check for zero length.

let myString: String = ""

if myString.isEmpty {
    print("String is empty.")
    return // or break, continue, throw
}

// myString is not empty (if this point is reached)
print(myString)

If the if statement passes, then you can safely use the string knowing that it isn't empty. If it is empty then the function will return early and nothing after it matters.

Optional String

Check for nil or zero length.

let myOptionalString: String? = nil

guard let myString = myOptionalString, !myString.isEmpty else {
    print("String is nil or empty.")
    return // or break, continue, throw
}

// myString is neither nil nor empty (if this point is reached)
print(myString)

This unwraps the optional and checks that it isn't empty at the same time. After passing the guard statement, you can safely use your unwrapped nonempty string.

Delete all rows in a table based on another table

This will delete all rows in Table1 that match the criteria:

DELETE Table1 
FROM Table2 
WHERE Table1.JoinColumn = Table2.JoinColumn And Table1.SomeStuff = 'SomeStuff'

Convert between UIImage and Base64 string

I tried all the solutions, none worked for me (using Swift 4), this is the solution that worked for me, if anyone in future faces the same problem.

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage

Python list directory, subdirectory, and files

You can take a look at this sample I made. It uses the os.path.walk function which is deprecated beware.Uses a list to store all the filepaths

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

Is there possibility of sum of ArrayList without looping

This can be done with reduce using method references reduce(Integer::sum):

Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
        .stream()
        .reduce(Integer::sum)
        .get();

Or without Optional:

Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
        .stream()
        .reduce(0, Integer::sum);

Using a scanner to accept String input and storing in a String Array

There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.

How to remove line breaks (no characters!) from the string?

$str = "
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill";

echo str_replace(array("\n", "\r"), '', $str);  // echo $str in a single line

Why does Eclipse complain about @Override on interface methods?

You could change the compiler settings to accept Java 6 syntax but generate Java 5 output (as I remember). And set the "Generated class files compatibility" a bit lower if needed by your runtime. Update: I checked Eclipse, but it complains if I set source compatibility to 1.6 and class compatibility to 1.5. If 1.6 is not allowed I usually manually comment out the offending @Override annotations in the source (which doesn't help your case).

Update2: If you do only manual build, you could write a small program which copies the original project into a new one, strips @Override annotations from the java sources and you just hit Clean project in Eclipse.

Refresh a page using JavaScript or HTML

You can also use

<input type="button" value = "Refresh" onclick="history.go(0)" />

It works fine for me.

Rounding a variable to two decimal places C#

Use System.Math.Round to rounds a decimal value to a specified number of fractional digits.

var pay = 200 + bonus;
pay = System.Math.Round(pay, 2);
Console.WriteLine(pay);

MSDN References:

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

If you’re using TortoiseSVN…

From your commit window in the “Changes Made” section you can select all the offending files, then right-click and select delete. Finish the commit and the files will be removed from the scheduled additions.

Redirect to Action in another controller

Try switching them:

return RedirectToAction("Account", "Login");

I tried it and it worked.

lodash multi-column sortBy descending

It's worth noting that if you want to sort particular properties descending, you don't want to simply append .reverse() at the end, as this will make all of the sorts descending.

To make particular sorts descending, chain your sorts from least significant to most significant, calling .reverse() after each sort that you want to be descending.

var data = _(data).chain()
    .sort("date")
    .reverse()    // sort by date descending
    .sort("name") // sort by name ascending
    .result()

Since _'s sort is a stable sort, you can safely chain and reverse sorts because if two items have the same value for a property, their order is preserved.

More information

How do I measure execution time of a command on the Windows command line?

This is a comment/edit to Luke Sampson's nice timecmd.bat and reply to

For some reason this only gives me output in whole seconds... which for me is useless. I mean that I run timecmd pause, and it always results in 1.00 sec, 2.00 sec, 4.00 sec... even 0.00 sec! Windows 7. – Camilo Martin Sep 25 '13 at 16:00 "

On some configurations the delimiters may differ. The following change should cover atleast most western countries.

set options="tokens=1-4 delims=:,." (added comma)

The %time% milliseconds work on my system after adding that ','

(*because site doesn't allow anon comment and doesn't keep good track of identity even though I always use same guest email which combined with ipv6 ip and browser fingerprint should be enough to uniquely identify without password)

Automatically create an Enum based on values in a database lookup table?

enum builder class

public class XEnum
{
    private EnumBuilder enumBuilder;
    private int index;
    private AssemblyBuilder _ab;
    private AssemblyName _name;
    public XEnum(string enumname)
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        _name = new AssemblyName("MyAssembly");
        _ab = currentDomain.DefineDynamicAssembly(
            _name, AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder mb = _ab.DefineDynamicModule("MyModule");

        enumBuilder = mb.DefineEnum(enumname, TypeAttributes.Public, typeof(int));


    }
    /// <summary>
    /// adding one string to enum
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public FieldBuilder add(string s)
    {
        FieldBuilder f = enumBuilder.DefineLiteral(s, index);
        index++;
        return f;
    }
    /// <summary>
    /// adding array to enum
    /// </summary>
    /// <param name="s"></param>
    public void addRange(string[] s)
    {
        for (int i = 0; i < s.Length; i++)
        {
            enumBuilder.DefineLiteral(s[i], i);
        }
    }
    /// <summary>
    /// getting index 0
    /// </summary>
    /// <returns></returns>
    public object getEnum()
    {
        Type finished = enumBuilder.CreateType();
        _ab.Save(_name.Name + ".dll");
        Object o1 = Enum.Parse(finished, "0");
        return o1;
    }
    /// <summary>
    /// getting with index
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    public object getEnum(int i)
    {
        Type finished = enumBuilder.CreateType();
        _ab.Save(_name.Name + ".dll");
        Object o1 = Enum.Parse(finished, i.ToString());
        return o1;
    }
}

create an object

string[] types = { "String", "Boolean", "Int32", "Enum", "Point", "Thickness", "long", "float" };
XEnum xe = new XEnum("Enum");
        xe.addRange(types);
        return xe.getEnum();

How to Update a Component without refreshing full page - Angular

To update component

 @Injectable()
    export class LoginService{
    private isUserLoggedIn: boolean = false;

    public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
    this.isUserLoggedIn= flag;
    }


public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}

Login Component ts
            Login Component{
             constructor(public service: LoginService){}

public login(){
service.setLoggedInUser(true);
}
            }
Inside Header component

 Header Component ts
        HeaderComponent {
         constructor(public service: LoginService){}

         public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
        }

template of header component: Check for user sign in here

<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>

You can use many approach like show hide using ngIf

App Component ts
AppComponent {
 public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>

You can also use service

@Injectable()
export class AppService {
private showHeader: boolean = false;

public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}

public getHeader(): boolean {
return this.showHeader;
}
}

App Component.ts
    AppComponent {
     constructor(public service: AppService){}
    }

App Component.html
    <div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
    <app-header></app-header>
    </div>
    <router-outlet></router-outlet>
    <app-footer></app-footer>

How can I create an array with key value pairs?

My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:

$catList[$row["datasource_id"]] = $row["title"];

In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.

Html table tr inside td

_x000D_
_x000D_
<table border="1px;" width="100%">
  <tr align="center">
    <td>Product</td>
    <td>quantity</td>
    <td>Price</td>
    <td>Totall</td>
  </tr>
  <tr align="center">
    <td>Item-1</td>
    <td>Item-1</td>
    <td>
      <table border="1px;" width="100%">
        <tr align="center">
          <td>Name1</td>
          <td>Price1</td>
        </tr>
        <tr align="center">
          <td>Name2</td>
          <td>Price2</td>
        </tr>
        <tr align="center">
          <td>Name3</td>
          <td>Price3</td>
        </tr>
        <tr>
          <td>Name4</td>
          <td>Price4</td>
        </tr>
      </table>
    </td>
    <td>Item-1</td>
  </tr>
  <tr align="center">
    <td>Item-2</td>
    <td>Item-2</td>
    <td>Item-2</td>
    <td>Item-2</td>
  </tr>
  <tr align="center">
    <td>Item-3</td>
    <td>Item-3</td>
    <td>Item-3</td>
    <td>Item-3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

How to pipe list of files returned by find command to cat to view all the files

  1. Piping to another process (Although this WON'T accomplish what you said you are trying to do):

    command1 | command2
    

    This will send the output of command1 as the input of command2

  2. -exec on a find (this will do what you are wanting to do -- but is specific to find)

    find . -name '*.foo' -exec cat {} \;
    

    (Everything between find and -exec are the find predicates you were already using. {} will substitute the particular file you found into the command (cat {} in this case); the \; is to end the -exec command.)

  3. send output of one process as command line arguments to another process

    command2 `command1`
    

    for example:

    cat `find . -name '*.foo' -print`
    

    (Note these are BACK-QUOTES not regular quotes (under the tilde ~ on my keyboard).) This will send the output of command1 into command2 as command line arguments. Note that file names containing spaces (newlines, etc) will be broken into separate arguments, though.

SQL 'LIKE' query using '%' where the search criteria contains '%'

The easiest solution is to dispense with "like" altogether:

Select * 
from table
where charindex(search_criteria, name) > 0

I prefer charindex over like. Historically, it had better performance, but I'm not sure if it makes much of difference now.

Change File Extension Using C#

You should do a move of the file to rename it. In your example code you are only changing the string, not the file:

myfile= "c:/my documents/my images/cars/a.jpg";
string extension = Path.GetExtension(myffile); 
myfile.replace(extension,".Jpeg");

you are only changing myfile (which is a string). To move the actual file, you should do

FileInfo f = new FileInfo(myfile);
f.MoveTo(Path.ChangeExtension(myfile, ".Jpeg"));

See FileInfo.MoveTo

How do I import the javax.servlet API in my Eclipse project?

For maven projects add following dependancy :

<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Reference

For gradle projects:

dependencies {
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
}

or download javax.servlet.jar and add to your project.

Performance of Java matrix math libraries?

I'm the author of la4j (Linear Algebra for Java) library and here is my point. I've been working on la4j for 3 years (the latest release is 0.4.0 [01 Jun 2013]) and only now I can start doing performace analysis and optimizations since I've just covered the minimal required functional. So, la4j isn't as fast as I wanted but I'm spending loads of my time to change it.

I'm currently in the middle of porting new version of la4j to JMatBench platform. I hope new version will show better performance then previous one since there are several improvement I made in la4j such as much faster internal matrix format, unsafe accessors and fast blocking algorithm for matrix multiplications.

Jasmine.js comparing arrays

just for the record you can always compare using JSON.stringify

const arr = [1,2,3]; expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3])); expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));

It's all meter of taste, this will also work for complex literal objects

How to calculate md5 hash of a file using javascript

I don't believe there is a way in javascript to access the contents of a file upload. So you therefore cannot look at the file contents to generate an MD5 sum.

You can however send the file to the server, which can then send an MD5 sum back or send the file contents back .. but that's a lot of work and probably not worthwhile for your purposes.

Pass Javascript Variable to PHP POST

Your idea of an hidden form element is solid. Something like this

<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>

<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>

Of course, this will change the location to script.php. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required

$.post("script.php", { total: getTotalFromSomewhere });

How do I configure Maven for offline development?

Answering your question directly: it does not require an internet connection, but access to a repository, on LAN or local disk (use hints from other people who posted here).

If your project is not in a mature phase, that means when POMs are changed quite often, offline mode will be very impractical, as you'll have to update your repository quite often, too. Unless you can get a copy of a repository that has everything you need, but how would you know? Usually you start a repository from scratch and it gets cloned gradually during development (on a computer connected to another repository). A copy of the repo1.maven.org public repository weighs hundreds of gigabytes, so I wouldn't recommend brute force, either.

Python coding standards/best practices

I stick to PEP-8 very closely.

There are three specific things that I can't be bothered to change to PEP-8.

  • Avoid extraneous whitespace immediately inside parentheses, brackets or braces.

    Suggested: spam(ham[1], {eggs: 2})

    I do this anyway: spam( ham[ 1 ], { eggs: 2 } )

    Why? 30+ years of ingrained habit is snuggling ()'s up against function names or (in C) statements keywords. Starting with Fortran IV in the 70's.

  • Use spaces around arithmetic operators:

    Suggested: x = x * 2 - 1

    I do this anyway: x= x * 2 - 1

    Why? Gries' The Science of Programming suggested this as a way to emphasize the connection between assignment and the variable who's state is being changed.

    It doesn't work well for multiple assignment or augmented assignment, for that I use lots of spaces.

  • For function names, method names and instance variable names

    Suggested: lowercase, with words separated by underscores as necessary to improve readability.

    I do this anyway: camelCase

    Why? 20+ years of ingrained habit of camelCase, starting with Pascal in the 80's.

Android: Unable to add window. Permission denied for this window type

Search

Draw over other apps

in your setting and enable your app. For Android 8 Oreo, try

Settings > Apps & Notifications > App info > Display over other apps > Enable

How can I find the maximum value and its index in array in MATLAB?

For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html

How to send a POST request from node.js Express?

var request = require('request');
 function updateClient(postData){
            var clientServerOptions = {
                uri: 'http://'+clientHost+''+clientContext,
                body: JSON.stringify(postData),
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            request(clientServerOptions, function (error, response) {
                console.log(error,response.body);
                return;
            });
        }

For this to work, your server must be something like:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

var port = 9000;

app.post('/sample/put/data', function(req, res) {
    console.log('receiving data ...');
    console.log('body is ',req.body);
    res.send(req.body);
});

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

Changing text color of menu item in navigation drawer

add app:itemTextColor="#fff" in your NavigationView like

 <android.support.design.widget.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    app:menu="@menu/slider_menu"
    android:background="@color/colorAccent"
    app:itemTextColor="#fff"
    android:id="@+id/navigation_view"
    android:layout_gravity="start"/>

Hibernate show real SQL

Can I see (...) the real SQL

If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).

Alternatively you can enable logging of the following categories (using a log4j.properties file here):

log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

The first is equivalent to hibernate.show_sql=true, the second prints the bound parameters among other things.

Reference

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

how to add <script>alert('test');</script> inside a text box?

Ok to answer this . I simply converted my < and the > to &lt; and &gt;. What was happening previously is i used to set the text <script>alert('1')</script> but before setting the text in the input text browserconverts &lt; and &gt; as < and the >. So hence converting them again to &lt; and &gt;since browser will understand that as only tags and converts them , than executing the script inside <input type="text" />

Could not autowire field:RestTemplate in Spring boot application

Error points directly that RestTemplate bean is not defined in context and it cannot load the beans.

  1. Define a bean for RestTemplate and then use it
  2. Use a new instance of the RestTemplate

If you are sure that the bean is defined for the RestTemplate then use the following to print the beans that are available in the context loaded by spring boot application

ApplicationContext ctx = SpringApplication.run(Application.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
    System.out.println(beanName);
}

If this contains the bean by the name/type given, then all good. Or else define a new bean and then use it.

Drag and drop menuitems

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

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I doubt anything is killing the process just because it takes a long time. Killed generically means something from the outside terminated the process, but probably not in this case hitting Ctrl-C since that would cause Python to exit on a KeyboardInterrupt exception. Also, in Python you would get MemoryError exception if that was the problem. What might be happening is you're hitting a bug in Python or standard library code that causes a crash of the process.

What does this thread join code mean?

This is a favorite Java interview question.

Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();

while (true) {
    try {
        t1.join(); // 1
        t2.join(); // 2  These lines (1,2) are in in public static void main
        break;
    }
}

t1.join() means, t1 says something like "I want to finish first". Same is the case with t2. No matter who started t1 or t2 thread (in this case the main method), main will wait until t1 and t2 finish their task.

However, an important point to note down, t1 and t2 themselves can run in parallel irrespective of the join call sequence on t1 and t2. It is the main/daemon thread that has to wait.

Retrieve list of tasks in a queue in Celery

This worked for me in my application:

def get_celery_queue_active_jobs(queue_name):
    connection = <CELERY_APP_INSTANCE>.connection()

    try:
        channel = connection.channel()
        name, jobs, consumers = channel.queue_declare(queue=queue_name, passive=True)
        active_jobs = []

        def dump_message(message):
            active_jobs.append(message.properties['application_headers']['task'])

        channel.basic_consume(queue=queue_name, callback=dump_message)

        for job in range(jobs):
            connection.drain_events()

        return active_jobs
    finally:
        connection.close()

active_jobs will be a list of strings that correspond to tasks in the queue.

Don't forget to swap out CELERY_APP_INSTANCE with your own.

Thanks to @ashish for pointing me in the right direction with his answer here: https://stackoverflow.com/a/19465670/9843399

Difference between ApiController and Controller in ASP.NET MVC

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach.

The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.

In order to do that, you need to do the following:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/ folder.
  • Add the following WebApiConfig.cs file to your /App_Config/ folder:

using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).

Startup.cs

 public void Configuration(IAppBuilder app)
 {
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureAuth(app);
    // ...
}

Global.asax.cs

protected void Application_Start()
{
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

This approach - together with its pros and cons - is further explained in this post I wrote on my blog.

Parsing JSON using C

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

"401 Unauthorized" on a directory

For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.

Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.

JPA Hibernate One-to-One relationship

This should be working too using JPA 2.0 @MapsId annotation instead of Hibernate's GenericGenerator:

@Entity
public class Person {

    @Id
    @GeneratedValue
    public int id;

    @OneToOne
    @PrimaryKeyJoinColumn
    public OtherInfo otherInfo;

    rest of attributes ...
}

@Entity
public class OtherInfo {

    @Id
    public int id;

    @MapsId
    @OneToOne
    @JoinColumn(name="id")
    public Person person;

    rest of attributes ...
}

More details on this in Hibernate 4.1 documentation under section 5.1.2.2.7.

How to get last inserted row ID from WordPress database?

I needed to get the last id way after inserting it, so

$lastid = $wpdb->insert_id;

Was not an option.

Did the follow:

global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');

Regex remove all special characters except numbers?

If you don't mind including the underscore as an allowed character, you could try simply:

result = subject.replace(/\W+/g, "");

If the underscore must be excluded also, then

result = subject.replace(/[^A-Z0-9]+/ig, "");

(Note the case insensitive flag)

getting error while updating Composer

If you're using php 7.3 for laravel 5.7. this work for me

sudo apt-get install php-gd php-xml php7.3-mbstring

Text Editor For Linux (Besides Vi)?

The best I've found is gedit unfortunately. Spend a few hours with it and you'll discover it's not so bad, with plugins and themes. You can use the command line to open documents in it.

Check if input is number or letter javascript

you can use isNaN(). it returns true when data is not number.

var data = 'hello there';
if(isNaN(data)){
  alert("it is not number");
}else {
  alert("its a valid number");
}

How do I create a circle or square with just CSS - with a hollow center?

In case of circle all you need is one div, but in case of hollow square you need to have 2 divs. The divs are having a display of inline-block which you can change accordingly. Live Codepen link: Click Me

In case of circle all you need to change is the border properties and the dimensions(width and height) of circle. If you want to change color just change the border color of hollow-circle.

In case of the square background-color property needs to be changed depending upon the background of page or the element upon which you want to place the hollow-square. Always keep the inner-circle dimension small as compared to the hollow-square. If you want to change color just change the background-color of hollow-square. The inner-circle is centered upon the hollow-square using the position, top, left, transform properties just don't mess with them.

Code is as follows:

_x000D_
_x000D_
/* CSS Code */_x000D_
_x000D_
.hollow-circle {_x000D_
  width: 4rem;_x000D_
  height: 4rem;_x000D_
  background-color: transparent;_x000D_
  border-radius: 50%;_x000D_
  display: inline-block;_x000D_
  _x000D_
  /* Use this */_x000D_
  border-color: black;_x000D_
  border-width: 5px;_x000D_
  border-style: solid;_x000D_
  /* or */_x000D_
  /* Shorthand Property */_x000D_
  /* border: 5px solid #000; */_x000D_
}_x000D_
_x000D_
.hollow-square {_x000D_
  position: relative;_x000D_
  width: 4rem;_x000D_
  height: 4rem;_x000D_
  display: inline-block;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner-circle {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  width: 3rem;_x000D_
  height: 3rem;_x000D_
  border-radius: 50%;_x000D_
  background-color: white;_x000D_
}
_x000D_
<!-- HTML Code -->_x000D_
_x000D_
<div class="hollow-circle">_x000D_
</div>_x000D_
_x000D_
<br/><br/><br/>_x000D_
_x000D_
<div class="hollow-square">_x000D_
  <div class="inner-circle"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Download File Using Javascript/jQuery

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

_x000D_
_x000D_
fetch('https://jsonplaceholder.typicode.com/todos/1')_x000D_
  .then(resp => resp.blob())_x000D_
  .then(blob => {_x000D_
    const url = window.URL.createObjectURL(blob);_x000D_
    const a = document.createElement('a');_x000D_
    a.style.display = 'none';_x000D_
    a.href = url;_x000D_
    // the filename you want_x000D_
    a.download = 'todo-1.json';_x000D_
    document.body.appendChild(a);_x000D_
    a.click();_x000D_
    window.URL.revokeObjectURL(url);_x000D_
    alert('your file has downloaded!'); // or you know, something with better UX..._x000D_
  })_x000D_
  .catch(() => alert('oh no!'));
_x000D_
_x000D_
_x000D_

2012 original jQuery/iframe/cookie based approach

I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

  • Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too

  • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications

  • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation

  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this. Hope this helps someone!

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

When should I use a List vs a LinkedList

My previous answer was not enough accurate. As truly it was horrible :D But now I can post much more useful and correct answer.


I did some additional tests. You can find it's source by the following link and reCheck it on your environment by your own: https://github.com/ukushu/DataStructuresTestsAndOther.git

Short results:

  • Array need to use:

    • So often as possible. It's fast and takes smallest RAM range for same amount information.
    • If you know exact count of cells needed
    • If data saved in array < 85000 b (85000/32 = 2656 elements for integer data)
    • If needed high Random Access speed
  • List need to use:

    • If needed to add cells to the end of list (often)
    • If needed to add cells in the beginning/middle of the list (NOT OFTEN)
    • If data saved in array < 85000 b (85000/32 = 2656 elements for integer data)
    • If needed high Random Access speed
  • LinkedList need to use:

    • If needed to add cells in the beginning/middle/end of the list (often)
    • If needed only sequential access (forward/backward)
    • If you need to save LARGE items, but items count is low.
    • Better do not use for large amount of items, as it's use additional memory for links.

More details:

??????? ???? ???????? ??????????? Interesting to know:

  1. LinkedList<T> internally is not a List in .NET. It's even does not implement IList<T>. And that's why there are absent indexes and methods related to indexes.

  2. LinkedList<T> is node-pointer based collection. In .NET it's in doubly linked implementation. This means that prior/next elements have link to current element. And data is fragmented -- different list objects can be located in different places of RAM. Also there will be more memory used for LinkedList<T> than for List<T> or Array.

  3. List<T> in .Net is Java's alternative of ArrayList<T>. This means that this is array wrapper. So it's allocated in memory as one contiguous block of data. If allocated data size exceeds 85000 bytes, it will be moved to Large Object Heap. Depending on the size, this can lead to heap fragmentation(a mild form of memory leak). But in the same time if size < 85000 bytes -- this provides a very compact and fast-access representation in memory.

  4. Single contiguous block is preferred for random access performance and memory consumption but for collections that need to change size regularly a structure such as an Array generally need to be copied to a new location whereas a linked list only needs to manage the memory for the newly inserted/deleted nodes.

WPF Datagrid Get Selected Cell Value

Ok after doing reverse engineering and a little pixie dust of reflection, one can do this operation on SelectedCells (at any point) to get all (regardless of selected on one row or many rows) the data from one to many selected cells:

MessageBox.Show(

string.Join(", ", myGrid.SelectedCells
                        .Select(cl => cl.Item.GetType()
                                             .GetProperty(cl.Column.SortMemberPath)
                                             .GetValue(cl.Item, null)))

               );

I tried this on text (string) fields only though a DateTime field should return a value the initiate ToString(). Also note that SortMemberPath is not the same as Header so that should always provide the proper property to reflect off of.

<DataGrid ItemsSource="{Binding MyData}"                      
          AutoGenerateColumns="True"
          Name="myGrid"
          IsReadOnly="True"
          SelectionUnit="Cell"
          SelectionMode="Extended">

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

Concatenate two slices in Go

Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:

func append

func append(slice []Type, elems ...Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:

slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)

As a special case, it is legal to append a string to a byte slice, like this:

slice = append([]byte("hello "), "world"...)

How do I find the width & height of a terminal window?

yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'

Bundling data files with PyInstaller (--onefile)

Instead for rewriting all my path code as suggested, I changed the working directory:

if getattr(sys, 'frozen', False):
    os.chdir(sys._MEIPASS)

Just add those two lines at the beginning of your code, you can leave the rest as is.

Socket.io + Node.js Cross-Origin Request Blocked

I had the same problem and any solution worked for me.

The cause was I am using allowRequest to accept or reject the connection using a token I pass in a query parameter.

I have a typo in the query parameter name in the client side, so the connection was always rejected, but the browser complained about cors...

As soon as I fixed the typo, it started working as expected, and I don't need to use anything extra, the global express cors settings is enough.

So, if anything is working for you, and you are using allowRequest, check that this function is working properly, because the errors it throws shows up as cors errors in the browser. Unless you add there the cors headers manually when you want to reject the connection, I guess.

How to get all selected values of a multiple select box?

You Can try this script

     <!DOCTYPE html>
    <html>
    <script>
    function getMultipleSelectedValue()
    {
      var x=document.getElementById("alpha");
      for (var i = 0; i < x.options.length; i++) {
         if(x.options[i].selected ==true){
              alert(x.options[i].value);
          }
      }
    }
    </script>
    </head>
    <body>
    <select multiple="multiple" id="alpha">
      <option value="a">A</option>
      <option value="b">B</option>
      <option value="c">C</option>
      <option value="d">D</option>
    </select>
    <input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
    </body>
    </html>

python's re: return True if string contains regex pattern

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print 'matched'

How to restrict user to type 10 digit numbers in input element?

whereas you could use maxLength on the input, and some javascript validation, it will still be necessary to do server side validation anyway.

QtCreator: No valid kits found

Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.

To do so:

Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.

jQuery form input select by id

You can just target the id directly:

var value = $('#b').val();

If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.

If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:

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

How to run a script file remotely using SSH

Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.

Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.

ssh kev@server1 './test/foo.sh'

Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

What is the difference between a process and a thread?

The best answer I've found so far is Michael Kerrisk's 'The Linux Programming Interface':

In modern UNIX implementations, each process can have multiple threads of execution. One way of envisaging threads is as a set of processes that share the same virtual memory, as well as a range of other attributes. Each thread is executing the same program code and shares the same data area and heap. However, each thread has it own stack containing local variables and function call linkage information. [LPI 2.12]

This book is a source of great clarity; Julia Evans mentioned its help in clearing up how Linux groups really work in this article.

Problems with Android Fragment back stack

Right!!! after much hair pulling I've finally worked out how to make this work properly.

It seems as though fragment [3] is not removed from the view when back is pressed so you have to do it manually!

First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.

The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0)
        {
            this.finish();
            return false;
        }
        else
        {
            getSupportFragmentManager().popBackStack();
            removeCurrentFragment();

            return false;
        }



    }

    return super.onKeyDown(keyCode, event);
}


public void removeCurrentFragment()
{
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    Fragment currentFrag =  getSupportFragmentManager().findFragmentById(R.id.detailFragment);


    String fragName = "NONE";

    if (currentFrag!=null)
        fragName = currentFrag.getClass().getSimpleName();


    if (currentFrag != null)
        transaction.remove(currentFrag);

    transaction.commit();

}

Hope this helps!

Pandas create empty DataFrame with only column names

You can create an empty DataFrame with either column names or an Index:

In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []

Or

In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Edit: Even after your amendment with the .to_html, I can't reproduce. This:

df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')

Produces:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

NO NO NO !!!!!

it's simple, in MIUI 9.x you need developer settings ON and then

  • Settings -> (system & device section) Additional Settings -> Developer options

(Debugging section)

  • Turn On "USB Debugging"
  • Turn On "Install via USB"

Then in Android select Runb app and choose your Xiaome phone

EDIT: you will also need allow installation from unknown sources

How to detect orientation change?

Here is an easy way to detect the device orientation: (Swift 3)

override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
            handleViewRotaion(orientation: toInterfaceOrientation)
        }

    //MARK: - Rotation controls
    func handleViewRotaion(orientation:UIInterfaceOrientation) -> Void {
        switch orientation {
        case .portrait :
            print("portrait view")
            break
        case .portraitUpsideDown :
            print("portraitUpsideDown view")
            break
        case .landscapeLeft :
            print("landscapeLeft view")
            break
        case .landscapeRight :
            print("landscapeRight view")
            break
        case .unknown :
            break
        }
    }

Correct way to find max in an Array in Swift

You can also sort your array and then use array.first or array.last

TypeError: $.ajax(...) is not a function?

I know this is an old posting -- and Gus basically answered it. But in my experience, JQuery has since changed their code for importing from the CDN - so I thought I would go ahead and post their latest code for importing from the CDN:

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

Building a fat jar using maven

You can use the onejar-maven-plugin for packaging. Basically, it assembles your project and its dependencies in as one jar, including not just your project jar file, but also all external dependencies as a "jar of jars", e.g.

<build>
    <plugins>
        <plugin>
            <groupId>com.jolira</groupId>
            <artifactId>onejar-maven-plugin</artifactId>
                <version>1.4.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>one-jar</goal>
                        </goals>
                    </execution>
                </executions>
        </plugin>
    </plugins>
</build>

Note 1: Configuration options is available at the project home page.

Note 2: For one reason or the other, the onejar-maven-plugin project is not published at Maven Central. However jolira.com tracks the original project and publishes it to with the groupId com.jolira.

how to configure hibernate config file for sql server

Keep the jar files under web-inf lib incase you included jar and it is not able to identify .

It worked in my case where everything was ok but it was not able to load the driver class.

Calculate row means on subset of columns

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))
  ID    Means
1  A 3.666667
2  B 4.333333
3  C 3.333333
4  D 4.666667
5  E 4.333333

How can I check if a checkbox is checked?

Try This

<script type="text/javascript">
window.onload = function () {
    var input = document.querySelector('input[type=checkbox]');

    function check() {
        if (input.checked) {
            alert("checked");
        } else {
            alert("You didn't check it.");
        }
    }
    input.onchange = check;
    check();
}
</script>

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:

SET FOREIGN_KEY_CHECKS = 0;

/* DO WHAT YOU NEED HERE */

SET FOREIGN_KEY_CHECKS = 1;

Please make sure to NOT use this on production and have a backup.

What causes a java.lang.StackOverflowError

I was having the same issue

Role.java

 @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
 Set<BusinessUnitMaster> businessUnits =new HashSet<>();

BusinessUnitMaster.java

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
        name = "BusinessUnitRoles",
        joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();

the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java

roleRepository.save(role);

for BusinessUnitMasterService.java

businessUnitMasterRepository.save(businessUnitMaster);

Not able to launch IE browser using Selenium2 (Webdriver) with Java

Before you start with Internet Explorer and Selenium Webdriver Consider these two important rules.

  • The zoom level :Should be set to default (100%) and
  • The security zone settings : Should be same for all. The security settings should be set according to your organisation permissions.

How to set this?

  • Simply go to Internet explorer, do both the stuffs manually. Thats it. No secret.
  • Do it through your code.

Method 1:

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

    capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);

    System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");

    WebDriver driver= new InternetExplorerDriver(capabilities);


    driver.get(baseURl);

    //Identify your elements and go ahead testing...

This will definetly not show any error and browser will open and also will navigate to the URL.

BUT This will not identify any element and hence you can not proceed.

Why? Because we have simly suppressed the error and asked IE to open and get that URL. However Selenium will identify elements only if the browser zoom is 100% ie. default. So the final code would be

Method 2 The robust and full proof way:

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

    capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);

    System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");

    WebDriver driver= new InternetExplorerDriver(capabilities);


    driver.get(baseURl);

    driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,"0"));

    //Identify your elements and go ahead testing...

Hope this helps. Do let me know if further information is required.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/

SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/

The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.

How to automatically select all text on focus in WPF TextBox?

I realize this is very old, but here is my solution which is based on the expressions/microsoft interactivity and interactions name spaces.

First, I followed the instructions at this link to place interactivity triggers into a style.

Then it comes down to this

<Style x:Key="baseTextBox" TargetType="TextBox">
  <Setter Property="gint:InteractivityItems.Template">
    <Setter.Value>
      <gint:InteractivityTemplate>
        <gint:InteractivityItems>
          <gint:InteractivityItems.Triggers>
            <i:EventTrigger EventName="GotKeyboardFocus">
              <ei:CallMethodAction MethodName="SelectAll"/>
            </i:EventTrigger>
            <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
              <ei:CallMethodAction MethodName="TextBox_PreviewMouseLeftButtonDown"
                TargetObject="{Binding ElementName=HostElementName}"/>
            </i:EventTrigger>
          </gint:InteractivityItems.Triggers>
        </gint:InteractivityItems>
      </gint:InteractivityTemplate>
    </Setter.Value>
  </Setter>
</Style>

and this

public void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
  TextBox tb = e.Source as TextBox;
  if((tb != null) && (tb.IsKeyboardFocusWithin == false))
  {
    tb.Focus();
    e.Handled = true;
  }
}

In my case, I have a user control where the text boxes are that has a code-behind. The code-behind has the handler function. I gave my user control a name in XAML, and I am using that name for the element. This is working perfectly for me. Simply apply the style to any TextBox where you would like to have all the text selected when you click in the TextBox.

The first CallMethodAction calls the text box's SelectAll method when the GotKeyboardFocus event on the TextBox fires.

I hope this helps.

How to know which is running in Jupyter notebook?

from platform import python_version

print(python_version())

This will give you the exact version of python running your script. eg output:

3.6.5

Bash or KornShell (ksh)?

Bash is the standard for Linux.
My experience is that it is easier to find help for bash than for ksh or csh.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

How to get the number of characters in a std::string?

std::string str("a string");
std::cout << str.size() << std::endl;

How to replace all occurrences of a string in Javascript?

In terms of performance related to the main answers these are some online tests.

While the following are some performance tests using console.time() (they work best in your own console, the time is very short to be seen in the snippet)

_x000D_
_x000D_
console.time('split and join');_x000D_
"javascript-test-find-and-replace-all".split('-').join(' ');_x000D_
console.timeEnd('split and join')_x000D_
_x000D_
console.time('regular expression');_x000D_
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');_x000D_
console.timeEnd('regular expression');_x000D_
_x000D_
console.time('while');_x000D_
let str1 = "javascript-test-find-and-replace-all";_x000D_
while (str1.indexOf('-') !== -1) {_x000D_
    str1 = str1.replace('-', ' ');_x000D_
}_x000D_
console.timeEnd('while');
_x000D_
_x000D_
_x000D_

The interesting thing to notice is that if you run them multiple time the results are always different even though the RegExp solution seems the fastest on average and the while loop solution the slowest.

how to parse JSONArray in android

Here is a better way for doing it. Hope this helps

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();
...

How can I serve static html from spring boot?

As it is written before, some folders (/META-INF/resources/, /resources/, /static/, /public/) serve static content by default, conroller misconfiguration can break this behaviour.

It is a common pitfall that people define the base url of a controller in the @RestController annotation, instead of the @RequestMapping annotation on the top of the controllers.

This is wrong:

@RestController("/api/base")
public class MyController {

    @PostMapping
    public String myPostMethod( ...) {

The above example will prevent you from opening the index.html. The Spring expects a POST method at the root, because the myPostMethod is mapped to the "/" path.

You have to use this instead:

@RestController
@RequestMapping("/api/base")
public class MyController {

    @PostMapping
    public String myPostMethod( ...) {

Where to place and how to read configuration resource files in servlet based application?

It just needs to be in the classpath (aka make sure it ends up under /WEB-INF/classes in the .war as part of the build).

Scroll event listener javascript

For those who found this question hoping to find an answer that doesn't involve jQuery, you hook into the window "scroll" event using normal event listening. Say we want to add scroll listening to a number of CSS-selector-able elements:

// what should we do when scrolling occurs
var runOnScroll =  function(evt) {
  // not the most exciting thing, but a thing nonetheless
  console.log(evt.target);
};

// grab elements as array, rather than as NodeList
var elements = document.querySelectorAll("...");
elements = Array.prototype.slice.call(elements);

// and then make each element do something on scroll
elements.forEach(function(element) {
  window.addEventListener("scroll", runOnScroll, {passive: true});
});

(Using the passive attribute to tell the browser that this event won't interfere with scrolling itself)

For bonus points, you can give the scroll handler a lock mechanism so that it doesn't run if we're already scrolling:

// global lock, so put this code in a closure of some sort so you're not polluting.
var locked = false;
var lastCall = false;

var runOnScroll =  function(evt) {
  if(locked) return;

  if (lastCall) clearTimeout(lastCall);
  lastCall = setTimeout(() => {
    runOnScroll(evt);
    // you do this because you want to handle the last
    // scroll event, even if it occurred while another
    // event was being processed.
  }, 200);

  // ...your code goes here...

  locked = false;
};

How do I load the contents of a text file into a javascript variable?

If your input was structured as XML, you could use the importXML function. (More info here at quirksmode).

If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.

Ignoring upper case and lower case in Java

The .equalsIgnoreCase() method should help with that.

How do I horizontally center an absolute positioned element inside a 100% width div?

here is the best practiced method to center a div as position absolute

DEMO FIDDLE

code --

#header {
background:black;
height:90px;
width:100%;
position:relative; // you forgot this, this is very important
}

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin: auto; // margin auto works just you need to put top left bottom right as 0
top:0;
bottom:0;
left:0;
right:0;
}

Setting the height of a SELECT in IE

There is a work-around for this (at least for multi-select):

  • set select size attribute to option list size (use JavaScript or set it to any large enough number)
  • set select max-height instead of height attribute to desired height (tested on IE9)

file_put_contents - failed to open stream: Permission denied

had the same problem; my issue was selinux was set to enforcing.

I kept getting the "failed to open stream: Permission denied" error even after chmoding to 777 and making sure all parent folders had execute permissions for the apache user. Turns out my issue was that selinux was set to enforcing (I'm on centos7), this is a devbox so I turned it off.

SQL Server ORDER BY date and nulls last

I know this is old but this is what worked for me

Order by Isnull(Date,'12/31/9999')

Install windows service without InstallUtil.exe

This Problem is due to Security, Better open Developer Command prompt for VS 2012 in RUN AS ADMINISTRATOR and install your Service, it fix your problem surely.

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

How to check if a key exists in Json Object and get its value

JSONObject root= new JSONObject();
JSONObject container= root.getJSONObject("LabelData");

try{
//if key will not be available put it in the try catch block your program 
 will work without error 
String Video=container.getString("video");
}
catch(JsonException e){

 if key will not be there then this block will execute

 } 
 if(video!=null || !video.isEmpty){
  //get Value of video
}else{
  //other vise leave it
 }

i think this might help you

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

This happens to me every time I add a pod to the podfile.

I constantly try and find the problem but I just go round in circles again and again!

The error messages range, however the way to fix it is the same every time!

Comment out(#) ALL of the pods in the podfile and run pod install in terminal.

Then...

Uncomment out all of the pods in the podfile and run pod install again.

This has worked for me every single time!

How to get the indexpath.row when an element is activated?

In Swift 3. Also used guard statements, avoiding a long chain of braces.

func buttonTapped(sender: UIButton) {
    guard let cellInAction = sender.superview as? UITableViewCell else { return }
    guard let indexPath = tableView?.indexPath(for: cellInAction) else { return }

    print(indexPath)
}

Get the last item in an array

to access the last element in array using c# we can use GetUpperBound(0)

(0) in case if this one dimention array

my_array[my_array.GetUpperBound(0)] //this is the last element in this one dim array

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

Find IP address of directly connected device

You can also get information from directly connected networking devices, such as network switches with LDWin, a portable and free Windows program published on github:

http://www.sysadmit.com/2016/11/windows-como-saber-la-ip-del-switch-al-que-estoy-conectado.html

LDWin supports the following methods of link discovery: CDP (Cisco Discovery Protocol) and LLDP (Link Layer Discovery Protocol).

You can obtain the model, management IP, VLAN identifier, Port identifier, firmware version, etc.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Android: show/hide status bar/power bar

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //hide status bar
    requestWindowFeature( Window.FEATURE_NO_TITLE );
    getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN );


    setContentView(R.layout.activity_main);
}

CSS to keep element at "fixed" position on screen

#fixedbutton {
    position: fixed;
    bottom: 0px;
    right: 0px; 
    z-index: 1000;
}

The z-index is added to overshadow any element with a greater property you might not know about.

Force index use in Oracle

If you think the performance of the query will be better using the index, how could you force the query to use the index?

First you would of course verify that the index gave a better result for returning the complete data set, right?

The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:

select /*+ index(table_name (column_having_index)) */ *
from   table_name
where  column_having_index="some value"; 

In more complex cases you might ...

select /*+ index(t (t.column_having_index)) */ *
from   my_owner.table_name t,
       ...
where  t.column_having_index="some value"; 

With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.

Set session variable in laravel

in Laravel 5.4

use this method:

Session::put('variableName', $value);

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Row names & column names in R

I think that using colnames and rownames makes the most sense; here's why.

Using names has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames whenever you use matrices. By calling colnames, you only have to remember one function. Finally, if you look at the code for colnames, you will see that it calls names in the case of a data frame anyway, so the output is identical.

rownames and row.names return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames will print "NULL" (as does colnames), but row.names returns it invisibly. Since there isn't much to choose between the two functions, rownames wins on the grounds of aesthetics, since it pairs more prettily withcolnames. (Also, for the lazy programmer, you save a character of typing.)

No line-break after a hyphen

IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.

As I could not use the CSS answer specified by Deb I instead opted to use no break tags.

<nobr>e-mail</nobr>

In addition I found a specific scenario that caused IE8/9 to break on a hyphen.

  • A string contains words separated by non-breaking spaces - &nbsp;
  • Width is limited
  • Contains a dash

IE renders it like this.

Example of hyphen breaking in IE8/9

The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta charset="utf-8"/>
        <style>
            body { padding: 20px; }
            div { width: 300px; border: 1px solid gray; }
        </style>
    </head>
    <body>
        <div>      
            <p>If&nbsp;there&nbsp;is&nbsp;a&nbsp;-&nbsp;and&nbsp;words&nbsp;are&nbsp;separated&nbsp;by&nbsp;the&nbsp;whitespace&nbsp;code&nbsp;&amp;nbsp;&nbsp;then&nbsp;IE&nbsp;will&nbsp;wrap&nbsp;on&nbsp;the&nbsp;dash.</p>
        </div>
    </body>
</html>

Adding css class through aspx code behind

If you're not using the id for anything other than code-behind reference (since .net mangles the ids), you could use a panel control and reference it in your codebehind:

<asp:panel runat="server" id="classMe"></asp:panel>

classMe.cssClass = "someClass"

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I found what I think is a faster solution. Install Git for Windows from here: http://git-scm.com/download/win

That automatically adds its path to the system variable during installation if you tell the installer to do so (it asks for that). So you don't have to edit anything manually.

Just close and restart Android Studio if it's open and you're ready to go.

wizard sample

Navigation bar show/hide

If you want to detect the status of navigation bar wether it is hidden/shown. You can simply use following code to detect -

if self.navigationController?.isNavigationBarHidden{
    print("Show navigation bar")
} else {
    print("hide navigation bar")
}

IF function with 3 conditions

=if([Logical Test 1],[Action 1],if([Logical Test 2],[Action 1],if([Logical Test 3],[Action 3],[Value if all logical tests return false])))

Replace the components in the square brackets as necessary.

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

How to add items to a combobox in a form in excel VBA?

Here is another answer:

With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With 

Source: Show the

How to print current date on python3?

import datetime
now = datetime.datetime.now()

print(now.year)

The above code works perfectly fine for me.

How to trim a file extension from a String in JavaScript?

Simple one:

var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

I know it's an old thread, but I'd like to point the possible version issue of DotNetCompilerPlatform.dll, f. ex. after an update. Please check, if the new generated Web.config file is different as your released web.config, in particular the system.codedom part. In my case it was the version change from 1.0.7 to 1.0.8. The new dll had been already copied to the server, but I didn't change the old web.config (with some server special settings):

<pre>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</pre>

After I update the two lines, the error disappeared.

adding noise to a signal in python

For those who want to add noise to a multi-dimensional dataset loaded within a pandas dataframe or even a numpy ndarray, here's an example:

import pandas as pd
# create a sample dataset with dimension (2,2)
# in your case you need to replace this with 
# clean_signal = pd.read_csv("your_data.csv")   
clean_signal = pd.DataFrame([[1,2],[3,4]], columns=list('AB'), dtype=float) 
print(clean_signal)
"""
print output: 
    A    B
0  1.0  2.0
1  3.0  4.0
"""
import numpy as np 
mu, sigma = 0, 0.1 
# creating a noise with the same dimension as the dataset (2,2) 
noise = np.random.normal(mu, sigma, [2,2]) 
print(noise)

"""
print output: 
array([[-0.11114313,  0.25927152],
       [ 0.06701506, -0.09364186]])
"""
signal = clean_signal + noise
print(signal)
"""
print output: 
          A         B
0  0.888857  2.259272
1  3.067015  3.906358
""" 

How to extract a floating number from a string

If your float is always expressed in decimal notation something like

>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")
['13.4']

may suffice.

A more robust version would be:

>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']

If you want to validate user input, you could alternatively also check for a float by stepping to it directly:

user_input = "Current Level: 1e100 db"
for token in user_input.split():
    try:
        # if this succeeds, you have your (first) float
        print float(token), "is a float"
    except ValueError:
        print token, "is something else"

# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else

How do I send a cross-domain POST request via JavaScript?

CORS is for you. CORS is "Cross Origin Resource Sharing", is a way to send cross domain request.Now the XMLHttpRequest2 and Fetch API both support CORS, and it can send both POST and GET request

But it has its limits.Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.

And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*')

For lots of request way if you don't know how to choice, I think you need a full functional component to do that.Let me introduce a simple component https://github.com/Joker-Jelly/catta


If you are using modern browser (> IE9, Chrome, FF, Edge, etc.), Very Recommend you to use a simple but beauty component https://github.com/Joker-Jelly/catta.It have no dependence, Less than 3KB, and it support Fetch, AJAX and JSONP with same deadly sample syntax and options.

catta('./data/simple.json').then(function (res) {
  console.log(res);
});

It also it support all the way to import to your project, like ES6 module, CommonJS and even <script> in HTML.

Serializing and submitting a form with jQuery and PHP

 $("#contactForm").submit(function() {

    $.post(url, $.param($(this).serializeArray()), function(data) {

    });
 });

How can I have a newline in a string in sh?

Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Seriously, echo's problems were the reason why the Unix Standardization process finally invented the printf utility, doing away with all the problems.

So to get a newline in a string:

FOO="hello
world"
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"

There! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. Everybody please use printf now and never look back.

Error: EACCES: permission denied

If you getting an error like below

Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/<PackageName>/vendor'

I suggest using the below command to install your global package

sudo npm install -g <PackageName> --unsafe-perm=true --allow-root

How to check Network port access and display useful message?

You can check if the Connected property is set to $true and display a friendly message:

    $t = New-Object Net.Sockets.TcpClient "10.45.23.109", 443 

    if($t.Connected)
    {
        "Port 443 is operational"
    }
    else
    {
        "..."
    }

OpenJDK availability for Windows OS

Red Hat announces they will distribute an OpenJDK for Windows platform: http://developers.redhat.com/blog/2016/06/27/openjdk-now-available-for-windows/

EDITED (thx to CaseyB comment): there is no PRODUCTION support on Windows. From the documentation:

All Red Hat distributions of OpenJDK 8 on Windows are supported for development of applications that work in conjunction with JBoss Middleware, so that you have the convenience and confidence to develop and test in Windows or Linux-based environments and deploy your solution to a 100% compatible, fully supported, OpenJDK 8 on Red Hat Enterprise Linux.

Clicking the back button twice to exit an activity

private static final int TIME_INTERVAL = 2000;
private long mBackPressed;
    @Override
        public void onBackPressed() {

            if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
                super.onBackPressed();
                Intent intent = new Intent(FirstpageActivity.this,
                        HomepageActivity.class);
                startActivity(intent);
                finish();

                return;
            } else {

                Toast.makeText(getBaseContext(),
                        "Tap back button twice  to go Home.", Toast.LENGTH_SHORT)
                        .show();

                mBackPressed = System.currentTimeMillis();

            }

        }

how can I Update top 100 records in sql server

Note, the parentheses are required for UPDATE statements:

update top (100) table1 set field1 = 1