Programs & Examples On #Video

Video is an electronic medium for the recording, copying, and broadcasting of moving visual images. Use more specific tags when relevant, such as [video-editing] for questions related to trimming and modifying videos, [video-encoding] for questions related to editing videos into any format, and [video-processing] for questions related to processing videos with filtering video frames.

YouTube URL in Video Tag

Try this solution for the perfectly working

new YouTubeToHtml5();

What are all codecs and formats supported by FFmpeg?

Codecs proper:

ffmpeg -codecs

Formats:

ffmpeg -formats

How to play YouTube video in my Android application?

Google has a YouTube Android Player API that enables you to incorporate video playback functionality into your Android applications. The API itself is very easy to use and works well. For example, here is how to create a new activity to play a video using the API.

Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, "<<YOUTUBE_API_KEY>>", "<<Youtube Video ID>>", 0, true, false);   
startActivity(intent);

See this for more details.

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

I created https://yt-embed.herokuapp.com/ to simplify this. The usage is direct, from the examples above:

[![Everything Is AWESOME](https://yt-embed.herokuapp.com/embed?v=StTqXEQ2l-Y)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

Will result in: example of usage of yt-embed

Just make a call to: https://yt-embed.herokuapp.com/embed?v=[video_id] as the image instead of https://img.youtube.com/vi/.

Qt jpg image display

I want to display .jpg image in an Qt UI

The simpliest way is to use QLabel for this:

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QLabel label("<img src='image.jpg' />");
    label.show();
    return a.exec();
}

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

How can I record a Video in my Android App.?

You record audio and video using the same MediaRecorder class. It's pretty simple. Here's an example.

Disable html5 video autoplay

Try adding autostart="false" to your source tag.

<video width="640" height="480" controls="controls" type="video/mp4" preload="none">
<source src="http://example.com/mytestfile.mp4" autostart="false">
Your browser does not support the video tag.
</video>

JSFiddle example

Streaming video from Android camera to server

Depending by your budget, you can use a Raspberry Pi Camera that can send images to a server. I add here two tutorials where you can find many more details:

This tutorial show you how to use a Raspberry Pi Camera and display images on Android device

This is the second tutorial where you can find a series of tutorial about real-time video streaming between camera and android device

Is there a way to make HTML5 video fullscreen?

You can do this if you tell to user to press F11(full screen for many browsers), and you put video on entire body of page.

Clicking HTML 5 Video element to play, pause video, breaks play button

How about this one

<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
   <source src="" type="video/mp4">
</video>

How to play videos in android from assets folder or raw folder?

If I remember well, I had the same kind of issue when loading stuff from the asset folder but with a database. It seems that the stuff in your asset folder can have 2 stats : compressed or not.
If it is compressed, then you are allowed 1 Mo of memory to uncompress it, otherwise you will get this kind of exception. There are several bug reports about that because the documentation is not clear. So if you still want to to use your format, you have to either use an uncompressed version, or give an extension like .mp3 or .png to your file. I know it's a bit crazy but I load a database with a .mp3 extension and it works perfectly fine. This other solution is to package your application with a special option to tell it not to compress certain extension. But then you need to build your app manually and add "zip -0" option.
The advantage of an uncompressed assest is that the phase of zip-align before publication of an application will align the data correctly so that when loaded in memory it can be directly mapped.

So, solutions :

  • change the extension of the file to .mp3 or .png and see if it works
  • build your app manually and use the zip-0 option

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

I see in the documentation page an example like this:

<source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">

Maybe you should enclose the codec information with &quot; entities instead of actual quotes and the type attribute with quotes instead of apostrophes.

You can also try removing the codec info altogether.

Fetch frame count with ffmpeg

You can use ffprobe to get frame number with the following commands

  1. first method

ffprobe.exe -i video_name -print_format json -loglevel fatal -show_streams -count_frames -select_streams v

which tell to print data in json format

select_streams v will tell ffprobe to just give us video stream data and if you remove it, it will give you audio information as well

and the output will be like

{
    "streams": [
        {
            "index": 0,
            "codec_name": "mpeg4",
            "codec_long_name": "MPEG-4 part 2",
            "profile": "Simple Profile",
            "codec_type": "video",
            "codec_time_base": "1/25",
            "codec_tag_string": "mp4v",
            "codec_tag": "0x7634706d",
            "width": 640,
            "height": 480,
            "coded_width": 640,
            "coded_height": 480,
            "has_b_frames": 1,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "4:3",
            "pix_fmt": "yuv420p",
            "level": 1,
            "chroma_location": "left",
            "refs": 1,
            "quarter_sample": "0",
            "divx_packed": "0",
            "r_frame_rate": "10/1",
            "avg_frame_rate": "10/1",
            "time_base": "1/3000",
            "start_pts": 0,
            "start_time": "0:00:00.000000",
            "duration_ts": 256500,
            "duration": "0:01:25.500000",
            "bit_rate": "261.816000 Kbit/s",
            "nb_frames": "855",
            "nb_read_frames": "855",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0
            },
            "tags": {
                "creation_time": "2005-10-17 22:54:33",
                "language": "eng",
                "handler_name": "Apple Video Media Handler",
                "encoder": "3ivx D4 4.5.1"
            }
        }
    ]
}

2. you can use

ffprobe -v error -show_format -show_streams video_name

which will give you stream data, if you want selected information like frame rate, use the following command

ffprobe -v error -select_streams v:0 -show_entries stream=avg_frame_rate -of default=noprint_wrappers=1:nokey=1 video_name

which give a number base on your video information, the problem is when you use this method, its possible you get a N/A as output.

for more information check this page FFProbe Tips

Writing an mp4 video using python opencv

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

'mp4v' returns no errors unlike 'MP4V' which is defined inside fourcc

for the error "OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???'"

Programmatically generate video or animated GIF in Python?

As of June 2009 the originally cited blog post has a method to create animated GIFs in the comments. Download the script images2gif.py (formerly images2gif.py, update courtesy of @geographika).

Then, to reverse the frames in a gif, for instance:

#!/usr/bin/env python

from PIL import Image, ImageSequence
import sys, os
filename = sys.argv[1]
im = Image.open(filename)
original_duration = im.info['duration']
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]    
frames.reverse()

from images2gif import writeGif
writeGif("reverse_" + os.path.basename(filename), frames, duration=original_duration/1000.0, dither=0)

Using ffmpeg to encode a high quality video

Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH

Does HTML5 <video> playback support the .avi format?

There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.

Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.

Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

Android intent for playing video?

Use setDataAndType on the Intent

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);

Use "video/mp4" as MIME or use "video/*" if you don't know the type.

Cutting the videos based on start and end time using ffmpeg

Use -to instead of -t: -to specifies the end time, -t specifies the duration

How to make a movie out of images in python

Thanks , but i found an alternative solution using ffmpeg:

def save():
    os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")

But thank you for your help :)

YouTube embedded video: set different thumbnail

There's a nice workaround for this in the sitepoint forums:

<div onclick="this.nextElementSibling.style.display='block'; this.style.display='none'">
   <img src="my_thumbnail.png" style="cursor:pointer" />
</div>
<div style="display:none">
    <!-- Embed code here -->
</div>

Note: To prevent having to click twice to make the video play, use autoplay=1 in the video embed code. It will start playing when the second div is displayed.

Live Video Streaming with PHP

PHP/AJAX/MySQL will not be enough for creating the live video streaming application There is a similar thread here. It primarily suggests using Flex or Silverlight.

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

HTML5 Video not working in IE 11

Although MP4 is supported in Internet explorer it does matter how you encode the file. Make sure you use BASELINE encoding when rendering the video file. This Fixed my issue with IE11

How to add a new audio (not mixing) into a video using ffmpeg?

Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:

ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4

How do I find the date a video (.AVI .MP4) was actually recorded?

For me the mtime (modification time) is also earlier than the create date in a lot of (most) cases since, as you say, any reorganisation modifies the create time. However, the mtime AFAIUI is an accurate reflection of when the file contents were actually changed so should be an accurate record of video capture date.

After discovering this metadata failure for movie files, I am going to be renaming my videos based on their mtime so I have this stored in a more robust way!

How to playback MKV video in web browser?

HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:

DivX Web Player (NPAPI browsers only)

AC3 Audio Decoder

And here is the HTML:

<embed id="divxplayer" type="video/divx" width="1024" height="768" 
src ="path_to_file" autoPlay=\"true\" 
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>

The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.

How can I stream webcam video with C#?

You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

In iOS 10+

Apple enabled the attribute playsinline in all browsers on iOS 10, so this works seamlessly:

<video src="file.mp4" playsinline>

In iOS 8 and iOS 9

Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.

Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()'ing it.

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

How to disable auto-play for local video in iframe

Replace the iframe for this:

<video class="video-fluid z-depth-1" loop controls muted>
  <source src="videos/example.mp4" type="video/mp4" />
</video>

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

Use this:

import cv2
cap = cv2.VideoCapture('path to video file')
count = 0
while cap.isOpened():
    ret,frame = cap.read()
    cv2.imshow('window-name', frame)
    cv2.imwrite("frame%d.jpg" % count, frame)
    count = count + 1
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows() # destroy all opened windows

Convert a video to MP4 (H.264/AAC) with ffmpeg

You can also try adding the Motumedia PPA to your apt sources and update your ffmpeg packages.

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

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

How can I autoplay a video using the new embed code style for Youtube?

You are using a wrong url for youtube auto play http://www.youtube.com/embed/JW5meKfy3fY&autoplay=1 this url display youtube id as wholeJW5meKfy3fY&autoplay=1 which youtube rejects to play. we have to pass autoplay variable to youtube, therefore you have to use ? instead of & so your url will be http://www.youtube.com/embed/JW5meKfy3fY?autoplay=1 and your final iframe will be like that.

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>

Using FFmpeg in .net?

The original question is now more than 5 years old. In the meantime there is now a solution for a WinRT solution from ffmpeg and an integration sample from Microsoft.

Download TS files from video stream

While this shouldn't have ever been asked on SO and got through the vetting processing in the first place, I have no idea... but I'm giving my answer anyway.

After exploring basically all of the options presented here, it turns out the simplest is often the best.

First download ffmpeg from: https://evermeet.cx/ffmpeg/

Next, after you have got your .m3u8 playlist file (most probably from the webpage source or network traffic), run this command:

ffmpeg -i "http://host/folder/file.m3u8" -bsf:a aac_adtstoasc -vcodec copy -c copy -crf 50 file.mp4

I tried running it from a locally saved m4u8 file, and it didn't work, because the ffmpeg download procedure downloads the chunks which are relative to the URL, so make sure you use the website url.

How to embed YouTube videos in PHP?

Use a regex to extract the "video id" after watch?v=

Store the video id in a variable, let's call this variable vid

Get the embed code from a random video, remove the video id from the embed code and replace it with the vid you got.

I don't know how to deal with regex in php, but it shouldn't be too hard

Here's example code in python:

>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>

The regular expression v\=([\-\w]+) captures a (sub)string of characters and dashes that comes after v=

youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

html5: display video inside canvas

Here's a solution that uses more modern syntax and is less verbose than the ones already provided:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const video = document.querySelector("video");

video.addEventListener('play', () => {
  function step() {
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
    requestAnimationFrame(step)
  }
  requestAnimationFrame(step);
})

Some useful links:

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

How do we download a blob url video

This is how I manage to "download" it:

  1. Use inspect-element to identify the URL of the M3U playlist file
  2. Download the M3U file
  3. Use VLC to read the M3U file, stream and convert the video to MP4

In Firefox the M3U file appeared as of type application/vnd.apple.mpegurl

enter image description here

The contents of the M3U file would look like:

Open VLC medial player and use the Media => Convert option. Use your (saved) M3U file as the source:

enter image description here

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

How to embed new Youtube's live video permanent URL?

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
            </iframe>
        </div>
    </div>
</div>

Tweak however you'd like!

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

How can I extract a good quality JPEG image from a video file with ffmpeg?

Output the images in a lossless format such as PNG:

ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png

Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).

I have since found that -vsync 0 is simpler than -r 10 because it avoids needing to know the frame rate.

This is something like what I currently use:

mkdir stills
ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

To extract only the key frames (which are likely to be of higher quality post-edit):

ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png

Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.

It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1 and outputting as JPEG directly from ffmpeg.

changing source on html5 video tag

Using JavaScript and jQuery:

<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
    $("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

Android video streaming example

I had the same problem but finally I found the way.

Here is the walk through:

1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)

2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.

3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:

:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}

NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...

NOTE: You can see, the video codec is MP4V which is supported by android.

4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:

mVideoView = (VideoView) findViewById(R.id.surface_view);

mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));

5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...

Question: Anybody know how to reduce buffering time and play video almost live ?

HTML 5 video or audio playlist

Yep, you can simply point your src tag to a .m3u playlist file. A .m3u file is easy to construct -

#hosted mp3's need absolute paths but file system links can use relative paths
http://servername.com/path/to/mp3.mp3
http://servername.com/path/to/anothermp3.mp3
/path/to/local-mp3.mp3

-----UPDATE-----

Well, it turns out playlist m3u files are supported on the iPhone, but not on much else including Safari 5 which is kind of sad. I'm not sure about Android phones but I doubt they support it either since Chrome doesn't. Sorry for the misinformation.

How to change the playing speed of videos in HTML5?

You can use this code:

var vid = document.getElementById("video1");

function slowPlaySpeed() { 
    vid.playbackRate = 0.5;
} 

function normalPlaySpeed() { 
    vid.playbackRate = 1;
} 

function fastPlaySpeed() { 
    vid.playbackRate = 2;
}

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

How do you change video src using jQuery?

This is working on Flowplayer 6.0.2.

<script>
    flowplayer().load({
         sources: [
            { type: "video/mp4",  src: variable }
            ]
        });
</script>

where variable is a javascript/jquery variable value, The video tag should be something this

<div class="flowplayer">
   <video>
      <source type="video/mp4" src="" class="videomp4">
   </video>
</div>

Hope it helps anyone.

Fastest way to extract frames using ffmpeg?

I tried it. 3600 frame in 32 seconds. your method is really slow. You should try this.

ffmpeg -i file.mpg -s 240x135 -vf fps=1 %d.jpg

TCP vs UDP on video stream

While reading the TCP UDP debate I noticed a logical flaw. A TCP packet loss causing a one minute delay that's converted into a one minute buffer cant be correlated to UDP dropping a full minute while experiencing the same loss. A more fair comparison is as follows.

TCP experiences a packet loss. The video is stopped while TCP resend's packets in an attempt to stream mathematically perfect packets. Video is delayed for one minute and picks up where it left off after missing packet makes its destination. We all wait but we know we wont miss a single pixel.

UDP experiences a packet loss. For a second during the video stream a corner of the screen gets a little blurry. No one notices and the show goes on without looking for the lost packets.

Anything that streams gains the most benefits from UDP. The packet loss causing a one minute delay to TCP would not cause a one minute delay to UDP. Considering that most systems use multiple resolution streams making things go blocky when starving for packets, makes even more sense to use UDP.

UDP FTW when streaming.

Detect if HTML5 Video element is playing

I just did it very simply using onpause and onplay properties of the html video tag. Create some javascript function to toggle a global variable so that the page knows the status of the video for other functions.

Javascript below:

   // onPause function
   function videoPause() {
      videoPlaying = 0;
   }

   // onPause function
   function videoPlay() {
      videoPlaying = 1;
   }

Html video tag:

<video id="mainVideo" width="660" controls onplay="videoPlay();" onpause="videoPause();" >
                             <source src="video/myvideo.mp4" type="video/mp4">

                            </video>

than you can use onclick javascript to do something depending on the status variable in this case videoPlaying.

hope this helps...

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

Chrome needs a user interaction for the video to be autoplayed or played via js (video.play()). But the interaction can be of any kind, in any moment. If you just click random on the page, the video will autoplay. I resolved then, adding a button (only on chrome browsers) that says "enable video autoplay". The button does nothing, but just clicking it, is the required user interaction for any further video.

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

Force HTML5 youtube video

I've found the solution :

You have to add the html5=1 in the src attribute of the iframe :

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>

The video will be displayed as HTML5 if available, or fallback into flash player.

How to center HTML5 Videos?

I found this page while trying to center align a pair of videos. So, if I enclose both videos in a center div (which I've called central), the margin trick works, but the width is important (2 videos at 400 + padding etc)

<div class=central>
    <video id="vid1" width="400" controls>
        <source src="Carnival01.mp4" type="video/mp4">
    </video> 

    <video id="vid2" width="400" controls>
        <source src="Carnival02.mp4" type="video/mp4">
    </video>
</div>

<style>
div.central { 
  margin: 0 auto;
  width: 880px; <!--this value must be larger than both videos + padding etc-->
}
</style>

Worked for me!

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>

WebView and HTML5 <video>

A-M's is similar to what the BrowerActivity does. for FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams (768, 512);

I think we can use

FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.FILL_PARENT) 

instead.

Another issue I met is if the video is playing, and user clicks the back button, next time, you go to this activity(singleTop one) and can not play the video. to fix this, I called the

try { 
    mCustomVideoView.stopPlayback();  
    mCustomViewCallback.onCustomViewHidden();
} catch(Throwable e) { //ignore }

in the activity's onBackPressed method.

Streaming via RTSP or RTP in HTML5

Technically 'Yes'

(but not really...)

HTML 5's <video> tag is protocol agnostic—it does not care. You place the protocol in the src attribute as part of the URL. E.g.:

<video src="rtp://myserver.com/path/to/stream">
    Your browser does not support the VIDEO tag and/or RTP streams.
</video>

or maybe

<video src="http://myserver.com:1935/path/to/stream/myPlaylist.m3u8">
    Your browser does not support the VIDEO tag and/or RTP streams.
</video>

That said, the implementation of the <video> tag is browser specific. Since it is early days for HTML 5, I expect frequently changing support (or lack of support).

From the W3C's HTML5 spec (The video element):

User agents may support any video and audio codecs and container formats

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How to prevent downloading images and video files from my website?

Don't post them to your site.

Otherwise it is not possible.

Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
etc...

Options are:

Code for 1440: vq=hd1440
Code for 1080: vq=hd1080
Code for 720: vq=hd720
Code for 480p: vq=large
Code for 360p: vq=medium
Code for 240p: vq=small

UPDATE
As of 10 of April 2018, this code still works.
Some users reported "not working", if it doesn't work for you, please read below:

From what I've learned, the problem is related with network speed and or screen size.
When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=), a lower quality video is displayed despite the option selected on vq=.

Also make sure you read the comments below.

H.264 file size for 1 hr of HD video

It really depends on many settings, on both the audio and video side of things. If you follow the compression-settings of this video, then it's approximately 3GB per hour. If you have a Mac, I would definitely recommend using 'Compressor' as it is fairly easy to use and works flawless.

As far as storage is concerned, if you're looking at 100hrs / 300GB, I would definitely go with an external hard drive. Video files are so huge, that they (even if they don't totally fill up your hard disk) really do confuse your computer. Make sure to make some time for compressing the whole thing because it takes hours and hours and hours.... for 100 hrs worth of footage, it'll take days.

HTML5 Video Autoplay not working correctly

_x000D_
_x000D_
html {_x000D_
  padding: 20px 0;_x000D_
  background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
  width: 400px;_x000D_
  padding: 40px;_x000D_
  margin: 0 auto;_x000D_
  background: #fff;_x000D_
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
  width: 400px;_x000D_
  display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
    Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
_x000D_
_x000D_

Live-stream video from one android phone to another over WiFi

If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.

If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).

Quick sample code for the server:

// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();

On the player side it is a bit tricky, you could try this:

// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();

Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.

See also:

Stream live video from phone to phone using socket fd

MediaPlayer stutters at start of mp3 playback

Reducing video size with same format and reducing frame size

Instead of chosing fixed bit rates, with the H.264 codec, you can also chose a different preset as described at https://trac.ffmpeg.org/wiki/x264EncodingGuide. I also found Video encoder comparison at KeyJ's blog (archived version) an interesting read, it compares H.264 against Theora and others.

Following is a comparison of various options I tried. The recorded video was originally 673M in size, taken on an iPad using RecordMyScreen. It has a duration of about 20 minutes with a resolution of 1024x768 (with half of the video being blank, so I cropped it to 768x768). In order to reduce size, I lowered the resolution to 480x480. There is no audio.

The results, taking the same 1024x768 as base (and applying cropping, scaling and a filter):

  • With no special options: 95M (encoding time: 1m19s).
  • With only -b 512k added, the size dropped to 77M (encoding time: 1m17s).
  • With only -preset veryslow (and no -b), it became 70M (encoding time: 6m14s)
  • With both -b 512k and -preset veryslow, the size becomes 77M (100K smaller than just -b 512k).
  • With -preset veryslow -crf 28, I get a file of 39M which took 5m47s (with no visual quality difference to me).

N=1, so take the results with a grain of salt and perform your own tests.

Correct mime type for .mp4

When uploading .mp4 file into Perl script, using CGI.pm I see it as video/mp when printing out Content-type for the uploaded file. I hope it will help someone.

video as site background? HTML 5

I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):

Put the video right after the body-tag with style="width:100%;". Right afterwords, put a "bodydummy"-tag:

<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
    <source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
    <source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
    <source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>    
</video>

<img id="bgImg" src="videos/poster.png" />

<!-- This image stretches exactly to the browser width/height and lies behind the video-->

<div id="bodyDummy">

Put all your content inside the bodydummy-div and put the z-indexes correctly in CSS like this:

#bgImg{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
}

#bgVideo{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
}

#bodyDummy{ 
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    overflow: auto;
    width: 100%;
    height: 100%;
}

Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.

HTML5 Video // Completely Hide Controls

There are two ways to hide video tag controls

  1. Remove the controls attribute from the video tag.

  2. Add the css to the video tag

    video::-webkit-media-controls-panel {
    display: none !important;
    opacity: 1 !important;}
    

HTML5 <video> element on Android

pointing my android 2.2 browser to html5test.com, tells me that the video element is supported, but none of the listed video codecs... seems a little pointless to support the video element but no codecs??? unless there is something wrong with that test page.

however, i did find the same kind of situation with the audio element: the element is supported, but no audio formats. see here:

http://textopiablog.wordpress.com/2010/06/25/browser-support-for-html5-audio/

Bootstrap 3 - Responsive mp4-video

This worked for me:

<video src="file.mp4" controls style="max-width:100%; height:auto"></video>

What's the difference between JavaScript and JScript?

Just different names for what is really ECMAScript. John Resig has a good explanation.

Here's the full version breakdown:

  • IE 6-7 support JScript 5 (which is equivalent to ECMAScript 3, JavaScript 1.5)
  • IE 8 supports JScript 6 (which is equivalent to ECMAScript 3, JavaScript 1.5 - more bug fixes over JScript 5)
  • Firefox 1.0 supports JavaScript 1.5 (ECMAScript 3 equivalent)
  • Firefox 1.5 supports JavaScript 1.6 (1.5 + Array Extras + E4X + misc.)
  • Firefox 2.0 supports JavaScript 1.7 (1.6 + Generator + Iterators + let + misc.)
  • Firefox 3.0 supports JavaScript 1.8 (1.7 + Generator Expressions + Expression Closures + misc.)
  • The next version of Firefox will support JavaScript 1.9 (1.8 + To be determined)
  • Opera supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.
  • Safari supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.

How to remove special characters from a string?

That depends on what you define as special characters, but try replaceAll(...):

String result = yourString.replaceAll("[-+.^:,]","");

Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".

Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).

So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):

String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");


If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").

A third way could be something like this, if you can exactly define what should be left in your string:

String  result = yourString.replaceAll("[^\\w\\s]","");

This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.

Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.

Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:

String  result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");

The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.

Additional information on Unicode

Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.

jQuery validation: change default error message

I never thought this would be so easy , I was working on a project to handle such validation.

The below answer will of great help to one who want to change validation message without much effort.

The below approaches uses the "Placeholder name" in place of "This Field".

You can easily modify things

   // Jquery Validation   
   $('.js-validation').each(function(){

       //Validation Error Messages 

       var validationObjectArray = [];

       var validationMessages = {};

       $(this).find('input,select').each(function(){  // add more type hear

          var singleElementMessages = {};

          var fieldName = $(this).attr('name');

          if(!fieldName){  //field Name is not defined continue ;
              return true;
          }


          // If attr data-error-field-name is given give it a priority , and then to placeholder and lastly a simple text

          var fieldPlaceholderName = $(this).data('error-field-name') || $(this).attr('placeholder') || "This Field";

          if( $( this ).prop( 'required' )){

              singleElementMessages['required'] = $(this).data('error-required-message') || $(this).data('error-message')  || fieldPlaceholderName + " is required";

          }

          if( $( this ).attr( 'type' ) == 'email' ){

              singleElementMessages['email'] = $(this).data('error-email-message') || $(this).data('error-message')  || "Enter valid email in "+fieldPlaceholderName;

          }       



          validationMessages[fieldName] = singleElementMessages;

       });


       $(this).validate({
          errorClass   : "error-message",
          errorElement : "div",
          messages     : validationMessages  
       });  
   });  

How to install mod_ssl for Apache httpd?

I found I needed to enable the SSL module in Apache (obviously prefix commands with sudo if you are not running as root):

a2enmod ssl

then restart Apache:

/etc/init.d/apache2 restart

More details of SSL in Apache for Ubuntu / Debian here.

Tomcat starts but home page cannot open with url http://localhost:8080

In my case, the port that tomcat was running on was defined in an application.properties file for 8000, not 8080. In my case, it looked like the same problem described here. Just leaving this here in case anyone has a similar setup and issue! :)

How to copy a row from one SQL Server table to another

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

How do I compare strings in GoLang?

== is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString do not contain "a", but "a\n" (if you look closely, you'll see the extra line break in your example output).

You can use the strings.TrimRight function to remove trailing whitespaces from your input:

if strings.TrimRight(input, "\n") == "a" {
    // ...
}

how to realize countifs function (excel) in R

library(matrixStats)
> data <- rbind(c("M", "F", "M"), c("Student", "Analyst", "Analyst"))
> rowCounts(data, value = 'M') # output = 2 0
> rowCounts(data, value = 'F') # output = 1 0

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

I've heard this doesn't always work on the designer, but it compiles fine.

Installing Java 7 on Ubuntu

Oracle Java 1.7.0 from .deb packages

wget https://raw.github.com/flexiondotorg/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source 
sudo apt-get dist-upgrade

Workaround for 1.7.0_51

There is an Issue 123 currently in OAB and a pull request

Here is the patched vesion:

wget https://raw.github.com/ladios/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source 
sudo apt-get dist-upgrade

jquery toggle slide from left to right and back

Use this...

$('#cat_icon').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').hide();
});
$('.panel_title').click(function () {
    $('#categories').toggle("slow");
    //$('#cat_icon').show();
});

See this Example

Greetings.

How to resolve git stash conflict without commit?

Don't follow other answers

Well, you can follow them :). But I don't think that doing a commit and then resetting the branch to remove that commit and similar workarounds suggested in other answers are the clean way to solve this issue.

Clean solution

The following solution seems to be much cleaner to me and it's also suggested by the Git itself — try to execute git status in the repository with a conflict:

Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

So let's do what Git suggests (without doing any useless commits):

  1. Manually (or using some merge tool, see below) resolve the conflict(s).
  2. Use git reset to mark conflict(s) as resolved and unstage the changes. You can execute it without any parameters and Git will remove everything from the index. You don't have to execute git add before.
  3. Finally, remove the stash with git stash drop, because Git doesn't do that on conflict.

Translated to the command-line:

$ git stash pop

# ...resolve conflict(s)

$ git reset

$ git stash drop

Explanation of the default behavior

There are two ways of marking conflicts as resolved: git add and git reset. While git reset marks the conflicts as resolved and removes files from the index, git add also marks the conflicts as resolved, but keeps files in the index.

Adding files to the index after a conflict is resolved is on purpose. This way you can differentiate the changes from the previous stash and changes you made after the conflict was resolved. If you don't like it, you can always use git reset to remove everything from the index.

Merge tools

I highly recommend using any of 3-way merge tools for resolving conflicts, e.g. KDiff3, Meld, etc., instead of doing it manually. It usually solves all or majority of conflicts automatically itself. It's huge time-saver!

Laravel 5 Carbon format datetime

Try that:

$createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
$createdAt= $createdAt->format('M d Y');

Unexpected character encountered while parsing value

I experienced the same error in my Xamarin.Android solution.

I verified that my JSON was correct, and noticed that the error only appeared when I ran the app as a Release build.

It turned out that the Linker was removing a library from Newtonsoft.JSON, causing the JSON to be parsed incorrectly.

I fixed the error by adding Newtonsoft.Json to the Ignore assemblies setting in the Android Build Configuration (screen shot below)

JSON Parsing Code

static readonly JsonSerializer _serializer = new JsonSerializer();
static readonly HttpClient _client = new HttpClient();

static async Task<T> GetDataObjectFromAPI<T>(string apiUrl)
{
    using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
    using (var reader = new StreamReader(stream))
    using (var json = new JsonTextReader(reader))
    {
        if (json == null)
            return default(T);

        return _serializer.Deserialize<T>(json);
    }
}

Visual Studio Mac Screenshot

enter image description here

Visual Studio Screenshot

enter image description here

How to use comparison and ' if not' in python?

There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:

if not ((u0 <= u) and (u < u0+step)):

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.

For an array:

var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();

As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.

But as we all know JavaScript is strange, so here are some weird bits:

array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!

This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.

So what are Objects?

Objects in JavaScript are just like arrays but the "index" can be any string.

var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK

You can even opt to not use the square brackets when working with objects!

console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";

You can go even further and define objects like so:

var newObject = {
    a: 2,
};
newObject.a === 2; // true

Insertion Sort vs. Selection Sort

Both insertion sort and selection sort has an sorted list at the front, and unsorted list at the end, and what the algorithm does is also similar:

  1. Take an element from the unsorted list
  2. Put it into the sorted list

The difference is:

  • Insertion sort take the first element of the unsorted list, and then do compare and swap in the sorted list to make sure the element goes to the right position, the effort is mostly in step #2 for insertion
auto insertion_sort(vector<int>& vs)
{
  for(int i=1; i < vs.size(); ++i)
  {
    for(int j=i; j > 0; --j)
    {
      if(vs[j] < vs[j-1]) swap(vs[j], vs[j-1]);
    }
  }
  return vs;
}
  • Selection sort compare and mark the smallest element of the unsorted list, and then swap it with the first element of the unsorted list, actually include this element as part of the sorted list - the effort is mostly in step #1 for selection
auto selection_sort(vector<int>& vs)
{
  for(int i = 0; i < vs.size(); ++i)
  {
    int iMin = i;
    for(int j=i; j < vs.size(); ++j)
    {
      if(vs[j] < vs[iMin]) iMin = j;
    }
    swap(vs[i], vs[iMin]);
  }
  return vs;
}

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

C# Test if user has write access to a folder

I faced the same problem: how to verify if I can read/write in a particular directory. I ended up with the easy solution to...actually test it. Here is my simple though effective solution.

 class Program
{

    /// <summary>
    /// Tests if can read files and if any are present
    /// </summary>
    /// <param name="dirPath"></param>
    /// <returns></returns>
    private genericResponse check_canRead(string dirPath)
    {
        try
        {
            IEnumerable<string> files = Directory.EnumerateFiles(dirPath);
            if (files.Count().Equals(0))
                return new genericResponse() { status = true, idMsg = genericResponseType.NothingToRead };

            return new genericResponse() { status = true, idMsg = genericResponseType.OK };
        }
        catch (DirectoryNotFoundException ex)
        {

            return new genericResponse() { status = false, idMsg = genericResponseType.ItemNotFound };

        }
        catch (UnauthorizedAccessException ex)
        {

            return new genericResponse() { status = false, idMsg = genericResponseType.CannotRead };

        }

    }

    /// <summary>
    /// Tests if can wirte both files or Directory
    /// </summary>
    /// <param name="dirPath"></param>
    /// <returns></returns>
    private genericResponse check_canWrite(string dirPath)
    {

        try
        {
            string testDir = "__TESTDIR__";
            Directory.CreateDirectory(string.Join("/", dirPath, testDir));

            Directory.Delete(string.Join("/", dirPath, testDir));


            string testFile = "__TESTFILE__.txt";
            try
            {
                TextWriter tw = new StreamWriter(string.Join("/", dirPath, testFile), false);
                tw.WriteLine(testFile);
                tw.Close();
                File.Delete(string.Join("/", dirPath, testFile));

                return new genericResponse() { status = true, idMsg = genericResponseType.OK };
            }
            catch (UnauthorizedAccessException ex)
            {

                return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteFile };

            }


        }
        catch (UnauthorizedAccessException ex)
        {

            return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteDir };

        }
    }


}

public class genericResponse
{

    public bool status { get; set; }
    public genericResponseType idMsg { get; set; }
    public string msg { get; set; }

}

public enum genericResponseType
{

    NothingToRead = 1,
    OK = 0,
    CannotRead = -1,
    CannotWriteDir = -2,
    CannotWriteFile = -3,
    ItemNotFound = -4

}

Hope it helps !

clear cache of browser by command line

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

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

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

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

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


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

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


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

pause

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

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

don't fail jenkins build if execute shell fails

This answer is correct, but it doesn't specify the || exit 0 or || true goes inside the shell command. Here's a more complete example:

sh "adb uninstall com.example.app || true"

The above will work, but the following will fail:

sh "adb uninstall com.example.app" || true

Perhaps it's obvious to others, but I wasted a lot of time before I realized this.

How to use underscore.js as a template engine?

Everything you need to know about underscore template is here. Only 3 things to keep in mind:

  1. <% %> - to execute some code
  2. <%= %> - to print some value in template
  3. <%- %> - to print some values HTML escaped

That's all about it.

Simple example:

var tpl = _.template("<h1>Some text: <%= foo %></h1>");

then tpl({foo: "blahblah"}) would be rendered to the string <h1>Some text: blahblah</h1>

Eclipse: The declared package does not match the expected package

The only thing that worked for me is deleting the project and then importing it again. Works like a charm :)

What is the difference between an annotated and unannotated tag?

TL;DR

The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

More About Lightweight Tags

According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

  • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
  • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
  • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
  • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

PHP Remove elements from associative array

You can use this

unset($dataArray['key']);

Check if current date is between two dates Oracle SQL

TSQL: Dates- need to look for gaps in dates between Two Date

select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1 
   join #temp e3 on e1.enddate < e3.startdate          
       /* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select *  /* Eliminates e1 rows if it is overlapped */
from #temp e5 
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);

CSS table-cell equal width

Replace

  <div style="display:table;">
    <div style="display:table-cell;"></div>
    <div style="display:table-cell;"></div>
  </div>

with

  <table>
    <tr><td>content cell1</td></tr>
    <tr><td>content cell1</td></tr>
  </table>

Look at all the issues surrounding trying to make divs perform like tables. They had to add table-xxx to mimic table layouts

Tables are supported and work very well in all browsers. Why ditch them? the fact that they had to mimic them is proof they did their job and well.

In my opinion use the best tool for the job and if you want tabulated data or something that resembles tabulated data tables just work.

Very Late reply I know but worth voicing.

How to extract base URL from a string in JavaScript?

var host = location.protocol + '//' + location.host + '/';

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Here's where it gets confusing, the text states "If the balance factor of R is 1, it means the insertion occurred on the (external) right side of that node and a left rotation is needed". But from m understanding the text said (as I quoted) that if the balance factor was within [-1, 1] then there was no need for balancing?

R is the right-hand child of the current node N.

If balance(N) = +2, then you need a rotation of some sort. But which rotation to use? Well, it depends on balance(R): if balance(R) = +1 then you need a left-rotation on N; but if balance(R) = -1 then you will need a double-rotation of some sort.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I know this an old Question but i feel this might help someone. I was recently faced with the same problem but in my case, i remember my password quite alright but it kept on giving me the same error. I tried so many solutions but still none helped then i tried this

mysql -u root -p 

after which it asks you for a pass word like this

Enter password: 

and then i typed in the password i used. That's all

Get integer value from string in swift

I wrote an extension for that purpose. It always returns an Int. If the string does not fit into an Int, 0 is returned.

extension String {
    func toTypeSafeInt() -> Int {
        if let safeInt = self.toInt() {
            return safeInt
        } else {
            return 0
        }
    }
}

How best to read a File into List<string>

//this is only good in .NET 4
//read your file:
List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();

//manipulate data here
foreach(string line in ReadFile)
{
    //do something here
}

//write back to your file:
File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I also faced this issue. I was having JDK 1.8.0_121. I upgraded JDK to 1.8.0_181 and it worked like a charm.

Word-wrap in an HTML table

The answer that won the bounty is correct, but it doesn't work if the first row of the table has a merged/joined cell (all the cells get equal width).

In this case you should use the colgroup and col tags to display it properly:

<table style="table-layout: fixed; width: 200px">
<colgroup>
    <col style="width: 30%;">
    <col style="width: 70%;">
</colgroup>
<tr>
    <td colspan="2">Merged cell</td>
</tr>
<tr>
    <td style="word-wrap: break-word">VeryLongWordInThisCell</td>
    <td style="word-wrap: break-word">Cell 2</td>
</tr>
</table>

How to read a Parquet file into Pandas DataFrame?

pandas 0.21 introduces new functions for Parquet:

pd.read_parquet('example_pa.parquet', engine='pyarrow')

or

pd.read_parquet('example_fp.parquet', engine='fastparquet')

The above link explains:

These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).

How to find minimum value from vector?

template <class ForwardIterator>
ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
    ForwardIterator lowest = first;
    if (first == last) return last;
    while (++first != last)
    if (*first < *lowest) 
        lowest = first;
    return lowest;
}

How do I get the title of the current active window using c#?

Use the Windows API. Call GetForegroundWindow().

GetForegroundWindow() will give you a handle (named hWnd) to the active window.

Documentation: GetForegroundWindow function | Microsoft Docs

Add a "sort" to a =QUERY statement in Google Spreadsheets

You can use ORDER BY clause to sort data rows by values in columns. Something like

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")

If you’d like to order by some columns descending, others ascending, you can add desc/asc, ie:

=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")

Identify duplicate values in a list in Python

mylist = [20, 30, 25, 20]

kl = {i: mylist.count(i) for i in mylist if mylist.count(i) > 1 }

print(kl)

Cannot create SSPI context

It's quite a common error with a variety of causes: start here with KB 811889

  • What version of SQL Server?
  • And Windows on client and server?
  • Local or network SQL instance?
  • Domain or workgroup? Provider?
  • Changing password
  • Local windows log errors?
  • Any other apps affected?

405 method not allowed Web API

I had the same exception. My problem was that I had used:

using System.Web.Mvc; // Wrong namespace for HttpGet attribute !!!!!!!!!
[HttpGet]
public string Blah()
{
    return "blah";
}

SHOULD BE

using System.Web.Http; // Correct namespace for HttpGet attribute !!!!!!!!!
[HttpGet]
public string Blah()
{
    return "blah";
}

How do I return the SQL data types from my query?

For SQL Server 2012 and above: If you place the query into a string then you can get the result set data types like so:

DECLARE @query nvarchar(max) = 'select 12.1 / 10.1 AS [Column1]';
EXEC sp_describe_first_result_set @query, null, 0;  

How to get last N records with activerecord?

If you have a default scope in your model that specifies an ascending order in Rails 3 you'll need to use reorder rather than order as specified by Arthur Neves above:

Something.limit(5).reorder('id desc')

or

Something.reorder('id desc').limit(5)

SQL Server : SUM() of multiple rows including where clauses

Use a common table expression to add grand total row, top 100 is required for order by to work.

With Detail as 
(
    SELECT  top 100 propertyId, SUM(Amount) as TOTAL_COSTS
    FROM MyTable
    WHERE EndDate IS NULL
    GROUP BY propertyId
    ORDER BY TOTAL_COSTS desc
)

Select * from Detail
Union all
Select ' Total ', sum(TOTAL_COSTS) from Detail

Jquery submit form

Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :

$(".nextbutton").click(function() { 
  $("#formID")[0].submit();
});

Check if file exists and whether it contains a specific string

You should use the grep -q flag for quiet output. See the man pages below:

man grep output :

 General Output Control

  -q, --quiet, --silent
              Quiet;  do  not write anything to standard output.  Exit immediately with zero status
              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or
              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

grepUtil.ksh :

#!/bin/ksh

#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"

#Function to initialize variables
initialize(){
    echo "Entering initialize"
    echo "Exiting initialize"
}

#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
    echo "Entering createFileWithInput"
    orgDirectory=${PWD}
    cd ${1}
    > ${2}
    print ${3} >> ${2}
    cd ${orgDirectory}
    echo "Exiting createFileWithInput"
}

#Function to create File with Input
#Params: 1}directoryName
createDir(){
    echo "Entering createDir"
    mkdir -p ${1}
    echo "Exiting createDir"
}

#Params: 1}FileName
readLine(){
    echo "Entering readLine"
    file=${1}
    while read line
    do
        #assign last line to var
        var="$line"
    done <"$file"
    echo "Exiting readLine"
}
#Check if file exists 
#Params: 1}File
doesFileExit(){
    echo "Entering doesFileExit"
    orgDirectory=${PWD}
    cd ${PWD}${dirPath}
    #echo ${PWD}
    if [[ -e "${1}" ]]; then
        echo "${1} exists"
    else
        echo "${1} does not exist"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileExit"
}
#Check if file contains a string quietly
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainStringQuiet(){
    echo "Entering doesFileContainStringQuiet"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep -q ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainStringQuiet"
}
#Check if file contains a string with output
#Params: 1}Directory Path 2}File 3}String to seach for in File
doesFileContainString(){
    echo "Entering doesFileContainString"
    orgDirectory=${PWD}
    cd ${PWD}${1}
    #echo ${PWD}
    grep ${3} ${2}
    if [ ${?} -eq 0 ];then
        echo "${3} found in ${2}"
    else
        echo "${3} not found in ${2}"
    fi
    cd ${orgDirectory}
    echo "Exiting doesFileContainString"
}

#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
#initialize #function call#
createDir ${dir} #function call#
createFileWithInput ${dir} ${file} ${searchString} #function call#
doesFileExit ${file} #function call#
if [ ${?} -eq 0 ];then
    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#
    doesFileContainString ${dirPath} ${file} ${searchString} #function call#
fi
echo "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh

JSON.parse vs. eval()

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:

var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"

eval(x)         //won't work
JSON.parse(x)   //does work

See this example.

Finding diff between current and last version

If the top commit is pointed to by HEAD then you can do something like this:

commit1 -> HEAD
commit2 -> HEAD~1
commit3 -> HEAD~2

Diff between the first and second commit:

git diff HEAD~1 HEAD

Diff between first and third commit:

git diff HEAD~2 HEAD

Diff between second and third commit:

git diff HEAD~2 HEAD~1

And so on...

Change the class from factor to numeric of many columns in a data frame

Here are some dplyr options:

# by column type:
df %>% 
  mutate_if(is.factor, ~as.numeric(as.character(.)))

# by specific columns:
df %>% 
  mutate_at(vars(x, y, z), ~as.numeric(as.character(.))) 

# all columns:
df %>% 
  mutate_all(~as.numeric(as.character(.))) 

How to affect other elements when one element is hovered

Using the sibling selector is the general solution for styling other elements when hovering over a given one, but it works only if the other elements follow the given one in the DOM. What can we do when the other elements should actually be before the hovered one? Say we want to implement a signal bar rating widget like the one below:

Signal bar rating widget

This can actually be done easily using the CSS flexbox model, by setting flex-direction to reverse, so that the elements are displayed in the opposite order from the one they're in the DOM. The screenshot above is from such a widget, implemented with pure CSS.

Flexbox is very well supported by 95% of modern browsers.

_x000D_
_x000D_
.rating {_x000D_
  display: flex;_x000D_
  flex-direction: row-reverse;_x000D_
  width: 9rem;_x000D_
}_x000D_
.rating div {_x000D_
  flex: 1;_x000D_
  align-self: flex-end;_x000D_
  background-color: black;_x000D_
  border: 0.1rem solid white;_x000D_
}_x000D_
.rating div:hover {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
.rating div[data-rating="1"] {_x000D_
  height: 5rem;_x000D_
}_x000D_
.rating div[data-rating="2"] {_x000D_
  height: 4rem;_x000D_
}_x000D_
.rating div[data-rating="3"] {_x000D_
  height: 3rem;_x000D_
}_x000D_
.rating div[data-rating="4"] {_x000D_
  height: 2rem;_x000D_
}_x000D_
.rating div[data-rating="5"] {_x000D_
  height: 1rem;_x000D_
}_x000D_
.rating div:hover ~ div {_x000D_
  background-color: lightblue;_x000D_
}
_x000D_
<div class="rating">_x000D_
  <div data-rating="1"></div>_x000D_
  <div data-rating="2"></div>_x000D_
  <div data-rating="3"></div>_x000D_
  <div data-rating="4"></div>_x000D_
  <div data-rating="5"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Looping through a DataTable

foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

I also tried http://www.eclipse.org/cdt/ in Ubuntu 12.04.2 LTS and works fine!

  1. First, I downloaded it from www.eclipse.org/downloads/, choosing Eclipse IDE for C/C++ Developers.
  2. I save the file somewhere, let´s say into my home directory. Open a console or terminal, and type:

    >>cd ~; tar xvzf eclipse*.tar.gz;

  3. Remember for having Eclipse running in Linux, it is required a JVM, so download a jdk file e.g jdk-7u17-linux-i586.rpm (I cann´t post the link due to my low reputation) ... anyway

  4. Install the .rpm file following http://www.wikihow.com/Install-Java-on-Linux

  5. Find the path to the Java installation, by typing:

    >>which java

  6. I got /usr/bin/java. To start up Eclipse, type:

    >>cd ~/eclipse; ./eclipse -vm /usr/bin/java

Also, once everything is installed, in the home directory, you can double-click the executable icon called eclipse, and then you´ll have it!. In case you like an icon, create a .desktop file in /usr/share/applications:

>>sudo gedit /usr/share/applications/eclipse.desktop

The .desktop file content is as follows:

[Desktop Entry]  
Name=Eclipse  
Type=Application  
Exec="This is the path of the eclipse executable on your machine"  
Terminal=false 
Icon="This is the path of the icon.xpm file on your machine"  
Comment=Integrated Development Environment  
NoDisplay=false  
Categories=Development;IDE  
Name[en]=eclipse.desktop  

Best luck!

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

write direct password into config>database.php

'password' => env('DB_PASSWORD', '')

Change to

'password' => 'your password',

Set Content-Type to application/json in jsp file

Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

How do I detect "shift+enter" and generate a new line in Textarea?

Using ReactJS ES6 here's the simplest way

shift + enter New Line at any position

enter Blocked

_x000D_
_x000D_
class App extends React.Component {_x000D_
_x000D_
 constructor(){_x000D_
    super();_x000D_
    this.state = {_x000D_
      message: 'Enter is blocked'_x000D_
    }_x000D_
  }_x000D_
  onKeyPress = (e) => {_x000D_
     if (e.keyCode === 13 && e.shiftKey) {_x000D_
        e.preventDefault();_x000D_
        let start = e.target.selectionStart,_x000D_
            end = e.target.selectionEnd;_x000D_
        this.setState(prevState => ({ message:_x000D_
            prevState.message.substring(0, start)_x000D_
            + '\n' +_x000D_
            prevState.message.substring(end)_x000D_
        }),()=>{_x000D_
            this.input.selectionStart = this.input.selectionEnd = start + 1;_x000D_
        })_x000D_
    }else if (e.keyCode === 13) { // block enter_x000D_
      e.preventDefault();_x000D_
    }_x000D_
    _x000D_
  };_x000D_
_x000D_
  render(){_x000D_
    return(_x000D_
      <div>_x000D_
      New line with shift enter at any position<br />_x000D_
       <textarea _x000D_
       value={this.state.message}_x000D_
       ref={(input)=> this.input = input}_x000D_
       onChange={(e)=>this.setState({ message: e.target.value })}_x000D_
       onKeyDown={this.onKeyPress}/>_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

What are some uses of template template parameters?

Say you're using CRTP to provide an "interface" for a set of child templates; and both the parent and the child are parametric in other template argument(s):

template <typename DERIVED, typename VALUE> class interface {
    void do_something(VALUE v) {
        static_cast<DERIVED*>(this)->do_something(v);
    }
};

template <typename VALUE> class derived : public interface<derived, VALUE> {
    void do_something(VALUE v) { ... }
};

typedef interface<derived<int>, int> derived_t;

Note the duplication of 'int', which is actually the same type parameter specified to both templates. You can use a template template for DERIVED to avoid this duplication:

template <template <typename> class DERIVED, typename VALUE> class interface {
    void do_something(VALUE v) {
        static_cast<DERIVED<VALUE>*>(this)->do_something(v);
    }
};

template <typename VALUE> class derived : public interface<derived, VALUE> {
    void do_something(VALUE v) { ... }
};

typedef interface<derived, int> derived_t;

Note that you are eliminating directly providing the other template parameter(s) to the derived template; the "interface" still receives them.

This also lets you build up typedefs in the "interface" that depend on the type parameters, which will be accessible from the derived template.

The above typedef doesn't work because you can't typedef to an unspecified template. This works, however (and C++11 has native support for template typedefs):

template <typename VALUE>
struct derived_interface_type {
    typedef typename interface<derived, VALUE> type;
};

typedef typename derived_interface_type<int>::type derived_t;

You need one derived_interface_type for each instantiation of the derived template unfortunately, unless there's another trick I haven't learned yet.

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

Laravel: Get Object From Collection By Attribute

As the question above when you are using the where clause you also need to use the get Or first method to get the result.

/**
*Get all food
*
*/

$foods = Food::all();

/**
*Get green food 
*
*/

$green_foods = Food::where('color', 'green')->get();

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

Why does overflow:hidden not work in a <td>?

Apply CSS table-layout:fixed; (and sometimes width:<any px or %>) to the TABLE and white-space: nowrap; overflow: hidden; style on TD. Then set CSS widths on the correct cell or column elements.

Significantly, fixed-layout table column widths are determined by the cell widths in the first row of the table. If there are TH elements in the first row, and widths are applied to TD (and not TH), then the width only applies to the contents of the TD (white-space and overflow may be ignored); the table columns will distribute evenly regardless of the set TD width (because there are no widths specified [on TH in the first row]) and the columns will have [calculated] equal widths; the table will not recalculate the column width based on TD width in subsequent rows. Set the width on the first cell elements the table will encounter.

Alternatively, and the safest way to set column widths is to use <COLGROUP> and <COL> tags in the table with the CSS width set on each fixed width COL. Cell width related CSS plays nicer when the table knows the column widths in advance.

"multiple target patterns" Makefile error

I met with the same error. After struggling, I found that it was due to "Space" in the folder name.

For example :

Earlier My folder name was : "Qt Projects"

Later I changed it to : "QtProjects"

and my issue was resolved.

Its very simple but sometimes a major issue.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Python: finding an element in a list

There is the index method, i = array.index(value), but I don't think you can specify a custom comparison operator. It wouldn't be hard to write your own function to do so, though:

def custom_index(array, compare_function):
    for i, v in enumerate(array):
        if compare_function(v):
            return i

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

How to use concerns in Rails 4

So I found it out by myself. It is actually a pretty simple but powerful concept. It has to do with code reuse as in the example below. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and messy.

As an example, I'll put one well known pattern, the taggable pattern:

# app/models/product.rb
class Product
  include Taggable

  ...
end

# app/models/concerns/taggable.rb
# notice that the file name has to match the module name 
# (applying Rails conventions for autoloading)
module Taggable
  extend ActiveSupport::Concern

  included do
    has_many :taggings, as: :taggable
    has_many :tags, through: :taggings

    class_attribute :tag_limit
  end

  def tags_string
    tags.map(&:name).join(', ')
  end

  def tags_string=(tag_string)
    tag_names = tag_string.to_s.split(', ')

    tag_names.each do |tag_name|
      tags.build(name: tag_name)
    end
  end

  # methods defined here are going to extend the class, not the instance of it
  module ClassMethods

    def tag_limit(value)
      self.tag_limit_value = value
    end

  end

end

So following the Product sample, you can add Taggable to any class you desire and share its functionality.

This is pretty well explained by DHH:

In Rails 4, we’re going to invite programmers to use concerns with the default app/models/concerns and app/controllers/concerns directories that are automatically part of the load path. Together with the ActiveSupport::Concern wrapper, it’s just enough support to make this light-weight factoring mechanism shine.

IllegalArgumentException or NullPointerException for a null parameter?

the dichotomy... Are they non-overlapping? Only non-overlapping parts of a whole can make a dichotomy. As i see it:

throw new IllegalArgumentException(new NullPointerException(NULL_ARGUMENT_IN_METHOD_BAD_BOY_BAD));

How can I get the current user's username in Bash?

All,

From what I'm seeing here all answers are wrong, especially if you entered the sudo mode, with all returning 'root' instead of the logged in user. The answer is in using 'who' and finding eh 'tty1' user and extracting that. Thw "w" command works the same and var=$SUDO_USER gets the real logged in user.

Cheers!

TBNK

How do I update Node.js?

You may use Chocolatey on Windows. It's very easy to use and useful for keeping you updated with other applications too.

Also, you can just simply download the latest version from https://nodejs.org and install it.

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

New Array from Index Range Swift

Array functional way:

   array.enumerated().filter { $0.offset < limit }.map { $0.element }

ranged:

 array.enumerated().filter { $0.offset >= minLimit && $0.offset < maxLimit }.map { $0.element }

The advantage of this method is such implementation is safe.

How to populate HTML dropdown list with values from database

<?php
 $query = "select username from users";
 $res = mysqli_query($connection, $query);   
?>


<form>
  <select>
     <?php
       while ($row = $res->fetch_assoc()) 
       {
         echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
       }
    ?>
  </select>
</form>

Declaring and initializing arrays in C

There is no such particular way in which you can initialize the array after declaring it once.

There are three options only:

1.) initialize them in different lines :

int array[SIZE];

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...

But thats not what you want i guess.

2.) Initialize them using a for or while loop:

for (i = 0; i < MAX ; i++)  {
    array[i] = i;
}

This is the BEST WAY by the way to achieve your goal.

3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.

And can I ask you why specifically you want to do so???

setTimeout or setInterval?

You can validate bobince answer by yourself when you run the following javascript or check this JSFiddle

<div id="timeout"></div>
<div id="interval"></div>

var timeout = 0;
var interval = 0;

function doTimeout(){
    $('#timeout').html(timeout);
    timeout++;
    setTimeout(doTimeout, 1);
}

function doInterval(){
    $('#interval').html(interval);
    interval++;
}

$(function(){
    doTimeout();
    doInterval();
    setInterval(doInterval, 1);
});

sqlalchemy filter multiple columns

A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.

search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()

Note: the %% are important to skip % formatting the query.

Multiple argument IF statement - T-SQL

Seems to work fine.

If you have an empty BEGIN ... END block you might see

Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.

Java 8 lambda Void argument

I don't think it is possible, because function definitions do not match in your example.

Your lambda expression is evaluated exactly as

void action() { }

whereas your declaration looks like

Void action(Void v) {
    //must return Void type.
}

as an example, if you have following interface

public interface VoidInterface {
    public Void action(Void v);
}

the only kind of function (while instantiating) that will be compatibile looks like

new VoidInterface() {
    public Void action(Void v) {
        //do something
        return v;
    }
}

and either lack of return statement or argument will give you a compiler error.

Therefore, if you declare a function which takes an argument and returns one, I think it is impossible to convert it to function which does neither of mentioned above.

How do I parse JSON with Ruby on Rails?

This can be done as below, just need to use JSON.parse, then you can traverse through it normally with indices.

#ideally not really needed, but in case if JSON.parse is not identifiable in your module  
require 'json'

#Assuming data from bitly api is stored in json_data here

json_data = '{
  "errorCode": 0,
  "errorMessage": "",
  "results":
  {
    "http://www.foo.com":
    {
       "hash": "e5TEd",
       "shortKeywordUrl": "",
       "shortUrl": "http://whateverurl",
       "userHash": "1a0p8G"
    }
  },
  "statusCode": "OK"
}'

final_data = JSON.parse(json_data)
puts final_data["results"]["http://www.foo.com"]["shortUrl"]

Get fragment (value after hash '#') from a URL in php

I found this trick if you insist want the value with PHP. split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP

How to handle the new window in Selenium WebDriver using Java?

I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

In my case checking the check-box

"Copy project into workspace"

did the trick.

What is the default stack size, can it grow, how does it work with garbage collection?

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.

Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).

Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.

how does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.

How to use EOF to run through a text file in C?

You should check the EOF after reading from file.

fscanf_s                   // read from file
while(condition)           // check EOF
{
   fscanf_s               // read from file
}

Connect Java to a MySQL database

String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";

// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);

Angular2 - Http POST request parameters

angular: 
    MethodName(stringValue: any): Observable<any> {
    let params = new HttpParams();
    params = params.append('categoryName', stringValue);

    return this.http.post('yoururl', '', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      params: params,
      responseType: "json"
    })
  }

api:   
  [HttpPost("[action]")]
  public object Method(string categoryName)

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

This really should be a comment to Brad Rippe's answer, but alas, not enough rep. That answer got me 90% of the way there. In my case, the installation and configuration of the databases put entries in the tnsnames.ora file for the databases I was running. First, I was able to connect to the database by setting the environment variables (Windows):

set ORACLE_SID=mydatabase
set ORACLE_HOME=C:\Oracle\product\11.2.0\dbhome_1

and then connecting using

sqlplus / as sysdba

Next, running the command from Brad Rippe's answer:

select value from v$parameter where name='service_names';

showed that the names didn't match exactly. The entries as created using Oracle's Database Configuration Assistant where originally:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase.mydomain.com)
    )
  ) 

The service name from the query was just mydatabase rather than mydatabase.mydomain.com. I edited the tnsnames.ora file to just the base name without the domain portion so they looked like this:

MYDATABASE =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = mylaptop.mydomain.com)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = mydatabase)
    )
  ) 

I restarted the TNS Listener service (I often use lsnrctl stop and lsnrctl start from an administrator command window [or Windows Powershell] instead of the Services control panel, but both work.) After that, I was able to connect.

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

Iterating over Typescript Map

es6

for (let [key, value] of map) {
    console.log(key, value);
}

es5

for (let entry of Array.from(map.entries())) {
    let key = entry[0];
    let value = entry[1];
}

how to deal with google map inside of a hidden div (Updated picture)

 $("#map_view").show("slow"); // use id of div which you want to show.
     var script = document.createElement("script");
     script.type = "text/javascript";
     script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize";
     document.body.appendChild(script);

Why cannot cast Integer to String in java?

You can't cast explicitly anything to a String that isn't a String. You should use either:

"" + myInt;

or:

Integer.toString(myInt);

or:

String.valueOf(myInt);

I prefer the second form, but I think it's personal choice.

Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

Javascript "Not a Constructor" Exception while creating objects

To add to @wprl's answer, the ES6 object method shorthand, like the arrow functions, cannot be used as a constructor either.

const o = {
  a: () => {},
  b() {},
  c: function () {}
};

const { a, b, c } = o;

new a(); // throws "a is not a constructor"
new b(); // throws "b is not a constructor"
new c(); // works

Upgrading React version and it's dependencies by reading package.json

I highly recommend using yarn upgrade-interactive to update React, or any Node project for that matter. It lists your packages, current version, the latest version, an indication of a Minor, Major, or Patch update compared to what you have, plus a link to the respective project.

You run it with yarn upgrade-interactive --latest, check out release notes if you want, go down the list with your arrow keys, choose which packages you want to upgrade by selecting with the space bar, and hit Enter to complete.

Npm-upgrade is ok but not as slick.

How do I create a multiline Python string with inline variables?

If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:

query = """
{{
  pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
    id
    txCount
    reserveUSD
    trackedReserveETH
    volumeUSD
  }}
}}
""".format(block=''.join(['{number: ', str(block), '}']))

 query = gql(query)

Make sure to escape all curly braces like I did: "{{", "}}"

How to prepend a string to a column value in MySQL?

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

How many bytes is unsigned long long?

It must be at least 64 bits. Other than that it's implementation defined.

Strictly speaking, unsigned long long isn't standard in C++ until the C++0x standard. unsigned long long is a 'simple-type-specifier' for the type unsigned long long int (so they're synonyms).

The long long set of types is also in C99 and was a common extension to C++ compilers even before being standardized.

How do I enable/disable log levels in Android?

Another way is to use a logging platform that has the capabilities of opening and closing logs. This can give much of flexibility sometimes even on a production app which logs should be open and which closed depending on which issues you have for example:

Why doesn't java.util.Set have get(int index)?

That's true, element in Set are not ordered, by definition of the Set Collection. So they can't be access by an index.

But why don't we have a get(object) method, not by providing the index as parameter, but an object that is equal to the one we are looking for? By this way, we can access the data of the element inside the Set, just by knowing its attributes used by the equal method.

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

I had similar problem in SQL Workbench.

URL:

jdbc:oracle:thin:@111.111.111.111:1111:xe

doesn't work.

URL:

jdbc:oracle:thin:@111.111.111.111:1111:asdb

works.

This help me in my concrete situation. I afraid, that could exists many other reasons with different solutions.

How can I show/hide a specific alert with twitter bootstrap?

On top of all the previous answers, dont forget to hide your alert before using it with a simple style="display:none;"

<div class="alert alert-success" id="passwordsNoMatchRegister" role="alert" style="display:none;" >Message of the Alert</div>

Then use either:

$('#passwordsNoMatchRegister').show();

$('#passwordsNoMatchRegister').fadeIn();

$('#passwordsNoMatchRegister').slideDown();

What is the purpose of a plus symbol before a variable?

Operator + is a unary operator which converts value to number. Below I prepared a table with corresponding results of using this operator for different values.

+-----------------------------+-----------+
| Value                       | + (Value) |
+-----------------------------+-----------+
| 1                           | 1         |
| '-1'                        | -1        |
| '3.14'                      | 3.14      |
| '3'                         | 3         |
| '0xAA'                      | 170       |
| true                        | 1         |
| false                       | 0         |
| null                        | 0         |
| 'Infinity'                  | Infinity  |
| 'infinity'                  | NaN       |
| '10a'                       | NaN       |
| undefined                   | Nan       |
| ['Apple']                   | Nan       |
| function(val){ return val } | NaN       |
+-----------------------------+-----------+

Operator + returns value for objects which have implemented method valueOf.

let something = {
    valueOf: function () {
        return 25;
    }
};

console.log(+something);

Sort JavaScript object by key

Just use lodash to unzip map and sortBy first value of pair and zip again it will return sorted key.

If you want sortby value change pair index to 1 instead of 0

var o = { 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' };
console.log(_(o).toPairs().sortBy(0).fromPairs().value())

enter image description here

What's the difference between session.persist() and session.save() in Hibernate?

It completely answered on basis of "generator" type in ID while storing any entity. If value for generator is "assigned" which means you are supplying the ID. Then it makes no diff in hibernate for save or persist. You can go with any method you want. If value is not "assigned" and you are using save() then you will get ID as return from the save() operation.

Another check is if you are performing the operation outside transaction limit or not. Because persist() belongs to JPA while save() for hibernate. So using persist() outside transaction boundaries will not allow to do so and throw exception related to persistant. while with save() no such restriction and one can go with DB transaction through save() outside the transaction limit.

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.

To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.

Example for manual parsing:

var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));

Example using date.js:

var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.

The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.

If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).

If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).

socket.error: [Errno 48] Address already in use

By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.

(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)

How do I print the elements of a C++ vector in GDB?

A little late to the party, so mostly a reminder to me next time I do this search!

I have been able to use:

p/x *(&vec[2])@4

to print 4 elements (as hex) from vec starting at vec[2].

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

jQuery javascript regex Replace <br> with \n

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");

or using jQuery:

var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));

example

edit: added i flag

edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

Visual Studio loading symbols

Visual Studio 2017 Debug symbol "speed-up" options, assuming you haven't gone crazy on option-customization already:

  1. At Tools -> Options -> Debugging -> Symbols
    a. Enable the "Microsoft Symbol Server" option
    b. Click "Empty Symbol Cache"
    c. Set your symbol cache to an easy to find spot, like C:\dbg_symbols or %USERPROFILE%\dbg_symbols
  2. After re-running Debug, let it load all the symbols once, from start-to-end, or as much as reasonably possible.

1A and 2 are the most important steps. 1B and 1C are just helpful changes to help you keep track of your symbols.

After your app has loaded all the symbols at least once and debugging didn't prematurely terminate, those symbols should be quickly loaded the next time debug runs.

I've noticed that if I cancel a debug-run, I have to reload those symbols, as I'm guessing they're "cleaned" up if newly introduced and suddenly cancelled. I understand the core rationale for that kind of flow, but in this case it seems poorly thought out.

What is System, out, println in System.out.println() in Java

System is a final class from the java.lang package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

The tilde operator in Python

I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.

The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n) time

The standard solution is:

Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
        and then multiplying them for the final answer 

His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~

def productExceptSelf(self, nums):
    res = [1]*len(nums)
    lprod = 1
    rprod = 1
    for i in range(len(nums)):
        res[i] *= lprod
        lprod *= nums[i]
        res[~i] *= rprod
        rprod *= nums[~i]
    return res

Angular 2 optional route parameter

With this matcher function you can get desirable behavior without component re-rendering. When url.length equals to 0, there's no optional parameters, with url.length equals to 1, there's 1 optional parameter. id - is the name of optional parameter.

  const routes: Routes = [
  {
    matcher: (segments) => {
      if (segments.length <= 1) {
        return {
          consumed: segments,
          posParams: {
            id: new UrlSegment(segments[0]?.path || '', {}),
          },
        };
      }
      return null;
    },
    pathMatch: 'prefix',
    component: UserComponent,
  }]

Removing all script tags from html with JS Regular Expression

/(?:(?!</s\w)<[^<])</s\w*/gi; - Removes any sequence in any combination with

What are WSDL, SOAP and REST?

Some clear explanations (for SOAP and WSDL) can be found here as well.

Difference between a SOAP message and a WSDL?

Correct way to initialize HashMap and can HashMap hold different value types?

The 2nd one is using generics which came in with Java 1.5. It will reduce the number of casts in your code & can help you catch errors at compiletime instead of runtime. That said, it depends on what you are coding. A quick & dirty map to hold a few objects of various types doesn't need generics. But if the map is holding objects all descending from a type other than Object, it can be worth it.

The prior poster is incorrect about the array in a map. An array is actually an object, so it is a valid value.

Map<String,Object> map = new HashMap<String,Object>();
map.put("one",1); // autoboxed to an object
map.put("two", new int[]{1,2} ); // array of ints is an object
map.put("three","hello"); // string is an object

Also, since HashMap is an object, it can also be a value in a HashMap.

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

If you are using bootstrap that will be the problem. If you want to use same bootstrap file in two locations use it below the header section .(example - inside body)

Note : "specially when you use html editors. "

Thank you.

Why doesn't JUnit provide assertNotEquals methods?

I'm coming to this party pretty late but I have found that the form:

static void assertTrue(java.lang.String message, boolean condition) 

can be made to work for most 'not equals' cases.

int status = doSomething() ; // expected to return 123
assertTrue("doSomething() returned unexpected status", status != 123 ) ;

How to crop an image using C#?

here it is working demo on github

https://github.com/SystematixIndore/Crop-SaveImageInCSharp

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
 <link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
</head>
<body>
  <form id="form2" runat="server">
  <div>
    <asp:Panel ID="pnlUpload" runat="server">
      <asp:FileUpload ID="Upload" runat="server" />
      <br />
      <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
      <asp:Label ID="lblError" runat="server" Visible="false" />
    </asp:Panel>
    <asp:Panel ID="pnlCrop" runat="server" Visible="false">
      <asp:Image ID="imgCrop" runat="server" />
      <br />
      <asp:HiddenField ID="X" runat="server" />
      <asp:HiddenField ID="Y" runat="server" />
      <asp:HiddenField ID="W" runat="server" />
      <asp:HiddenField ID="H" runat="server" />
      <asp:Button ID="btnCrop" runat="server" Text="Crop" OnClick="btnCrop_Click" />
    </asp:Panel>
    <asp:Panel ID="pnlCropped" runat="server" Visible="false">
      <asp:Image ID="imgCropped" runat="server" />
    </asp:Panel>
  </div>
  </form>
    <script type="text/javascript">
  jQuery(document).ready(function() {
    jQuery('#imgCrop').Jcrop({
      onSelect: storeCoords
    });
  });

  function storeCoords(c) {
    jQuery('#X').val(c.x);
    jQuery('#Y').val(c.y);
    jQuery('#W').val(c.w);
    jQuery('#H').val(c.h);
  };

</script>
</body>
</html>

C# code logic for upload and crop.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Boolean FileOK = false;
            Boolean FileSaved = false;

            if (Upload.HasFile)
            {
                Session["WorkingImage"] = Upload.FileName;
                String FileExtension = Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
                String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (FileExtension == allowedExtensions[i])
                    {
                        FileOK = true;
                    }
                }
            }

            if (FileOK)
            {
                try
                {
                    Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
                    FileSaved = true;
                }
                catch (Exception ex)
                {
                    lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                    lblError.Visible = true;
                    FileSaved = false;
                }
            }
            else
            {
                lblError.Text = "Cannot accept files of this type.";
                lblError.Visible = true;
            }

            if (FileSaved)
            {
                pnlUpload.Visible = false;
                pnlCrop.Visible = true;
                imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
            }
        }

        protected void btnCrop_Click(object sender, EventArgs e)
        {
            string ImageName = Session["WorkingImage"].ToString();
            int w = Convert.ToInt32(W.Value);
            int h = Convert.ToInt32(H.Value);
            int x = Convert.ToInt32(X.Value);
            int y = Convert.ToInt32(Y.Value);

            byte[] CropImage = Crop(path + ImageName, w, h, x, y);
            using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
            {
                ms.Write(CropImage, 0, CropImage.Length);
                using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
                {
                    string SaveTo = path + "crop" + ImageName;
                    CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
                    pnlCrop.Visible = false;
                    pnlCropped.Visible = true;
                    imgCropped.ImageUrl = "images/crop" + ImageName;
                }
            }
        }

        static byte[] Crop(string Img, int Width, int Height, int X, int Y)
        {
            try
            {
                using (SD.Image OriginalImage = SD.Image.FromFile(Img))
                {
                    using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
                    {
                        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                        using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                        {
                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, OriginalImage.RawFormat);
                            return ms.GetBuffer();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
        }
    }
}

Save results to csv file with Python

This is how I do it

 import csv
    file = open('???.csv', 'r')
    read = csv.reader(file)
    for column in read:
            file = open('???.csv', 'r')
            read = csv.reader(file)
            file.close()
            file = open('????.csv', 'a', newline='')
            write = csv.writer(file, delimiter = ",")
            write.writerow((, ))
            file.close()

How to run Java program in command prompt

All you need to do is:

  • Build the mainjava class using the class path if any (optional)

    javac *.java [ -cp "wb.jar;"]

  • Create Manifest.txt file with content is:

    Main-Class: mainjava

  • Package the jar file for mainjava class

    jar cfm mainjava.jar Manifest.txt *.class

Then you can run this .jar file from cmd with class path (optional) and put arguments for it.

java [-cp "wb.jar;"] mainjava arg0 arg1 

HTH.

How to construct a REST API that takes an array of id's for the resources

If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:

api.com/users?id=id1,id2,id3,id4,id5

Memory address of variables in Java

Like Sunil said, this is not memory address.This is just the hashcode

To get the same @ content, you can:

If hashCode is not overridden in that class:

"@" + Integer.toHexString(obj.hashCode())

If hashCode is overridden, you get the original value with:

"@" + Integer.toHexString(System.identityHashCode(obj)) 

This is often confused with memory address because if you don't override hashCode(), the memory address is used to calculate the hash.

Make install, but not to default directories?

try using INSTALL_ROOT.

make install INSTALL_ROOT=$INSTALL_DIRECTORY

How can I get the source directory of a Bash script from within the script itself?

$_ is worth mentioning as an alternative to $0. If you're running a script from Bash, the accepted answer can be shortened to:

DIR="$( dirname "$_" )"

Note that this has to be the first statement in your script.

Change the background color of CardView programmatically

You can use this in XML

card_view:cardBackgroundColor="@android:color/white"

or this in Java

cardView.setCardBackgroundColor(Color.WHITE);

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

Sending E-mail using C#

I can strongly recommend the aspNetEmail library: http://www.aspnetemail.com/

The System.Net.Mail will get you somewhere if your needs are only basic, but if you run into trouble, please check out aspNetEmail. It has saved me a bunch of time, and I know of other develoeprs who also swear by it!

Make copy of an array

For a null-safe copy of an array, you can also use an optional with the Object.clone() method provided in this answer.

int[] arrayToCopy = {1, 2, 3};
int[] copiedArray = Optional.ofNullable(arrayToCopy).map(int[]::clone).orElse(null);

PostgreSQL delete with inner join

Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

Is it possible to clone html element objects in JavaScript / JQuery?

Get the HTML of the element to clone with .innerHTML, and then just make a new object by means of createElement()...

var html = document.getElementById('test').innerHTML;
var clone = document.createElement('span');
clone.innerHTML = html;

In general, clone() functions must be coded by, or understood by, the cloner. For example, let's clone this: <div>Hello, <span>name!</span></div>. If I delete the clone's <span> tags, should it also delete the original's span tags? If both are deleted, the object references were cloned; if only one set is deleted, the object references are brand-new instantiations. In some cases you want one, in others the other.

In HTML, typically, you'll want anything cloned to be referentially self-contained. The best way to make sure these new references are contained properly is to have the same innerHTML rerun and re-understood by the browser within a new element. Better than working to solve your problem, you should know exactly how it's doing its cloning...

Full Working Demo:

_x000D_
_x000D_
function cloneElement() {
    var html = document.getElementById('test').innerHTML;
    var clone = document.createElement('span');
    clone.innerHTML = html;
    document.getElementById('clones').appendChild(clone);
}
_x000D_
<span id="test">Hello!!!</span><br><br>

<span id="clones"></span><br><br>

<input type="button" onclick="cloneElement();" value="Click Here to Clone an Element">
_x000D_
_x000D_
_x000D_

Automating running command on Linux from Windows using PuTTY

In case you are using Key based authentication, using saved Putty session seems to work great, for example to run a shell script on a remote server(In my case an ec2).Saved configuration will take care of authentication.

C:\Users> plink saved_putty_session_name path_to_shell_file/filename.sh

Please remember if you save your session with name like(user@hostname), this command would not work as it will be treated as part of the remote command.

How to return dictionary keys as a list in Python?

Python >= 3.5 alternative: unpack into a list literal [*newdict]

New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:

>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]

Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.

Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).

The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.


Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:

%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop

%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop

%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop

with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).


In a similar fashion, you can create tuples and sets of dictionary keys:

>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}

beware of the trailing comma in the tuple case!

Linux: Which process is causing "device busy" when doing umount?

You should use the fuser command.

Eg. fuser /dev/cdrom will return the pid(s) of the process using /dev/cdrom.

If you are trying to unmount, you can kill theses process using the -k switch (see man fuser).

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

How to call function of one php file from another php file and pass parameters to it?

you can write the function in a separate file (say common-functions.php) and include it wherever needed.

function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}

You can include common-functions.php in another file as below.

include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);

You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.

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

import platform
is_windows = any(platform.win32_ver())

or

import sys
is_windows = hasattr(sys, 'getwindowsversion')

How do I disable right click on my web page?

Disabling right click on your web page is simple. There are just a few lines of JavaScript code that will do this job. Below is the JavaScript code:

$("html").on("contextmenu",function(e){
   return false;
});

In the above code, I have selected the tag. After you add just that three lines of code, it will disable right click on your web page.

Source: Disable right click, copy, cut on web page using jQuery

Is it correct to use DIV inside FORM?

Definition and Usage

The tag defines a division or a section in an HTML document.

The tag is used to group block-elements to format them with styles. http://www.w3schools.com/tags/tag_div.asp

Also DIV - MDN

The HTML element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as or ) is appropriate.

You can use div inside form, if you are talking about using div instead of table, then google about Tableless web design

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

Checking if type == list in python

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

htaccess - How to force the client's browser to clear the cache?

You can force browsers to cache something, but

You can't force browsers to clear their cache.

Thus the only (AMAIK) way is to use a new URL for your resources. Something like versioning.

How can I print a quotation mark in C?

Besides escaping the character, you can also use the format %c, and use the character literal for a quotation mark.

printf("And I quote, %cThis is a quote.%c\n", '"', '"');

Call to a member function fetch_assoc() on boolean in <path>

OK, i just fixed this error.

This happens when there is an error in query or table doesn't exist.

Try debugging the query buy running it directly on phpmyadmin to confirm the validity of the mysql Query

PHP - add 1 day to date format mm-dd-yyyy

there you go

$date = "04-15-2013";
$date1 = str_replace('-', '/', $date);
$tomorrow = date('m-d-Y',strtotime($date1 . "+1 days"));

echo $tomorrow;

this will output

04-16-2013

Documentation for both function
date
strtotime

PHP Create and Save a txt file to root directory

It's creating the file in the same directory as your script. Try this instead.

$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

Difference between a script and a program?

A "program" in general, is a sequence of instructions written so that a computer can perform certain task.

A "script" is code written in a scripting language. A scripting language is nothing but a type of programming language in which we can write code to control another software application.

In fact, programming languages are of two types:

a. Scripting Language

b. Compiled Language

Please read this: Scripting and Compiled Languages

in_array() and multidimensional array

I believe you can just use array_key_exists nowadays:

<?php
$a=array("Mac"=>"NT","Irix"=>"Linux");
if (array_key_exists("Mac",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>

Trying to embed newline in a variable in bash

sed solution:

echo "a b c" | sed 's/ \+/\n/g'

Result:

a
b
c

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Short And working Solution :

Follow Simple Steps :

Step 1 : Override onSaveInstanceState state in respective fragment. And remove super method from it.

@Override
public void onSaveInstanceState(Bundle outState) {
}

Step 2 : Use CommitAllowingStateLoss(); instead of commit(); while fragment operations.

fragmentTransaction.commitAllowingStateLoss();

How do I make XAML DataGridColumns fill the entire DataGrid?

Set the columns Width property to be a proportional width such as *

Authenticated HTTP proxy with Java

http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword says:

Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.

This is relevant if some http/https requests don't go through the proxy (which is quite possible depending on configuration). In that case, you would send your credentials directly to some http server, not to your proxy.

He suggests the following fix.

// Java ignores http.proxyUser. Here come's the workaround.
Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            String prot = getRequestingProtocol().toLowerCase();
            String host = System.getProperty(prot + ".proxyHost", "");
            String port = System.getProperty(prot + ".proxyPort", "80");
            String user = System.getProperty(prot + ".proxyUser", "");
            String password = System.getProperty(prot + ".proxyPassword", "");

            if (getRequestingHost().equalsIgnoreCase(host)) {
                if (Integer.parseInt(port) == getRequestingPort()) {
                    // Seems to be OK.
                    return new PasswordAuthentication(user, password.toCharArray());  
                }
            }
        }
        return null;
    }  
});

I haven't tried it yet, but it looks good to me.

I modified the original version slightly to use equalsIgnoreCase() instead of equals(host.toLowerCase()) because of this: http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug and I added "80" as the default value for port to avoid NumberFormatException in Integer.parseInt(port).

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

This happens because of your application does not allow to append iframe from origin other than your application domain.

If your application have web.config then add the following tag in web.config

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="X-Frame-Options" value="ALLOW" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

This will allow application to append iframe from other origin also. You can also use the following value for X-Frame-Option

X-FRAME-OPTIONS: ALLOW-FROM https://example.com/ 

Format Date time in AngularJS

You can use momentjs to implement date-time filter in angularjs. For example:

angular.module('myApp')
 .filter('formatDateTime', function ($filter) {
    return function (date, format) {
        if (date) {
            return moment(Number(date)).format(format || "DD/MM/YYYY h:mm A");
        }
        else
            return "";
    };
});

Where date is in time stamp format.

converting a base 64 string to an image and saving it

public bool SaveBase64(string Dir, string FileName, string FileType, string Base64ImageString)
{
    try
    {
        string folder = System.Web.HttpContext.Current.Server.MapPath("~/") + Dir;
        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        string filePath = folder + "/" + FileName + "." + FileType;
        File.WriteAllBytes(filePath, Convert.FromBase64String(Base64ImageString));
        return true;
    }
    catch
    {
        return false;
    }

}

ViewBag, ViewData and TempData

TempData will be always available until first read, once you read it its not available any more can be useful to pass quick message also to view that will be gone after first read. ViewBag Its more useful when passing quickly piece of data to the view, normally you should pass all data to the view through model , but there is cases when you model coming direct from class that is map into database like entity framework in that case you don't what to change you model to pass a new piece of data, you can stick that into the viewbag ViewData is just indexed version of ViewBag and was used before MVC3

Reading and writing to serial port in C on Linux

1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

Edited to Add:

Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

int tmp, serialLines;

cout << "Dropping Reading DTR and RTS\n";
ioctl ( readFd, TIOCMGET, & serialLines );
serialLines &= ~TIOCM_DTR;
serialLines &= ~TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
usleep(100000);
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
sleep (2);

cout << "Setting Reading DTR and RTS\n";
serialLines |= TIOCM_DTR;
serialLines |= TIOCM_RTS;
ioctl ( readFd, TIOCMSET, & serialLines );
ioctl ( readFd, TIOCMGET, & tmp );
cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;

C++ Convert string (or char*) to wstring (or wchar_t*)

std::string -> wchar_t[] with safe mbstowcs_s function:

auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());

This is from my sample code

Vue template or render function not defined yet I am using neither?

I am using Typescript with vue-property-decorator and what happened to me is that my IDE auto-completed "MyComponent.vue.js" instead of "MyComponent.vue". That got me this error.

It seems like the moral of the story is that if you get this error and you are using any kind of single-file component setup, check your imports in the router.

Print in new line, java

\n creates a new line in Java. Don't use spaces before or after \n.

Example: printing It creates\na new line outputs

It creates
a new line.

Get HTML code from website in C#

Better you can use the Webclient class to simplify your task:

using System.Net;

using (WebClient client = new WebClient())
{
    string htmlCode = client.DownloadString("http://somesite.com/default.html");
}

NuGet auto package restore does not work with MSBuild

Ian Kemp has the answer (have some points btw..), this is to simply add some meat to one of his steps.

The reason I ended up here was that dev's machines were building fine, but the build server simply wasn't pulling down the packages required (empty packages folder) and therefore the build was failing. Logging onto the build server and manually building the solution worked, however.

To fulfil the second of Ians 3 point steps (running nuget restore), you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step (other CI available...) immediately prior to building the solution

<Target Name="BeforeBuild">
  <Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>

For the record I'd already tried the "nuget installer" runner type but this step was hanging on web projects (worked for DLL's and Windows projects)

How do I convert an enum to a list in C#?

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public class NameValue
{
    public string Name { get; set; }
    public object Value { get; set; }
}

public static List<NameValue> EnumToList<T>()
{
    var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); 
    var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); 
    List<NameValue> lst = null;
    for (int i = 0; i < array.Length; i++)
    {
        if (lst == null)
            lst = new List<NameValue>();
        string name = array2[i];
        T value = array[i];
        lst.Add(new NameValue { Name = name, Value = value });
    }
    return lst;
}

Convert Enum To a list more information available here.

Conditionally ignoring tests in JUnit 4

You should checkout Junit-ext project. They have RunIf annotation that performs conditional tests, like:

@Test
@RunIf(DatabaseIsConnected.class)
public void calculateTotalSalary() {
    //your code there
}

class DatabaseIsConnected implements Checker {
   public boolean satisify() {
        return Database.connect() != null;
   }
}

[Code sample taken from their tutorial]

In Java how does one turn a String into a char or a char into a String?

String someString = "" + c;
char c = someString.charAt(0);

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

How to run Rake tasks from within Rake tasks?

If you want each task to run regardless of any failures, you can do something like:

task :build_all do
  [:debug, :release].each do |t| 
    ts = 0
    begin  
      Rake::Task["build"].invoke(t)
    rescue
      ts = 1
      next
    ensure
      Rake::Task["build"].reenable # If you need to reenable
    end
    return ts # Return exit code 1 if any failed, 0 if all success
  end
end

Why does Google prepend while(1); to their JSON responses?

It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.

Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script> tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.

The while(1); or &&&BLAH&&& prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.

This does not address the issue of cross-site request forgery.

rbenv not changing ruby version

I fixed this by adding the following to my ~/.bash_profile:

#PATH for rbenv
export PATH="$HOME/.rbenv/shims:$PATH"

This is what is documented at https://github.com/sstephenson/rbenv.

From what I can tell there isn't ~/.rbenv/bin directory, which was mentioned in the post by @rodowi.

Check element CSS display with JavaScript

For jQuery, do you mean like this?

$('#object').css('display');

You can check it like this:

if($('#object').css('display') === 'block')
{
    //do something
}
else
{
    //something else
}

How do I set a VB.Net ComboBox default value

You can try this:

Me.cbo1.Text = Me.Cbo1.Items(0).Tostring

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

ALTER TABLE add constraint

Omit the parenthesis:

ALTER TABLE User 
    ADD CONSTRAINT userProperties
    FOREIGN KEY(properties)
    REFERENCES Properties(ID)

var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

How to create a function in SQL Server

This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.

CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
    DECLARE @Work VARCHAR(250)

    SET @Work = @URL

    SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))   
    SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))

    --Alternate:
    --SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)   

    RETURN @work
END

Get parent of current directory from Python script

import os def parent_directory(): # Create a relative path to the parent # of the current working directory path = os.getcwd() parent = os.path.dirname(path)

relative_parent = os.path.join(path, parent)

# Return the absolute path of the parent directory
return relative_parent

print(parent_directory())

get index of DataTable column with name

I wrote an extension method of DataRow which gets me the object via the column name.

public static object Column(this DataRow source, string columnName)
{
    var c = source.Table.Columns[columnName];
    if (c != null)
    {
        return source.ItemArray[c.Ordinal];
    }

    throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}

And its called like this:

DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{        
    var obj = row.Column("YourColumnName");
    Console.WriteLine(obj);
}

Row names & column names in R

Just to expand a little on Dirk's example:

It helps to think of a data frame as a list with equal length vectors. That's probably why names works with a data frame but not a matrix.

The other useful function is dimnames which returns the names for every dimension. You will notice that the rownames function actually just returns the first element from dimnames.

Regarding rownames and row.names: I can't tell the difference, although rownames uses dimnames while row.names was written outside of R. They both also seem to work with higher dimensional arrays:

>a <- array(1:5, 1:4)
> a[1,,,]
> rownames(a) <- "a"
> row.names(a)
[1] "a"
> a
, , 1, 1    
  [,1] [,2]
a    1    2

> dimnames(a)
[[1]]
[1] "a"

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

How to pass integer from one Activity to another?

In Activity A

private void startSwitcher() {
    int yourInt = 200;
    Intent myIntent = new Intent(A.this, B.class);
    intent.putExtra("yourIntName", yourInt);
    startActivity(myIntent);
}

in Activity B

int score = getIntent().getIntExtra("yourIntName", 0);

How to save a pandas DataFrame table as a png

The solution of @bunji works for me, but default options don't always give a good result. I added some useful parameter to tweak the appearance of the table.

import pandas as pd
import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import numpy as np

dates = pd.date_range('20130101',periods=6)
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))

df.index = [item.strftime('%Y-%m-%d') for item in df.index] # Format date

fig, ax = plt.subplots(figsize=(12, 2)) # set size frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis
ax.set_frame_on(False)  # no visible frame, uncomment if size is ok
tabla = table(ax, df, loc='upper right', colWidths=[0.17]*len(df.columns))  # where df is your data frame
tabla.auto_set_font_size(False) # Activate set fontsize manually
tabla.set_fontsize(12) # if ++fontsize is necessary ++colWidths
tabla.scale(1.2, 1.2) # change size table
plt.savefig('table.png', transparent=True)

The result: Table

Copy / Put text on the clipboard with FireFox, Safari and Chrome

I have to say that none of these solutions really work. I have tried the clipboard solution from the accepted answer, and it does not work with Flash Player 10. I have also tried ZeroClipboard, and I was very happy with it for awhile.

I'm currently using it on my own site (http://www.blogtrog.com), but I've been noticing weird bugs with it. The way ZeroClipboard works is that it puts an invisible flash object over the top of an element on your page. I've found that if my element moves (like when the user resizes the window and i have things right aligned), the ZeroClipboard flash object gets out of whack and is no longer covering the object. I suspect it's probably still sitting where it was originally. They have code that's supposed to stop that, or restick it to the element, but it doesn't seem to work well.

So... in the next version of BlogTrog, I guess I'll follow suit with all the other code highlighters I've seen out in the wild and remove my Copy to Clipboard button. :-(

(I noticed that dp.syntaxhiglighter's Copy to Clipboard is broken now also.)

Python: avoiding pylint warnings about too many arguments

I do not like referring to the number, the sybolic name is much more expressive and avoid having to add a comment that could become obsolete over time.

So I'd rather do:

#pylint: disable-msg=too-many-arguments

And I would also recommend to not leave it dangling there: it will stay active until the file ends or it is disabled, whichever comes first.

So better doing:

#pylint: disable-msg=too-many-arguments
code_which_would_trigger_the_msg
#pylint: enable-msg=too-many-arguments    

I would also recommend enabling/disabling one single warning/error per line.

Anaconda version with Python 3.5

It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5

In general you can do this for any python package you want

conda install package_name=package_version

Regex to get the words after matching string

This might work out for you depending on which language you are using:

(?<=Object Name:).*

It's a positive lookbehind assertion. More information could be found here.

It won't work with JavaScript though. In your comment I read that you're using it for logstash. If you are using GROK parsing for logstash then it would work. You can verify it yourself here:

https://grokdebug.herokuapp.com/

Enter image description here

How to format LocalDate to string?

There is a built-in way to format LocalDate in Joda library

import org.joda.time.LocalDate;

LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);

In case you don't have it already - add this to the build.gradle:

implementation 'joda-time:joda-time:2.9.5'

Happy coding! :)

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

  1. Open your command prompt
  2. Navigate working directory to 1.8.0/bin
  3. paste keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
  4. Press enter if it ask you a password

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:

$ ps -ef|grep httpd
0     681     1   0 10:38pm ??         0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501   690   681   0 10:38pm ??         0:00.02 /Applications/MAMP/Library/bin/httpd -k start

...

Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)

$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.

Wait for crash... then:

(gdb) backtrace

Or

(gdb) backtrace full

Should give you some clue what's going on. If you file a bug report you should include the backtrace.

If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:

StartServers 1
MinSpareServers 1
MaxSpareServers 1

Python class inherits object

Is there any reason for a class declaration to inherit from object?

In Python 3, apart from compatibility between Python 2 and 3, no reason. In Python 2, many reasons.


Python 2.x story:

In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of object as a base-class:

  1. "classic" style classes: they don't have object as a base class:

    >>> class ClassicSpam:      # no base class
    ...     pass
    >>> ClassicSpam.__bases__
    ()
    
  2. "new" style classes: they have, directly or indirectly (e.g inherit from a built-in type), object as a base class:

    >>> class NewSpam(object):           # directly inherit from object
    ...    pass
    >>> NewSpam.__bases__
    (<type 'object'>,)
    >>> class IntSpam(int):              # indirectly inherit from object...
    ...    pass
    >>> IntSpam.__bases__
    (<type 'int'>,) 
    >>> IntSpam.__bases__[0].__bases__   # ... because int inherits from object  
    (<type 'object'>,)
    

Without a doubt, when writing a class you'll always want to go for new-style classes. The perks of doing so are numerous, to list some of them:

  • Support for descriptors. Specifically, the following constructs are made possible with descriptors:

    1. classmethod: A method that receives the class as an implicit argument instead of the instance.
    2. staticmethod: A method that does not receive the implicit argument self as a first argument.
    3. properties with property: Create functions for managing the getting, setting and deleting of an attribute.
    4. __slots__: Saves memory consumptions of a class and also results in faster attribute access. Of course, it does impose limitations.
  • The __new__ static method: lets you customize how new class instances are created.

  • Method resolution order (MRO): in what order the base classes of a class will be searched when trying to resolve which method to call.

  • Related to MRO, super calls. Also see, super() considered super.

If you don't inherit from object, forget these. A more exhaustive description of the previous bullet points along with other perks of "new" style classes can be found here.

One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, I doubt this would be an issue and it's a negative sinking in a sea of positives.


Python 3.x story:

In Python 3, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding object is requiring you to type in 8 more characters. This:

class ClassicSpam:
    pass

is completely equivalent (apart from their name :-) to this:

class NewSpam(object):
     pass

and to this:

class Spam():
    pass

All have object in their __bases__.

>>> [object in cls.__bases__ for cls in {Spam, NewSpam, ClassicSpam}]
[True, True, True]

So, what should you do?

In Python 2: always inherit from object explicitly. Get the perks.

In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.

How do I get the MAX row with a GROUP BY in LINQ query?

In methods chain form:

db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
    {
        Serial_Number = g.Key,
        uid = g.Max(row => row.uid)
    });

React Router v4 - How to get current route?

Here is a solution using history Read more

import { createBrowserHistory } from "history";

const history = createBrowserHistory()

inside Router

<Router>
   {history.location.pathname}
</Router>

HTML5 iFrame Seamless Attribute

You only need to write

seamless

in your code. There is not need for:

seamless ="seamless"

I just found this out myself.

EDIT - this does not remove scrollbars. Strangely

scrolling="no" still seems to work in html5. I have tried using the overflow function with an inline style as recommended by html5 but this doesn't work for me.

How to initialize const member variable in a class?

  1. You can upgrade your compiler to support C++11 and your code would work perfectly.

  2. Use initialization list in constructor.

    T1() : t( 100 )
    {
    }