Programs & Examples On #Youtube

YouTube is a video-sharing website on which users can upload, share, and view videos. StackOverflow questions tagged with "youtube" should be about specific programming problems, software tools, or libraries. If your question is about the YouTube API, the "youtube-api" tag should also be added.

How can I align YouTube embedded video in the center in bootstrap

An important thing to note / "Bootstrap" is just a bunch of CSS rules

a fiddle

HTML

<div class="your-centered-div">
    <img src="http://placehold.it/1120x630&text=Pretend Video 560x315" alt="" />
</div>


CSS

/* key stuff */
.your-centered-div {
    width: 560px; /* you have to have a size or this method doesn't work */
    height: 315px; /* think about making these max-width instead - might give you some more responsiveness */

    position: absolute; /* positions out of the flow, but according to the nearest parent */
    top: 0; right: 0; /* confuse it i guess */
    bottom: 0; left: 0;
    margin: auto; /* make em equal */
}

Fully working jsFiddle is here.

EDIT

I mostly use this these days:

straight CSS

.centered-thing {
    position: absolute;
    margin: auto;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

if your use stylus/mixins ( you should... it's the best )

center-center()
    absolute()
    margin auto
    top 50%
    left 50%
    transform translate(-50%,-50%)

This way... you don't need to know the size of the element - and the translate is based of it's size - So, -50% of itself. Neat.

Bootstrap 3 and Youtube in Modal

_x000D_
_x000D_
$('#videoLink').click(function () {_x000D_
    var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';_x000D_
    // $('#introVideo').modal('show'); <-- remove this line_x000D_
    $('#introVideo iframe').attr('src', src);_x000D_
});_x000D_
_x000D_
$('#introVideo button.close').on('hidden.bs.modal', function () {_x000D_
    $('#introVideo iframe').removeAttr('src');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- triggering Link -->_x000D_
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>_x000D_
_x000D_
<!-- Intro video -->_x000D_
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">_x000D_
  <div class="modal-dialog modal-lg">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <div class="embed-responsive embed-responsive-16by9">_x000D_
            <iframe class="embed-responsive-item allowfullscreen"></iframe>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

youtube: link to display HD video by default

Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.

Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080

What you get as a result is the standalone 1080p video but not in the Tube environment.

Android YouTube app Play Video Intent

And how about this:

public static void watchYoutubeVideo(Context context, String id){
    Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));
    Intent webIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://www.youtube.com/watch?v=" + id));
    try {
        context.startActivity(appIntent);
    } catch (ActivityNotFoundException ex) {
        context.startActivity(webIntent);
    }
} 

Note: Beware when you are using this method, YouTube may suspend your channel due to spam, this happened two times with me

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

How to embed YouTube videos in PHP?

If you want to upload videos programatically, check the YouTube Data API for PHP

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

How do I get the YouTube video ID from a URL?

You don't need to use a regular expression for this.

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
  video_id = video_id.substring(0, ampersandPosition);
}

YouTube URL in Video Tag

This will give you the answer you need. The easiest way to do it is with the youTube-provided methods. How to Embed Youtube Videos into HTML5 <video> Tag?

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

Okay this is an example for the new embed code for youtube videos.

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM" frameborder="0" allowFullScreen></iframe>

if you want to autoplay it, at the src="http://www.youtube.com/embed/8v_4O44sfjM" add the ?autoplay=1 parameter

So the code will look like this:

<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM?autoplay=1" frameborder="0" allowFullScreen></iframe>

i tried this on my blog and it works ! Hope this help (:

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.

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


YouTube embedded video: set different thumbnail

This solution is HTML and CSS based using z-index and hover, which works if JS is disabled or the video isn't yours (since you can add a thumbnail in YouTube).

<style>
.videoWrapper {
  position: relative;
  padding-bottom: 56.25%;
}
.videoWrapper .video-modal-poster img {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
.videoWrapper .video-modal-poster:hover img {
  z-index:0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
</style>
<div class="videoWrapper">
  <a href="#" class="video-modal-poster">
    <img alt="" src="" width="353" height="199" />
    <iframe width="353" height="199" src="https://www.youtube.com/embed/" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
  </a>
</div>

Embed Youtube video inside an Android app

Refer to this answer: How can we play YouTube embeded code in an Android application using webview?

It uses WebViews and loads an iframe in it... and yes it works.

How to extract closed caption transcript from YouTube video?

Another option is to use youtube-dl:

youtube-dl --skip-download --write-auto-sub $youtube_url

The default format is vtt and the other available format is ttml (--sub-format ttml).

--write-sub
       Write subtitle file

--write-auto-sub
       Write automatically generated subtitle file (YouTube only)

--all-subs
       Download all the available subtitles of the video

--list-subs
       List all available subtitles for the video

--sub-format FORMAT
       Subtitle format, accepts formats preference, for example: "srt" or "ass/srt/best"

--sub-lang LANGS
       Languages of the subtitles to download (optional) separated by commas, use --list-subs for available language tags

You can use ffmpeg to convert the subtitle file to another format:

ffmpeg -i input.vtt output.srt

This is what the VTT subtitles look like:

WEBVTT
Kind: captions
Language: en

00:00:01.429 --> 00:00:04.249 align:start position:0%

ladies<00:00:02.429><c> and</c><00:00:02.580><c> gentlemen</c><c.colorE5E5E5><00:00:02.879><c> I'd</c></c><c.colorCCCCCC><00:00:03.870><c> like</c></c><c.colorE5E5E5><00:00:04.020><c> to</c><00:00:04.110><c> thank</c></c>

00:00:04.249 --> 00:00:04.259 align:start position:0%
ladies and gentlemen<c.colorE5E5E5> I'd</c><c.colorCCCCCC> like</c><c.colorE5E5E5> to thank
 </c>

00:00:04.259 --> 00:00:05.930 align:start position:0%
ladies and gentlemen<c.colorE5E5E5> I'd</c><c.colorCCCCCC> like</c><c.colorE5E5E5> to thank
you<00:00:04.440><c> for</c><00:00:04.620><c> coming</c><00:00:05.069><c> tonight</c><00:00:05.190><c> especially</c></c><c.colorCCCCCC><00:00:05.609><c> at</c></c>

00:00:05.930 --> 00:00:05.940 align:start position:0%
you<c.colorE5E5E5> for coming tonight especially</c><c.colorCCCCCC> at
 </c>

00:00:05.940 --> 00:00:07.730 align:start position:0%
you<c.colorE5E5E5> for coming tonight especially</c><c.colorCCCCCC> at
such<00:00:06.180><c> short</c><00:00:06.690><c> notice</c></c>

00:00:07.730 --> 00:00:07.740 align:start position:0%
such short notice


00:00:07.740 --> 00:00:09.620 align:start position:0%
such short notice
I'm<00:00:08.370><c> sure</c><c.colorE5E5E5><00:00:08.580><c> mr.</c><00:00:08.820><c> Irving</c><00:00:09.000><c> will</c><00:00:09.120><c> fill</c><00:00:09.300><c> you</c><00:00:09.389><c> in</c><00:00:09.420><c> on</c></c>

00:00:09.620 --> 00:00:09.630 align:start position:0%
I'm sure<c.colorE5E5E5> mr. Irving will fill you in on
 </c>

00:00:09.630 --> 00:00:11.030 align:start position:0%
I'm sure<c.colorE5E5E5> mr. Irving will fill you in on
the<00:00:09.750><c> circumstances</c><00:00:10.440><c> that's</c><00:00:10.620><c> brought</c><00:00:10.920><c> us</c></c>

00:00:11.030 --> 00:00:11.040 align:start position:0%
<c.colorE5E5E5>the circumstances that's brought us
 </c>

Here are the same subtitles without the part at the top of the file and without tags:

00:00:01.429 --> 00:00:04.249 align:start position:0%

ladies and gentlemen I'd like to thank

00:00:04.249 --> 00:00:04.259 align:start position:0%
ladies and gentlemen I'd like to thank


00:00:04.259 --> 00:00:05.930 align:start position:0%
ladies and gentlemen I'd like to thank
you for coming tonight especially at

00:00:05.930 --> 00:00:05.940 align:start position:0%
you for coming tonight especially at


00:00:05.940 --> 00:00:07.730 align:start position:0%
you for coming tonight especially at
such short notice

00:00:07.730 --> 00:00:07.740 align:start position:0%
such short notice


00:00:07.740 --> 00:00:09.620 align:start position:0%
such short notice
I'm sure mr. Irving will fill you in on

00:00:09.620 --> 00:00:09.630 align:start position:0%
I'm sure mr. Irving will fill you in on


00:00:09.630 --> 00:00:11.030 align:start position:0%
I'm sure mr. Irving will fill you in on
the circumstances that's brought us

You can see that each subtitle text is repeated three times. There is a new subtitle text every eighth line (3rd, 11th, 19th, and 27th).

This converts the VTT subtitles to a simpler format:

sed '1,/^$/d' *.vtt| # remove the part at the top
sed 's/<[^>]*>//g'| # remove tags
awk -F. 'NR%8==1{printf"%s ",$1}NR%8==3' # print each new subtitle text and its start time without milliseconds

This is what the output of the command above looks like:

00:00:01 ladies and gentlemen I'd like to thank
00:00:04 you for coming tonight especially at
00:00:05 such short notice
00:00:07 I'm sure mr. Irving will fill you in on
00:00:09 the circumstances that's brought us

This prints the closed captions of a video in the simplified format:

cap()(cd /tmp;rm -f -- *.vtt;youtube-dl --skip-download --write-auto-sub -- "$1";sed '1,/^$/d' -- *.vtt|sed 's/<[^>]*>//g'|awk -F. 'NR%8==1{printf"%s ",$1}NR%8==3')

The command below downloads the captions of all videos on a channel. When there is an error like Unable to extract video data, -i (--ignore-errors) causes youtube-dl to skip the video instead of exiting with an error.

youtube-dl -i --skip-download --write-auto-sub -o '%(upload_date)s.%(title)s.%(id)s.%(ext)s' https://www.youtube.com/channel/$channelid;for f in *.vtt;do sed '1,/^$/d' "$f"|sed 's/<[^>]*>//g'|awk -F. 'NR%8==1{printf"%s ",$1}NR%8==3'>"${f%.vtt}";done

Youtube - How to force 480p video quality in embed link / <iframe>

You can use the YouTube JavaScript player API, which has a feature on its own to set playback quality.

player.setPlaybackQuality(suggestedQuality:String):Void

This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function. [source]

Force youtube embed to start in 720p

(This answer was updated, as the previous method using vq isn't recognized anymore.)

Specifying the height of the video will change the quality accordingly. example for html 5;

<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>

If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.

Tested on a working server + passes the w3.org nuhtml validator.

How do you use youtube-dl to download live streams (that are live)?

There is no need to pass anything to ffmpeg you can just grab the desired format, in this example, it was the "95" format.

So once you know that it is the 95, you just type:

youtube-dl -f 95  https://www.youtube.com/watch\?v\=6aXR-SL5L2o

that is to say:

youtube-dl -f <format number> <url>

It will begin generating on the working directory a <somename>.<probably mp4>.part which is the partially downloaded file, let it go and just press <Ctrl-C> to stop the capture.

The file will still be named <something>.part, rename it to <whatever>.mp4 and there it is...

The ffmpeg code:

ffmpeg -i $(youtube-dl -f <format number> -g <url>) -copy <file_name>.ts

also worked for me, but sound and video got out of sync, using just youtube-dl seemed to yield a better result although it too uses ffmpeg.

The downside of this approach is that you cannot watch the video while downloading, well you can open yet another FF or Chrome, but it seems that mplayer cannot process the video output till youtube-dl/ffmpeg are running.

Stop a youtube video with jquery?

Actually you only need javascript and build the embed of the youtube video correctly with swfobject google library

This is an example

<script type="text/javascript" src="swfobject.js"></script>    
<div style="width: 425; height: 356px;">
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>      
  <script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/y5whWXxGHUA?enablejsapi=1&playerapiid=ytplayer&version=3",
    "ytapiplayer", "425", "356", "8", null, null, params, atts);
  </script>
</div> 

After that you can call this functions:

ytplayer = document.getElementById("myytplayer");
ytplayer.playVideo();
ytplayer.pauseVideo();
ytplayer.stopVideo();

How to play YouTube video in my Android application?

I didn't want to have to have the YouTube app present on the device so I used this tutorial:

http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html

...to produce this code in my app:

WebView mWebView; 

@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.video_webview);
    mWebView=(WebView)findViewById(R.id.videoview);

    //build your own src link with your video ID
    String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
        }
    });
    WebSettings ws = mWebView.getSettings();
    ws.setJavaScriptEnabled(true);
    mWebView.loadData(videoStr, "text/html", "utf-8");

}

//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:background="#000000"
    android:id="@+id/bmp_programme_ll"
    android:orientation="vertical" >

   <WebView
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />  
</LinearLayout>     

This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.

Shrink a YouTube video to responsive width

I make this with simple css as follows

HTML CODE

<iframe id="vid" src="https://www.youtube.com/embed/RuD7Se9jMag" frameborder="0" allowfullscreen></iframe>

CSS CODE

<style type="text/css">
#vid {

max-width: 100%;
height: auto;

}

Open youtube video in Fancybox jquery

If you wanna add autoplay function to it. Simply replace

this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 

with

this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',

also you can do the same with vimeo

this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),

with

this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

I'm going to add to the answer given before.

It's not a bug in your code or the browser's code. It's the JavaScript code inside the YouTube iframe polls for the extensions it could interoperate with in case they were installed (likely to determine if the extension is installed).

Look at the source of www-embed-player.js (loaded from s.ytimg.com, it's YouTube static files CDN). You'll find the following:

function Wj(a){return"chrome-extension://"+a+"/cast_sender.js"}

start/play embedded (iframe) youtube-video on click of an image

Example youtube iframe

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

The click to play HTML element

<div class="videoplay">Play</div> 

jQuery code to play the Video

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

Thanks to https://codepen.io/martinwolf/pen/dyLAC

YouTube API to fetch all videos on a channel

Recently I had to retrieve all videos from a channel, and according to YouTube developer documentation: https://developers.google.com/youtube/v3/docs/playlistItems/list

function playlistItemsListByPlaylistId($service, $part, $params) {
    $params = array_filter($params);
    $response = $service->playlistItems->listPlaylistItems(
        $part,
        $params
    );

    print_r($response);
}

playlistItemsListByPlaylistId($service,
    'snippet,contentDetails',
    array('maxResults' => 25, 'playlistId' => 'id of "uploads" playlist'));

Where $service is your Google_Service_YouTube object.

So you have to fetch information from the channel to retrieve the "uploads" playlist that actually has all the videos uploaded by the channel: https://developers.google.com/youtube/v3/docs/channels/list

If new with this API, I highly recommend to turn the code sample from the default snippet to the full sample.

So the basic code to retrieve all videos from a channel can be:

class YouTube
{
    const       DEV_KEY = 'YOUR_DEVELOPPER_KEY';
    private     $client;
    private     $youtube;
    private     $lastChannel;

    public function __construct()
    {
        $this->client = new Google_Client();
        $this->client->setDeveloperKey(self::DEV_KEY);
        $this->youtube = new Google_Service_YouTube($this->client);
        $this->lastChannel = false;
    }

    public function getChannelInfoFromName($channel_name)
    {
        if ($this->lastChannel && $this->lastChannel['modelData']['items'][0]['snippet']['title'] == $channel_name)
        {
            return $this->lastChannel;
        }
        $this->lastChannel = $this->youtube->channels->listChannels('snippet, contentDetails, statistics', array(
            'forUsername' => $channel_name,
        ));
        return ($this->lastChannel);
    }

    public function getVideosFromChannelName($channel_name, $max_result = 5)
    {
        $this->getChannelInfoFromName($channel_name);
        $params = [
            'playlistId' => $this->lastChannel['modelData']['items'][0]['contentDetails']['relatedPlaylists']['uploads'],
            'maxResults'=> $max_result,
        ];
        return ($this->youtube->playlistItems->listPlaylistItems('snippet,contentDetails', $params));
    }
}

$yt = new YouTube();
echo '<pre>' . print_r($yt->getVideosFromChannelName('CHANNEL_NAME'), true) . '</pre>';

Youtube - downloading a playlist - youtube-dl

I found the best solution after many attempts for this problem.

youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}

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

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

YouTube: How to present embed video with sound muted

Updated

Add &mute=1 to the end of your url.

Your new code would be:

_x000D_
_x000D_
<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?rel=0&amp;autoplay=1&mute=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
_x000D_
_x000D_
_x000D_

How do I get a YouTube video thumbnail from the YouTube API?

Use img.youtube.com/vi/YouTubeID/ImageFormat.jpg

Here image formats are different like default, hqdefault, maxresdefault.

Embed HTML5 YouTube video without iframe?

Use the object tag:

<object data="http://iamawesome.com" type="text/html" width="200" height="200">
  <a href="http://iamawesome.com">access the page directly</a>
</object>

Ref: http://debug.ga/embedding-external-pages-without-iframes/

Can you hide the controls of a YouTube embed without enabling autoplay?

use autoplay=0

autoplay takes 2 values.

Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

the important part

autoplay=0&showinfo=0&controls=0

Here is the demo for ur problem FIDDLE

How to play only the audio of a Youtube video using HTML 5?

Embed the video player and use CSS to hide the video. If you do it properly you may even be able to hide only the video and not the controls below it.

However, I'd recommend against it, because it will be a violation of YouTube TOS. Use your own server instead if you really want to play only audio.

How can I get a channel ID from YouTube?

To get Channel id

Ex: Apple channel ID

enter image description here

Select any of the video in that channel

enter image description here

Select iPhone - Share photos (video)

Now click on channel name Apple bottom of the video.

enter image description here

Now you will get channel id in browser url

enter image description here

Here this is Apple channel id : UCE_M8A5yxnLfW0KghEeajjw

YouTube Autoplay not working

It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes

<iframe id="existing-iframe-example"
          width="640" height="360"
          src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
          frameborder="0"
          style="border: solid 4px #37474F"
          ></iframe>

Update :

Audio/Video Updates in Chrome 73

Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa

Properly embedding Youtube video into bootstrap 3.0 page

I know it's late, I have the same issue with an old custom theme, just added to boostrap.css:

.embed-responsive {
  position: relative;
  display: block;
  height: 0;
  padding: 0;
  overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}
.embed-responsive-16by9 {
  padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
  padding-bottom: 75%;
}

And for the video:

<div class="embed-responsive embed-responsive-16by9" >
<iframe class="embed-responsive-item"  src="https://www.youtube.com/embed/jVIxe3YLNs8"></iframe>
</div>

Code for download video from Youtube on Java, Android

3 steps:

  1. Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);

  2. Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;

  3. Use the code to download stream:

    URL u = null;
    InputStream is = null;  
    
    try {
        u = new URL(url);
        is = u.openStream(); 
        HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
        int size = huc.getContentLength();                 
    
        if(huc != null) {
            String fileName = "FILE.mp4";
            String storagePath = Environment.getExternalStorageDirectory().toString();
            File f = new File(storagePath,fileName);
    
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            if(is != null) {
                while ((len1 = is.read(buffer)) > 0) {
                    fos.write(buffer,0, len1);  
                }
            }
            if(fos != null) {
                fos.close();
            }
        }                       
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {               
            if(is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    

That's all, most of stuff you'll find on the web!!!

How to download videos from youtube on java?

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class JavaYoutubeDownloader {

 public static String newline = System.getProperty("line.separator");
 private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
 private static final Level defaultLogLevelSelf = Level.FINER;
 private static final Level defaultLogLevel = Level.WARNING;
 private static final Logger rootlog = Logger.getLogger("");
 private static final String scheme = "http";
 private static final String host = "www.youtube.com";
 private static final Pattern commaPattern = Pattern.compile(",");
 private static final Pattern pipePattern = Pattern.compile("\\|");
 private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };

 private static void usage(String error) {
  if (error != null) {
   System.err.println("Error: " + error);
  }
  System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
  System.exit(-1);
 }

 public static void main(String[] args) {
  if (args == null || args.length == 0) {
   usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
  }
  try {
   setupLogging();

   log.fine("Starting");
   String videoId = null;
   String outdir = ".";
   // TODO Ghetto command line parsing
   if (args.length == 1) {
    videoId = args[0];
   } else if (args.length == 2) {
    videoId = args[0];
    outdir = args[1];
   }

   int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
   String encoding = "UTF-8";
   String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
   File outputDir = new File(outdir);
   String extension = getExtension(format);

   play(videoId, format, encoding, userAgent, outputDir, extension);

  } catch (Throwable t) {
   t.printStackTrace();
  }
  log.fine("Finished");
 }

 private static String getExtension(int format) {
  // TODO
  return "mp4";
 }

 private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
  log.fine("Retrieving " + videoId);
  List<NameValuePair> qparams = new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("video_id", videoId));
  qparams.add(new BasicNameValuePair("fmt", "" + format));
  URI uri = getUri("get_video_info", qparams);

  CookieStore cookieStore = new BasicCookieStore();
  HttpContext localContext = new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

  HttpClient httpclient = new DefaultHttpClient();
  HttpGet httpget = new HttpGet(uri);
  httpget.setHeader("User-Agent", userAgent);

  log.finer("Executing " + uri);
  HttpResponse response = httpclient.execute(httpget, localContext);
  HttpEntity entity = response.getEntity();
  if (entity != null && response.getStatusLine().getStatusCode() == 200) {
   InputStream instream = entity.getContent();
   String videoInfo = getStringFromInputStream(encoding, instream);
   if (videoInfo != null && videoInfo.length() > 0) {
    List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
    URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
    String token = null;
    String downloadUrl = null;
    String filename = videoId;

    for (NameValuePair pair : infoMap) {
     String key = pair.getName();
     String val = pair.getValue();
     log.finest(key + "=" + val);
     if (key.equals("token")) {
      token = val;
     } else if (key.equals("title")) {
      filename = val;
     } else if (key.equals("fmt_url_map")) {
      String[] formats = commaPattern.split(val);
      for (String fmt : formats) {
       String[] fmtPieces = pipePattern.split(fmt);
       if (fmtPieces.length == 2) {
        // in the end, download somethin!
        downloadUrl = fmtPieces[1];
        int pieceFormat = Integer.parseInt(fmtPieces[0]);
        if (pieceFormat == format) {
         // found what we want
         downloadUrl = fmtPieces[1];
         break;
        }
       }
      }
     }
    }

    filename = cleanFilename(filename);
    if (filename.length() == 0) {
     filename = videoId;
    } else {
     filename += "_" + videoId;
    }
    filename += "." + extension;
    File outputfile = new File(outputdir, filename);

    if (downloadUrl != null) {
     downloadWithHttpClient(userAgent, downloadUrl, outputfile);
    }
   }
  }
 }

 private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
  HttpGet httpget2 = new HttpGet(downloadUrl);
  httpget2.setHeader("User-Agent", userAgent);

  log.finer("Executing " + httpget2.getURI());
  HttpClient httpclient2 = new DefaultHttpClient();
  HttpResponse response2 = httpclient2.execute(httpget2);
  HttpEntity entity2 = response2.getEntity();
  if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
   long length = entity2.getContentLength();
   InputStream instream2 = entity2.getContent();
   log.finer("Writing " + length + " bytes to " + outputfile);
   if (outputfile.exists()) {
    outputfile.delete();
   }
   FileOutputStream outstream = new FileOutputStream(outputfile);
   try {
    byte[] buffer = new byte[2048];
    int count = -1;
    while ((count = instream2.read(buffer)) != -1) {
     outstream.write(buffer, 0, count);
    }
    outstream.flush();
   } finally {
    outstream.close();
   }
  }
 }

 private static String cleanFilename(String filename) {
  for (char c : ILLEGAL_FILENAME_CHARACTERS) {
   filename = filename.replace(c, '_');
  }
  return filename;
 }

 private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
  URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
  return uri;
 }

 private static void setupLogging() {
  changeFormatter(new Formatter() {
   @Override
   public String format(LogRecord arg0) {
    return arg0.getMessage() + newline;
   }
  });
  explicitlySetAllLogging(Level.FINER);
 }

 private static void changeFormatter(Formatter formatter) {
  Handler[] handlers = rootlog.getHandlers();
  for (Handler handler : handlers) {
   handler.setFormatter(formatter);
  }
 }

 private static void explicitlySetAllLogging(Level level) {
  rootlog.setLevel(Level.ALL);
  for (Handler handler : rootlog.getHandlers()) {
   handler.setLevel(defaultLogLevelSelf);
  }
  log.setLevel(level);
  rootlog.setLevel(defaultLogLevel);
 }

 private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
  Writer writer = new StringWriter();

  char[] buffer = new char[1024];
  try {
   Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
   int n;
   while ((n = reader.read(buffer)) != -1) {
    writer.write(buffer, 0, n);
   }
  } finally {
   instream.close();
  }
  String result = writer.toString();
  return result;
 }
}

/**
 * <pre>
 * Exploded results from get_video_info:
 * 
 * fexp=90...
 * allow_embed=1
 * fmt_stream_map=35|http://v9.lscache8...
 * fmt_url_map=35|http://v9.lscache8...
 * allow_ratings=1
 * keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
 * track_embed=0
 * fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * author=lukebessey
 * muted=0
 * length_seconds=390
 * plid=AA...
 * ftoken=null
 * status=ok
 * watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
 * timestamp=12...
 * has_cc=False
 * fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
 * leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
 * hl=en_US
 * endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
 * vq=auto
 * avg_rating=5.0
 * video_id=S6IZP3yRJ9I
 * token=vPpcFNh...
 * thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
 * title=The Story of Our Unenslavement - Animated
 * </pre>
 */

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!

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

I had this same problem and it turns out it was because I had the Chrome extension "HTTPS Everywhere" running. Disabling the extension solved my problem.

How to make an embedded Youtube video automatically start playing?

<iframe title='YouTube video player' class='youtube-player' type='text/html'
        width='030' height='030'
        src='http://www.youtube.com/embed/ZFo8b9DbcMM?rel=0&border=&autoplay=1'
        type='application/x-shockwave-flash'
        allowscriptaccess='always' allowfullscreen='true'
        frameborder='0'></iframe>

just insert your code after embed/

YouTube Video Embedded via iframe Ignoring z-index?

Joshc's answer was on the right track, but I found that it totally deletes the ?rel=0 querystring and replaces it with the ?wmode=transparent item - which has the effect of displaying the YouTube Suggested Videos list at the end of the playback, even though you originally didn't want this to happen.

I changed the code so that the src attribute of the embedded video is scanned first, to see if there is a question mark ? in it already (because this denotes the presence of a pre-existing query string, which might be something like ?rel=0 but could in theory be anything that YouTube choose to append in the future). If there's a query string already there, we want to preserve it, not destroy it, because it represents a setting chosen by whoever pasted in this YouTube video, and they presumably chose it for a reason!

So, if ? is found, the wmode=transparent will be appended using the format: &mode=transparent to just tag it on the end of the pre-existing query string.

If no ? is found, then the code will work in exactly the same way as it did originally (in toomanyairmiles's post), appending just ?wmode=transparent as a new query string to the URL.

Now, regardless of what may or may not be on the end of the YouTube URL as a query string already, it gets preserved, and the required wmode parameters get injected or added without damage to what was there before.

Here's the code to drop into your document.ready function:

$('iframe').each(function() {
  var url = $(this).attr("src");
  if (url.indexOf("?") > 0) {
    $(this).attr({
      "src" : url + "&wmode=transparent",
      "wmode" : "opaque"
    });
  }
  else {
    $(this).attr({
      "src" : url + "?wmode=transparent",
      "wmode" : "opaque"
    });
  }
});

Downloading video from YouTube

I suggest you to take a look into SharpGrabber - a .NET Standard library I've written just for this purpose. It is newer than YouTubeExtractor and libvideo. It supports YouTube and Instagram as the time of this answer. This project also offers high-quality video and audio muxing and a cross-platform desktop application.

How do I automatically play a Youtube video (IFrame API) muted?

The player_api will be deprecated on Jun 25, 2015. For play youtube videos there is a new api IFRAME_API

It looks like the following code:

<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

How to hide the bar at the top of "youtube" even when mouse hovers over it?

Open youtube video. Click on share option. In share option click on embed tag. You can see in embed tag there is some check box. Unchecked on show video title and player actions. After this just copy frame tag.

<iframe width="100%" height="350" src="https://www.youtube.com/embed/uqhnxAjK7qY?autoplay=1&showinfo=0" frameborder="0" allowfullscreen></iframe>

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

Along with the embed, I also had to install the Google Cast extension in my browser.

<iframe width="1280" height="720" src="https://www.youtube.com/embed/4u856utdR94" frameborder="0" allowfullscreen></iframe>

How to customize an end time for a YouTube video?

Today I found, that the old ways are not working very well.

So I used: "Customize YouTube Start and End Time - Acetrot.com" from http://www.youtubestartend.com/

They provide a link into https://xxxx.app.goo.gl/yyyyyyyyyy e.g. https://v637g.app.goo.gl/Cs2SV9NEeoweNGGy9 Link contain forward to format like this https://www.youtube.com/embed/xyzabc123?start=17&end=21&version=3&autoplay=1

How to embed an autoplaying YouTube video in an iframe?

at the end of the iframe src, add &enablejsapi=1 to allow the js API to be used on the video

and then with jquery:

jQuery(document).ready(function( $ ) {
  $('.video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
});

this should play the video automatically on document.ready

note, that you could also use this inside a click function to click on another element to start the video

More importantly, you cannot auto-start videos on a mobile device so users will always have to click on the video-player itself to start the video

Edit: I'm actually not 100% sure on document.ready the iframe will be ready, because YouTube could still be loading the video. I'm actually using this function inside a click function:

$('.video-container').on('click', function(){
  $('video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  // add other code here to swap a custom image, etc
});

Youtube iframe wmode issue

&wmode=opaque didn't work for me (chrome 10) but &amp;wmode=transparent cleared the issue right up.

Youtube autoplay not working on mobile devices with embedded HTML5 player

There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.

Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.

Getting an Embedded YouTube Video to Auto Play and Loop

Here is the full list of YouTube embedded player parameters.

Relevant info:

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

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

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

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

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

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.

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>

ffprobe or avprobe not found. Please install one

brew install ffmpeg will install what you need and all the dependencies if you are on a Mac.

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
      ],

Show Youtube video source into HTML5 video tag?

I have created a realtively small (4.89 KB) javascript library for this exact functionality.

Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/

It's as simple as:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/

What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.

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

Adding a link with the thumbnail, originally used by YouTube is a solution, that works. The thumbnail, used by YouTube is accessible the following way:

  • if the official video link is: https://www.youtube.com/watch?v=5yLzZikS15k
  • then the thumbnail is: https://img.youtube.com/vi/5yLzZikS15k/0.jpg

Following this logic, the code below produces flawless results:

_x000D_
_x000D_
<div align="left">
      <a href="https://www.youtube.com/watch?v=5yLzZikS15k">
         <img src="https://img.youtube.com/vi/5yLzZikS15k/0.jpg" style="width:100%;">
      </a>
</div>
_x000D_
_x000D_
_x000D_

jQuery document.createElement equivalent?

var div = $('<div/>');
div.append('Hello World!');

Is the shortest/easiest way to create a DIV element in jQuery.

Simplest way to set image as JPanel background

As I know the way you can do it is to override paintComponent method that demands to inherit JPanel

 @Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); // paint the background image and scale it to fill the entire space
    g.drawImage(/*....*/);
}

The other way (a bit complicated) to create second custom JPanel and put is as background for your main

ImagePanel

public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;

public ImagePanel(Image image)
{
    this.image = image;
    this.iWidth2 = image.getWidth(this)/2;
    this.iHeight2 = image.getHeight(this)/2;
}


public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    if (image != null)
    {
        int x = this.getParent().getWidth()/2 - iWidth2;
        int y = this.getParent().getHeight()/2 - iHeight2;
        g.drawImage(image,x,y,this);
    }
}
}

EmptyPanel

public class EmptyPanel extends JPanel{

private static final long serialVersionUID = 1L;

public EmptyPanel() {
    super();
    init();
}

@Override
public boolean isOptimizedDrawingEnabled() {
    return false;
}


public void init(){

    LayoutManager overlay = new OverlayLayout(this);
    this.setLayout(overlay);

    ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
    iPanel.setLayout(new BorderLayout());   
    this.add(iPanel);
    iPanel.setOpaque(false);                
}
}

IconToImage

public class IconToImage {

Icon icon;
Image image;


public IconToImage(Icon icon) {
    this.icon = icon;
    image = iconToImage();
}

public Image iconToImage() { 
    if (icon instanceof ImageIcon) { 
        return ((ImageIcon)icon).getImage(); 
    } else { 
        int w = icon.getIconWidth(); 
        int h = icon.getIconHeight(); 
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
        GraphicsDevice gd = ge.getDefaultScreenDevice(); 
        GraphicsConfiguration gc = gd.getDefaultConfiguration(); 
        BufferedImage image = gc.createCompatibleImage(w, h); 
        Graphics2D g = image.createGraphics(); 
        icon.paintIcon(null, g, 0, 0); 
        g.dispose(); 
        return image; 
    } 
}


/**
 * @return the image
 */
public Image getImage() {
    return image;
}
}

Wait until all jQuery Ajax requests are done?

jQuery now defines a when function for this purpose.

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    // the code here will be executed when all four ajax requests resolve.
    // a1, a2, a3 and a4 are lists of length 3 containing the response text,
    // status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
    // NOTE:  This function must return the value 
    //        from calling the $.ajax() method.
    return $.ajax({
        url: "someUrl",
        dataType: "json",
        data:  yourJsonData,            
        ...
    });
}

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

Is there a way to represent a directory tree in a Github README.md?

Here is a useful git alias that works for me.

git config --global alias.tree '! git ls-tree --full-name --name-only -t -r HEAD | sed -e "s/[^-][^\/]*\//   |/g" -e "s/|\([^ ]\)/|-- \1/"'

Here is the output of git tree

jonavon@XPS13:~/projects/roman-numerals$ git tree
.gitignore
pom.xml
src
   |-- main
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- AbstractFile.java
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Main.java
   |   |   |   |   |   |   |-- Numeral.java
   |   |   |   |   |   |   |-- RomanNumberInputFile.java
   |   |   |   |   |   |   |-- RomanNumeralToDecimalEvaluator.java
   |-- test
   |   |-- java
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- InterpretSteps.java
   |   |   |   |   |   |   |-- RunCukesTest.java
   |   |-- resources
   |   |   |-- com
   |   |   |   |-- foxguardsolutions
   |   |   |   |   |-- jonavon
   |   |   |   |   |   |-- roman
   |   |   |   |   |   |   |-- Interpret.feature
   |   |   |-- sample-input.txt

The comparable tree command

jonavon@XPS13:~/projects/roman-numerals$ tree -n
.
+-- pom.xml
+-- src
¦   +-- main
¦   ¦   +-- java
¦   ¦       +-- com
¦   ¦           +-- foxguardsolutions
¦   ¦               +-- jonavon
¦   ¦                   +-- AbstractFile.java
¦   ¦                   +-- roman
¦   ¦                       +-- Main.java
¦   ¦                       +-- Numeral.java
¦   ¦                       +-- RomanNumberInputFile.java
¦   ¦                       +-- RomanNumeralToDecimalEvaluator.java
¦   +-- test
¦       +-- java
¦       ¦   +-- com
¦       ¦       +-- foxguardsolutions
¦       ¦           +-- jonavon
¦       ¦               +-- roman
¦       ¦                   +-- InterpretSteps.java
¦       ¦                   +-- RunCukesTest.java
¦       +-- resources
¦           +-- com
¦           ¦   +-- foxguardsolutions
¦           ¦       +-- jonavon
¦           ¦           +-- roman
¦           ¦               +-- Interpret.feature
¦           +-- sample-input.txt
+-- target
    +-- classes
    ¦   +-- com
    ¦       +-- foxguardsolutions
    ¦           +-- jonavon
    ¦               +-- AbstractFile.class
    ¦               +-- roman
    ¦                   +-- Main.class
    ¦                   +-- Numeral.class
    ¦                   +-- RomanNumberInputFile.class
    ¦                   +-- RomanNumeralToDecimalEvaluator.class
    +-- generated-sources
    ¦   +-- annotations
    +-- maven-status
        +-- maven-compiler-plugin
            +-- compile
                +-- default-compile
                    +-- createdFiles.lst
                    +-- inputFiles.lst

30 directories, 17 files

Clearly tree has better output, but I would like it to use my .gitignore file. So that my compiled content doesn't show

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Inserting data into a temporary table

INSERT INTO #TempTable(ID, Date, Name)
SELECT OtherID, OtherDate, OtherName FROM PhysicalTable

How to get named excel sheets while exporting from SSRS

To export to different sheets and use custom names, as of SQL Server 2008 R2 this can be done using a combination of grouping, page breaks and the PageName property of the group.

Alternatively, if it's just the single sheet that you'd like to give a specific name, try the InitialPageName property on the report.

For a more detailed explanation, have a look here: http://blog.hoegaerden.be/2011/03/23/where-the-sheets-have-a-name-ssrs-excel-export/

Share link on Google+

New Google share link: http://plus.google.com/share?url=YOUR_URL

For secure connection:

https://plus.google.com/share?url=YOUR_URL

For Wordpress:

https://plus.google.com/share?url=<?php the_permalink(); ?>

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How can I generate a list of files with their absolute path in Linux?

If you give find an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:

find "$(pwd)" -name .htaccess

or if your shell expands $PWD to the current directory:

find "$PWD" -name .htaccess

find simply prepends the path it was given to a relative path to the file from that path.

Greg Hewgill also suggested using pwd -P if you want to resolve symlinks in your current directory.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

How does "FOR" work in cmd batch file?

This works for me:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
@REM insure path is terminated with a ;
set tpath=%path%;
echo.
:again
@REM This FOR statement grabs the first element in the path
FOR /F "delims=;" %%I IN ("%TPATH%") DO (
  echo    %%I 
  @REM remove the current element of the path
  set TPATH=!TPATH:%%I;=!
)
@REM loop back if there is more to do. 
IF DEFINED TPATH GOTO :again

ENDLOCAL

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Ansible: deploy on multiple hosts in the same time

As mentioned before: By default Ansible will attempt to run on all hosts in parallel, but task after Task(serial).

If you also want to run Tasks in parallel you have to start different instances of ansible. Here are some ways to to it.

1. Groups

If you already have different groups you can run one ansible instance for each group:

shell-1 #> ansible-playbook site.yml --limit webservers
shell-2 #> ansible-playbook site.yml --limit dbservers
shell-3 #> ansible-playbook site.yml --limit load_balancers

2. Multiple shells

Playbooks

If your playbooks work standalone you can although do this:

shell-1 #> ansible-playbook load_balancers.yml
shell-2 #> ansible-playbook webservers.yml
shell-3 #> ansible-playbook dbservers.yml

Limit

If not, you can let ansible do the fragmentation. When you have 6 hosts and want to run 3 instances with 2 host each, you can do something like this:

shell-1 #> ansible-playbook site.yml --limit all[0-2]
shell-2 #> ansible-playbook site.yml --limit all[2-4]
shell-3 #> ansible-playbook site.yml --limit all[4-6]

3. Background

Of course you can use one shell and put the tasks in background, an simple example would be:

shell-1 #> ansible-playbook site.yml --limit all[0-2] &
shell-1 #> ansible-playbook site.yml --limit all[2-4] &
shell-1 #> ansible-playbook site.yml --limit all[4-6] &

With this method you get all output mixed together in one terminal. To avoid this you can write the output to different files.

ansible-playbook site.yml --limit all[0-2] > log1 &
ansible-playbook site.yml --limit all[2-4] > log2 &
ansible-playbook site.yml --limit all[4-6] > log3 &

4. Better Solutions

Maybe it's better to use a tool like tmux / screen to start the instances in virtual shells.

Or have a look at the "fireball mode": http://jpmens.net/2012/10/01/dramatically-speeding-up-ansible-runs/

If you want to know more about limits, look here: https://docs.ansible.com/playbooks_best_practices.html#what-this-organization-enables-examples

Bash: infinite sleep (infinite blocking)

sleep infinity does exactly what it suggests and works without cat abuse.

HTML5 Local storage vs. Session storage

localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.

That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.

ASP.Net MVC: How to display a byte array image from model

Something like this may work...

@{
    var base64 = Convert.ToBase64String(Model.ByteArray);
    var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
}

<img src="@imgSrc" />

As mentioned in the comments below, please use the above armed with the knowledge that although this may answer your question it may not solve your problem. Depending on your problem this may be the solution but I wouldn't completely rule out accessing the database twice.

Javascript negative number

function negative(n) {
  return n < 0;
}

Your regex should work fine for string numbers, but this is probably faster. (edited from comment in similar answer above, conversion with +n is not needed.)

Output of git branch in tree like fashion

You can use a tool called gitk.

How can I generate an MD5 hash?

 import java.math.BigInteger;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;

/**
* MD5 encryption
*
* @author Hongten
*
*/
public class MD5 {

 public static void main(String[] args) {
     System.out.println(MD5.getMD5("123456"));
 }

 /**
  * Use md5 encoded code value
  *
  * @param sInput
  * clearly
  * @ return md5 encrypted password
  */
 public static String getMD5(String sInput) {

     String algorithm = "";
     if (sInput == null) {
         return "null";
     }
     try {
         algorithm = System.getProperty("MD5.algorithm", "MD5");
     } catch (SecurityException se) {
     }
     MessageDigest md = null;
     try {
         md = MessageDigest.getInstance(algorithm);
     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
     }
     byte buffer[] = sInput.getBytes();

     for (int count = 0; count < sInput.length(); count++) {
         md.update(buffer, 0, count);
     }
     byte bDigest[] = md.digest();
     BigInteger bi = new BigInteger(bDigest);
     return (bi.toString(16));
 }
}

There is an article on Codingkit about that. Check out: http://codingkit.com/a/JAVA/2013/1020/2216.html

How do I round to the nearest 0.5?

I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:

The solution I came up with is the following:

//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10;  // NUMBER - Input Your Number here
var n:int = r * 10;   // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; //  NUMBER - Re-assemble the number

trace("ORG No: " + r);
trace("NEW No: " + d);

Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.

Good Luck!

Android Image View Pinch Zooming

Custom zoom view in Kotlin

 import android.content.Context
 import android.graphics.Matrix
 import android.graphics.PointF
 import android.util.AttributeSet
 import android.util.Log
 import android.view.MotionEvent
 import android.view.ScaleGestureDetector
 import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener
 import androidx.appcompat.widget.AppCompatImageView

 class ZoomImageview : AppCompatImageView {
var matri: Matrix? = null
var mode = NONE

// Remember some things for zooming
var last = PointF()
var start = PointF()
var minScale = 1f
var maxScale = 3f
lateinit var m: FloatArray
var viewWidth = 0
var viewHeight = 0
var saveScale = 1f
protected var origWidth = 0f
protected var origHeight = 0f
var oldMeasuredWidth = 0
var oldMeasuredHeight = 0
var mScaleDetector: ScaleGestureDetector? = null
var contex: Context? = null

constructor(context: Context) : super(context) {
    sharedConstructing(context)
}

constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    sharedConstructing(context)
}

private fun sharedConstructing(context: Context) {
    super.setClickable(true)
    this.contex= context
    mScaleDetector = ScaleGestureDetector(context, ScaleListener())
    matri = Matrix()
    m = FloatArray(9)
    imageMatrix = matri
    scaleType = ScaleType.MATRIX
    setOnTouchListener { v, event ->
        mScaleDetector!!.onTouchEvent(event)
        val curr = PointF(event.x, event.y)
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                last.set(curr)
                start.set(last)
                mode = DRAG
            }
            MotionEvent.ACTION_MOVE -> if (mode == DRAG) {
                val deltaX = curr.x - last.x
                val deltaY = curr.y - last.y
                val fixTransX = getFixDragTrans(deltaX, viewWidth.toFloat(), origWidth * saveScale)
                val fixTransY = getFixDragTrans(deltaY, viewHeight.toFloat(), origHeight * saveScale)
                matri!!.postTranslate(fixTransX, fixTransY)
                fixTrans()
                last[curr.x] = curr.y
            }
            MotionEvent.ACTION_UP -> {
                mode = NONE
                val xDiff = Math.abs(curr.x - start.x).toInt()
                val yDiff = Math.abs(curr.y - start.y).toInt()
                if (xDiff < CLICK && yDiff < CLICK) performClick()
            }
            MotionEvent.ACTION_POINTER_UP -> mode = NONE
        }
        imageMatrix = matri
        invalidate()
        true // indicate event was handled
    }
}

fun setMaxZoom(x: Float) {
    maxScale = x
}

private inner class ScaleListener : SimpleOnScaleGestureListener() {
    override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
        mode = ZOOM
        return true
    }

    override fun onScale(detector: ScaleGestureDetector): Boolean {
        var mScaleFactor = detector.scaleFactor
        val origScale = saveScale
        saveScale *= mScaleFactor
        if (saveScale > maxScale) {
            saveScale = maxScale
            mScaleFactor = maxScale / origScale
        } else if (saveScale < minScale) {
            saveScale = minScale
            mScaleFactor = minScale / origScale
        }
        if (origWidth * saveScale <= viewWidth || origHeight * saveScale <= viewHeight) matri!!.postScale(mScaleFactor, mScaleFactor, viewWidth / 2.toFloat(), viewHeight / 2.toFloat()) else matri!!.postScale(mScaleFactor, mScaleFactor, detector.focusX, detector.focusY)
        fixTrans()
        return true
    }
}

fun fixTrans() {
    matri!!.getValues(m)
    val transX = m[Matrix.MTRANS_X]
    val transY = m[Matrix.MTRANS_Y]
    val fixTransX = getFixTrans(transX, viewWidth.toFloat(), origWidth * saveScale)
    val fixTransY = getFixTrans(transY, viewHeight.toFloat(), origHeight * saveScale)
    if (fixTransX != 0f || fixTransY != 0f) matri!!.postTranslate(fixTransX, fixTransY)
}

fun getFixTrans(trans: Float, viewSize: Float, contentSize: Float): Float {
    val minTrans: Float
    val maxTrans: Float
    if (contentSize <= viewSize) {
        minTrans = 0f
        maxTrans = viewSize - contentSize
    } else {
        minTrans = viewSize - contentSize
        maxTrans = 0f
    }
    if (trans < minTrans) return -trans + minTrans
    if (trans > maxTrans) return -trans + maxTrans
    return 0f
}

fun getFixDragTrans(delta: Float, viewSize: Float, contentSize: Float): Float {
    if (contentSize <= viewSize) {
        return 0f
    } else {
        return delta
    }
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    viewWidth = MeasureSpec.getSize(widthMeasureSpec)
    viewHeight = MeasureSpec.getSize(heightMeasureSpec)
    //
    // Rescales image on rotation
    //
    if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) return
    oldMeasuredHeight = viewHeight
    oldMeasuredWidth = viewWidth
    if (saveScale == 1f) {
        //Fit to screen.
        val scale: Float
        val drawable = drawable
        if (drawable == null || drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) return
        val bmWidth = drawable.intrinsicWidth
        val bmHeight = drawable.intrinsicHeight
        Log.d("bmSize", "bmWidth: $bmWidth bmHeight : $bmHeight")
        val scaleX = viewWidth.toFloat() / bmWidth.toFloat()
        val scaleY = viewHeight.toFloat() / bmHeight.toFloat()
        scale = Math.min(scaleX, scaleY)
        matri!!.setScale(scale, scale)
        // Center the image
        var redundantYSpace = viewHeight.toFloat() - scale * bmHeight.toFloat()
        var redundantXSpace = viewWidth.toFloat() - scale * bmWidth.toFloat()
        redundantYSpace /= 2.toFloat()
        redundantXSpace /= 2.toFloat()
        matri!!.postTranslate(redundantXSpace, redundantYSpace)
        origWidth = viewWidth - 2 * redundantXSpace
        origHeight = viewHeight - 2 * redundantYSpace
        imageMatrix = matri
    }
    fixTrans()
}

companion object {
    // We can be in one of these 3 states
    const val NONE = 0
    const val DRAG = 1
    const val ZOOM = 2
    const val CLICK = 3
}
 }

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

You can do this in any program other than Explorer, e.g. Notepad, cmd.exe etc.

You just can't do it in Explorer, and Raymond Chen has offered an explanation as to why not.

How to set up java logging using a properties file? (java.util.logging)

you can set your logging configuration file through command line:

$ java -Djava.util.logging.config.file=/path/to/app.properties MainClass

this way seems cleaner and easier to maintain.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

Why do you use typedef when declaring an enum in C++?

In some C codestyle guide the typedef version is said to be preferred for "clarity" and "simplicity". I disagree, because the typedef obfuscates the real nature of the declared object. In fact, I don't use typedefs because when declaring a C variable I want to be clear about what the object actually is. This choice helps myself to remember faster what an old piece of code actually does, and will help others when maintaining the code in the future.

Installing Python packages from local file system folder to virtualenv with pip

I am installing pyfuzzybut is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy.

I tried the accepted answer

pip install  --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy

But it does not work either and returns the following error:

Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy

At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html

Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip

So the following command worked for me:

pip install ../pyfuzzy-0.1.0.tar.gz.

Hope it can help you.

How do I URL encode a string

Swift 2.0 Example (iOS 9 Compatiable)

extension String {

  func stringByURLEncoding() -> String? {

    let characters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet

    characters.removeCharactersInString("&")

    guard let encodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(characters) else {
      return nil
    }

    return encodedString

  }

}

What's the difference between Unicode and UTF-8?

There's a lot of misunderstanding being displayed here. Unicode isn't an encoding, but the Unicode standard is devoted primarily to encoding anyway.

ISO 10646 is the international character set you (probably) care about. It defines a mapping between a set of named characters (e.g., "Latin Capital Letter A" or "Greek small letter alpha") and a set of code points (a number assigned to each -- for example, 61 hexadecimal and 3B1 hexadecimal for those two respectively; for Unicode code points, the standard notation would be U+0061 and U+03B1).

At one time, Unicode defined its own character set, more or less as a competitor to ISO 10646. That was a 16-bit character set, but it was not UTF-16; it was known as UCS-2. It included a rather controversial technique to try to keep the number of necessary characters to a minimum (Han Unification -- basically treating Chinese, Japanese and Korean characters that were quite a bit alike as being the same character).

Since then, the Unicode consortium has tacitly admitted that that wasn't going to work, and now concentrate primarily on ways to encode the ISO 10646 character set. The primary methods are UTF-8, UTF-16 and UCS-4 (aka UTF-32). Those (except for UTF-8) also have LE (little endian) and BE (big-endian) variants.

By itself, "Unicode" could refer to almost any of the above (though we can probably eliminate the others that it shows explicitly, such as UTF-8). Unqualified use of "Unicode" probably happens the most often on Windows, where it will almost certainly refer to UTF-16. Early versions of Windows NT adopted Unicode when UCS-2 was current. After UCS-2 was declared obsolete (around Win2k, if memory serves), they switched to UTF-16, which is the most similar to UCS-2 (in fact, it's identical for characters in the "basic multilingual plane", which covers a lot, including all the characters for most Western European languages).

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.

Set a path variable with spaces in the path in a Windows .cmd file or batch file

Try this;

  1. create a variable as below

    SET "SolutionDir=C:\Test projects\Automation tests\bin\Debug"**
    
  2. Then replace the path with variable. Make sure to add quotes for starts and end

    vstest.console.exe "%SolutionDir%\Automation.Specs.dll"
    

Java: how do I initialize an array size if it's unknown?

**input of list of number for array from single line.

   String input = sc.nextLine();
    String arr[] = input.split(" ");
    int new_arr[] = new int[arr.length];
    for(int i=0; i<arr.length; i++)
    {
         new_arr[i] = Integer.parseInt(arr[i]);
    }

Convert a 1D array to a 2D array in numpy

Try something like:

B = np.reshape(A,(-1,ncols))

You'll need to make sure that you can divide the number of elements in your array by ncols though. You can also play with the order in which the numbers are pulled into B using the order keyword.

Setting Authorization Header of HttpClient

UTF8 Option

request.DefaultRequestHeaders.Authorization = 
new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(
        System.Text.Encoding.UTF8.GetBytes(
           $"{yourusername}:{yourpwd}")));

How do I perform a Perl substitution on a string while keeping the original?

Another pre-5.14 solution: http://www.perlmonks.org/?node_id=346719 (see japhy's post)

As his approach uses map, it also works well for arrays, but requires cascading map to produce a temporary array (otherwise the original would be modified):

my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You could return an XmlDocument for the ToXML method in your class, then when you are going to add the Element with the result document just use something like:

XmlDocument returnedDocument = Your_Class.ToXML();

XmlDocument finalDocument = new XmlDocument();
XmlElement createdElement = finalDocument.CreateElement("Desired_Element_Name");
createdElement.InnerXML = docResult.InnerXML;
finalDocument.AppendChild(createdElement);

That way the entire value for "Desired_Element_Name" on your result XmlDocument will be the entire content of the returned Document.

I hope this helps.

UIView's frame, bounds, center, origin, when to use what?

Marco's answer above is correct, but just to expand on the question of "under what context"...

frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.

center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.

bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds] on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.

Why is there an frame rectangle and an bounds rectangle in an UIView?

Hopefully this helps clarify the circumstances where each property might get used.

Android SDK Setup under Windows 7 Pro 64 bit

If SDK Setup.exe fails, please try to open a command-prompt and run "tools\android.bat" manually. That's all what SDK Setup does, however the current version has a bug in that it doesn't display errors that the batch might output:

 > cd <your-sdk>\tools
 > android.bat

That way you may see a more useful error message.

You must have a java.exe on your %PATH%.

Subtract minute from DateTime in SQL Server 2005

You want to use DATEADD, using a negative duration. e.g.

DATEADD(minute, -15, '2000-01-01 08:30:00') 

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

how to add value to combobox item

Now you can use insert method instead add

' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")

How to beautifully update a JPA entity in Spring Data?

This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.

Make .gitignore ignore everything except a few files

The simplest way that I go about this is to force add a file. It will be accounted for in git even if it is buried or nested inside a git-ignored subdirectory tree.

For example:

x64 folder is excluded in .gitignore:

x64/

But you want to include the file myFile.py located in x64/Release/ directory. Then you have to:

git add -f x64/Release/myFile.py

You can do this for multiple files of files that match a pattern e.g.

git add -f x64/Release/myFile*.py

and so on.

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

Lists in ConfigParser

I landed here seeking to consume this...

[global]
spys = [email protected], [email protected]

The answer is to split it on the comma and strip the spaces:

SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]

To get a list result:

['[email protected]', '[email protected]']

It may not answer the OP's question exactly but might be the simple answer some people are looking for.

Adjusting and image Size to fit a div (bootstrap)

Simply add the class img-responsive to your img tag, it is applicable in bootstrap 3 onward!

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Java command not found on Linux

  1. Execute: vi ~/.bashrc OR vi ~/.bash_profile

(if above command will not allow to update the .bashrc file then you can open this file in notepad by writing command at terminal i.e. "leafpad ~/.bashrc")

  1. add line : export JAVA_HOME=/usr/java/jre1.6.0_24
  2. save the file (by using shift + Z + Z)
  3. source ~/.bashrc OR source ~/.bash_profile
  4. Execute : echo $JAVA_HOME (Output should print the path)

"Post Image data using POSTMAN"

Follow the below steps:

  1. No need to give any type of header.
  2. Select body > form-data and do same as shown in the image. 1

  3. Now in your Django view.py

def post(self, request, *args, **kwargs):
    image = request.FILES["image"]
    data = json.loads(request.data['data'])
    ...
    return Response(...)
  1. You can access all the keys (id, uid etc..) from the data variable.

What is the difference between bindParam and bindValue?

For the most common purpose, you should use bindValue.

bindParam has two tricky or unexpected behaviors:

  • bindParam(':foo', 4, PDO::PARAM_INT) does not work, as it requires passing a variable (as reference).
  • bindParam(':foo', $value, PDO::PARAM_INT) will change $value to string after running execute(). This, of course, can lead to subtle bugs that might be difficult to catch.

Source: http://php.net/manual/en/pdostatement.bindparam.php#94711

c++ array assignment of multiple values

There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.

Here is what you can do:

#include <algorithm>

int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);

However, in C++0x, you can do this:

std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};

Of course, if you choose to use std::vector instead of raw array.

How to delete large data of table in SQL without log?

Shorter syntax

select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
  DELETE TOP (10000) LargeTable 
  WHERE readTime < dateadd(MONTH,-7,GETDATE())
END

How to attach a file using mail command on Linux?

The following is a decent solution across Unix/Linux installations, that does not rely on any unusual program features. This supports a multi-line message body, multiple attachments, and all the other typical features of mailx.

Unfortunately, it does not fit on a single line.

#!/bin/ksh

# Get the date stamp for temporary files
DT_STAMP=`date +'%C%y%m%d%H%M%S'`

# Create a multi-line body
echo "here you put the message body
which can be split across multiple lines!
woohoo!
" > body-${DT_STAMP}.mail

# Add several attachments
uuencode File1.pdf File1.pdf >  attachments-${DT_STAMP}.mail
uuencode File2.pdf File2.pdf >> attachments-${DT_STAMP}.mail

# Put everything together and send it off!
cat body-${DT_STAMP}.mail attachments-${DT_STAMP}.mail > out-${DT_STAMP}.mail
mailx -s "here you put the message subject" [email protected] < out-${DT_STAMP}.mail

# Clean up temporary files
rm body-${DT_STAMP}.mail
rm attachments-${DT_STAMP}.mail
rm out-${DT_STAMP}.mail

How to get a enum value from string in C#?

With some error handling...

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
   key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
   //unknown string or s is null
}

Error "The input device is not a TTY"

For those who struggle with this error and git bash on Windows, just use PowerShell where -it works perfectly.

How to add url parameter to the current url?

I know I'm late to the game, but you can just do ?id=14&like=like by using http build query as follows:

http_build_query(array_merge($_GET, array("like"=>"like")))

Whatever GET parameters you had will still be there and if like was a parameter before it will be overwritten, otherwise it will be included at the end.

bash export command

Probably because it's trying to execute "export" as an external command, and it's a shell internal.

setting global sql_mode in mysql

Check the documentation of sql_mode

Method 1:

Check default value of sql_mode:

SELECT @@sql_mode //check current value for sql_mode

SET GLOBAL sql_mode = "NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

Method 2:

Access phpmyadmin for editing your sql_mode

  • Login on phpmyadmin and open localhost
  • Top on Variables present on the top in menu items and search out for sql mode
  • Click on edit button to modify sql_mode based on your requirements
  • Save the changes

sql mode settings in phpmyadmin

Restart server after executing above things

Line Break in XML formatting?

Take note: I have seen other posts that say &#xA; will give you a paragraph break, which oddly enough works in the Android xml String.xml file, but will NOT show up in a device when testing (no breaks at all show up). Therefore, the \n shows up on both.

Hive query output to file

The following query will insert the results directly into HDFS:

INSERT OVERWRITE DIRECTORY '/path/to/output/dir' SELECT * FROM table WHERE id > 100;

How do I split a string, breaking at a particular character?

If Spliter is found then only

Split it

else return the same string

function SplitTheString(ResultStr) {
    if (ResultStr != null) {
        var SplitChars = '~';
        if (ResultStr.indexOf(SplitChars) >= 0) {
            var DtlStr = ResultStr.split(SplitChars);
            var name  = DtlStr[0];
            var street = DtlStr[1];
        }
    }
}

center a row using Bootstrap 3

Simply use text-center class

 <div class="row">
     <div class="col-md-12">
          <h3 class="text-center">Here Comes your Text</h3>
     </div>
 </div>

What is the best way to conditionally apply a class?

This works like a charm ;)

<ul class="nav nav-pills" ng-init="selectedType = 'return'">
    <li role="presentation" ng-class="{'active':selectedType === 'return'}"
        ng-click="selectedType = 'return'"><a href="#return">return

    </a></li>
    <li role="presentation" ng-class="{'active':selectedType === 'oneway'}"
        ng-click="selectedType = 'oneway'"><a href="#oneway">oneway
    </a></li>
</ul>

Directly assigning values to C Pointers

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

You need to create an int variable somewhere in memory for the int * variable to point at.

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

How do I pass a list as a parameter in a stored procedure?

Check the below code this work for me

@ManifestNoList      VARCHAR(MAX)


WHERE
    (
        ManifestNo IN (SELECT value FROM dbo.SplitString(@ManifestNoList, ','))
    )

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

Can you hide the controls of a YouTube embed without enabling autoplay?

Autoplay works only with /v/ instead of /embed/, so change the src to:

src="//www.youtube.com/v/qUJYqhKZrwA?autoplay=1&showinfo=0&controls=0"

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

If you are trying to insert the therefore symbol into a WORD DOCUMENT

Hold down the ALT key and type 8756

Hope the answer ur question Regards Al~Hash.

Reverse a string in Java

Here is a low level solution:

import java.util.Scanner;

public class class1 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String inpStr = in.nextLine();
        System.out.println("Original String :" + inpStr);
        char temp;
        char[] arr = inpStr.toCharArray();
        int len = arr.length;
        for(int i=0; i<(inpStr.length())/2; i++,len--){
            temp = arr[i];
            arr[i] = arr[len-1];
            arr[len-1] = temp;
        }

        System.out.println("Reverse String :" + String.valueOf(arr));
    }
}

Set default syntax to different filetype in Sublime Text 2

In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice].

Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as... at the top of the menu.

Updated 2016-04-19: As of now, this also works for Sublime Text 3.

Node.js: what is ENOSPC error and how to solve?

A simple way that solve my problem was:

npm cache clear

npm or a process controlled by it is watching too many files. Updating max_user_watches on the build node can fix it forever. For debian put the following on terminal:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

If you want know how Increase the amount of inotify watchers only click on link.

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

What is the meaning of the term "thread-safe"?

As others have pointed out, thread safety means that a piece of code will work without errors if it's used by more than one thread at once.

It's worth being aware that this sometimes comes at a cost, of computer time and more complex coding, so it isn't always desirable. If a class can be safely used on only one thread, it may be better to do so.

For example, Java has two classes that are almost equivalent, StringBuffer and StringBuilder. The difference is that StringBuffer is thread-safe, so a single instance of a StringBuffer may be used by multiple threads at once. StringBuilder is not thread-safe, and is designed as a higher-performance replacement for those cases (the vast majority) when the String is built by only one thread.

How to convert an int array to String with toString method in Java

System.out.println(array.toString());

should be:

System.out.println(Arrays.toString(array));

WordPress path url in js script file

According to the Wordpress documentation, you should use wp_localize_script() in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

See Codex

Example:

<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>

To access this variable within in Javascript, you would simply do:

<script type="text/javascript">
    var url = WPURLS.siteurl;
</script>

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

What's the difference between the 'ref' and 'out' keywords?

Since you're passing in a reference type (a class) there is no need use ref because per default only a reference to the actual object is passed and therefore you always change the object behind the reference.

Example:

public void Foo()
{
    MyClass myObject = new MyClass();
    myObject.Name = "Dog";
    Bar(myObject);
    Console.WriteLine(myObject.Name); // Writes "Cat".
}

public void Bar(MyClass someObject)
{
    someObject.Name = "Cat";
}

As long you pass in a class you don't have to use ref if you want to change the object inside your method.

Select Multiple Fields from List in Linq

You can make it a KeyValuePair, so it will return a "IEnumerable<KeyValuePair<string, string>>"

So, it will be like this:

.Select(i => new KeyValuePair<string, string>(i.category_id, i.category_name )).Distinct();

Interactive shell using Docker Compose

docker-compose run myapp sh should do the deal.

There is some confusion with up/run, but docker-compose run docs have great explanation: https://docs.docker.com/compose/reference/run

How to send image to PHP file using Ajax?

Post both multiple text inputs plus multiple files via Ajax in one Ajax request

HTML

<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">

Jquery Code

$(document).on('click','#btnSendData',function (event) {
    event.preventDefault();
    var form = $('#myform')[0];
    var formData = new FormData(form);
    // Set header if need any otherwise remove setup part
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
        }
    });
    $.ajax({
        url: "{{route('sendFormWithImage')}}",// your request url
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
            console.log(data);
        },
        error: function () {

        }
    });

});

<> And Not In VB.NET

If you need to know if the variable exists use Is/IsNot Nothing.

Using <> requires that the variable you're evaluating have the "<>" operator defined. Check out

 Dim b As HttpContext
 If b <> Nothing Then
    ...
 End If

and the resultant error

Error   1   Operator '<>' is not defined for types 'System.Web.HttpContext' and 'System.Web.HttpContext'.   

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

Thanks for John Doe's solution that helped a lot. Mine is very similar with some difference, using TempVars

Instead of :

      strSQL = "SELECT * FROM Table1 WHERE Name = Forms!Table!Control;"

I used:

      strSQL = "SELECT * FROM Query1"  , Query1 being common for other usage

Query1 as:

 "Select Field1, Field2 from Table1 where Id= [TempVars]![MyVar]

And similarly, removing [TempVars]![MyVar] from view solved the problem.

Namespace not recognized (even though it is there)

In my case removing/adding that assembly worked.

Remove Fragment Page from ViewPager in Android

I had the idea of simply copy the source code from android.support.v4.app.FragmentPagerAdpater into a custom class named CustumFragmentPagerAdapter. This gave me the chance to modify the instantiateItem(...) so that every time it is called, it removes / destroys the currently attached fragment before it adds the new fragment received from getItem() method.

Simply modify the instantiateItem(...) in the following way:

@Override
public Object instantiateItem(ViewGroup container, int position) {
    if (mCurTransaction == null) {
        mCurTransaction = mFragmentManager.beginTransaction();
    }
    final long itemId = getItemId(position);

    // Do we already have this fragment?
    String name = makeFragmentName(container.getId(), itemId);
    Fragment fragment = mFragmentManager.findFragmentByTag(name);

    // remove / destroy current fragment
    if (fragment != null) {
        mCurTransaction.remove(fragment);
    }

    // get new fragment and add it
    fragment = getItem(position);
    mCurTransaction.add(container.getId(), fragment,    makeFragmentName(container.getId(), itemId));

    if (fragment != mCurrentPrimaryItem) {
        fragment.setMenuVisibility(false);
        fragment.setUserVisibleHint(false);
    }

    return fragment;
}

What are native methods in Java and where should they be used?

Java native code necessities:

  • h/w access and control.
  • use of commercial s/w and system services[h/w related].
  • use of legacy s/w that hasn't or cannot be ported to Java.
  • Using native code to perform time-critical tasks.

hope these points answers your question :)

How to make code wait while calling asynchronous calls like Ajax

If you need wait until the ajax call is completed all do you need is make your call synchronously.

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

In Bash, how can I check if a string begins with some value?

Adding a tiny bit more syntax detail to Mark Rushakoff's highest rank answer.

The expression

$HOST == node*

Can also be written as

$HOST == "node"*

The effect is the same. Just make sure the wildcard is outside the quoted text. If the wildcard is inside the quotes it will be interpreted literally (i.e. not as a wildcard).

Using the Underscore module with Node.js

As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:

var _ = require('underscore');

Happy coding!

Shell command to sum integers, one per line?

I think AWK is what you are looking for:

awk '{sum+=$1}END{print sum}'

You can use this command either by passing the numbers list through the standard input or by passing the file containing the numbers as a parameter.

How to call a function in shell Scripting?

You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.

Function Definition : Create a new script file
Function Call       : Invoke the script file

WampServer orange icon

After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.

Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)

link: http://bugs.mysql.com/bug.php?id=72533

Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.

Regards SB

Min and max value of input in angular4 application

Simply do this in angular2+ by adding (onkeypress)

<input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput"
    (onkeypress)="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
    name="rateInput">

Tested on Angular 7

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date < DATEADD(Day, -1, date)

How to install a specific version of a ruby gem?

Linux

To install different version of ruby, check the latest version of package using apt as below:

$ apt-cache madison ruby
      ruby |    1:1.9.3 | http://ftp.uk.debian.org/debian/ wheezy/main amd64 Packages
      ruby |        4.5 | http://ftp.uk.debian.org/debian/ squeeze/main amd64 Packages

Then install it:

$ sudo apt-get install ruby=1:1.9.3

To check what's the current version, run:

$ gem --version # Check for the current user.
$ sudo gem --version # Check globally.

If the version is still old, you may try to switch the version to new by using ruby version manager (rvm) by:

rvm 1.9.3

Note: You may prefix it by sudo if rvm was installed globally. Or run /usr/local/rvm/scripts/rvm if your command rvm is not in your global PATH. If rvm installation process failed, see the troubleshooting section.


Troubleshooting:

  • If you still have the old version, you may try to install rvm (ruby version manager) via:

    sudo apt-get install curl # Install curl first
    curl -sSL https://get.rvm.io | bash -s stable --ruby # Install only for the user.
    #or:# curl -sSL https://get.rvm.io | sudo bash -s stable --ruby # Install globally. 
    

    then if installed locally (only for current user), load rvm via:

    source /usr/local/rvm/scripts/rvm; rvm 1.9.3
    

    if globally (for all users), then:

    sudo bash -c "source /usr/local/rvm/scripts/rvm; rvm 1.9.3"
    
  • if you still having problem with the new ruby version, try to install it by rvm via:

    source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3 # Locally.
    sudo bash -c "source /usr/local/rvm/scripts/rvm && rvm install ruby-1.9.3" # Globally.
    
  • if you'd like to install some gems globally and you have rvm already installed, you may try:

    rvmsudo gem install [gemname]
    

    instead of:

      gem install [gemname] # or:
      sudo gem install [gemname]
    

Note: It's prefered to NOT use sudo to work with RVM gems. When you do sudo you are running commands as root, another user in another shell and hence all of the setup that RVM has done for you is ignored while the command runs under sudo (such things as GEM_HOME, etc...). So to reiterate, as soon as you 'sudo' you are running as the root system user which will clear out your environment as well as any files it creates are not able to be modified by your user and will result in strange things happening.

PowerShell equivalent to grep -f

This question already has an answer, but I just want to add that in Windows there is Windows Subsystem for Linux WSL.

So for example if you want to check if you have service named Elasicsearch that is in status running you can do something like the snippet below in powershell

net start | grep Elasticsearch

jQuery iframe load() event?

Without code in iframe + animate:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

    jQuery(document).ready(function($) {

        $(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

    });

}    
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >

What is the best way to get the minimum or maximum value from an Array of numbers?

There isn't any reliable way to get the minimum/maximum without testing every value. You don't want to try a sort or anything like that, walking through the array is O(n), which is better than any sort algorithm can do in the general case.

How do I use the built in password reset/change views with my own templates

You just need to wrap the existing functions and pass in the template you want. For example:

from django.contrib.auth.views import password_reset

def my_password_reset(request, template_name='path/to/my/template'):
    return password_reset(request, template_name)

To see this just have a look at the function declartion of the built in views:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

How can a web application send push notifications to iOS devices?

You can use HTML5 Websockets to introduce your own push messages. From Wikipedia:

"For the client side, WebSocket was to be implemented in Firefox 4, Google Chrome 4, Opera 11, and Safari 5, as well as the mobile version of Safari in iOS 4.2. Also the BlackBerry Browser in OS7 supports WebSockets."

To do this, you need your own provider server to push the messages to the clients.
If you want to use APN (Apple Push Notification) or C2DM (Cloud to Device Message), you must have a native application which must be downloaded through the online store.

How can I change UIButton title color?

You can use -[UIButton setTitleColor:forState:] to do this.

Example:

Objective-C

[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

Swift 2

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Swift 3

buttonName.setTitleColor(UIColor.white, for: .normal)

Thanks to richardchildan

While variable is not defined - wait

The following will keep looking for someVariable until it is found. It checks every 0.25 seconds.

function waitForElement(){
    if(typeof someVariable !== "undefined"){
        //variable exists, do what you want
    }
    else{
        setTimeout(waitForElement, 250);
    }
}

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

I had to run my commands in the one and same terminal, not seperately.

nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"

Convert int to a bit array in .NET

Use Convert.ToString (value, 2)

so in your case

string binValue = Convert.ToString (3, 2);

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Android Completely transparent Status Bar?

I found the answer while I investigating this library: https://github.com/laobie/StatusBarUtil

so you need to add following codes to your activity

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
    window.statusBarColor = Color.TRANSPARENT
} else {
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}

Splitting comma separated string in a PL/SQL stored proc

I use apex_util.string_to_table to parse strings, but you can use a different parser if you wish. Then you can insert the data as in this example:

declare
  myString varchar2(2000) :='0.75, 0.64, 0.56, 0.45';
  myAmount varchar2(2000) :='0.25, 0.5, 0.65, 0.8';
  v_array1 apex_application_global.vc_arr2;
  v_array2 apex_application_global.vc_arr2;
begin

  v_array1 := apex_util.string_to_table(myString, ', ');
  v_array2 := apex_util.string_to_table(myAmount, ', ');

  forall i in 1..v_array1.count
     insert into mytable (a, b) values (v_array1(i), v_array2(i));
end;

Apex_util is available from Oracle 10G onwards. Prior to this it was called htmldb_util and was not installed by default. If you can't use that you could use the string parser I wrote many years ago and posted here.

Is the ternary operator faster than an "if" condition in Java

Does it matter which I use?

Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.

Which is faster?

Neither.

Is it a better practice to use the shortest code whenever possible?

Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).

File Upload In Angular?

I've upload file using reference. No package is required to upload file this way.

// code to be written in .ts file

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
  let fileToUpload = fi.files[0];
    this.admin.addQuestionApi(fileToUpload)
      .subscribe(
        success => {
          this.loading = false;
          this.flashMessagesService.show('Uploaded successfully', {
            classes: ['alert', 'alert-success'],
            timeout: 1000,
          });
        },
        error => {
          this.loading = false;
          if(error.statusCode==401) this.router.navigate(['']);
          else
            this.flashMessagesService.show(error.message, {
              classes: ['alert', 'alert-danger'],
              timeout: 1000,
            });
        });
  }

}

// code to be written in service.ts file

addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
      .map(response => response.json())
      .catch(this.errorHandler);

}

// code to be written in html

<input type="file" #fileInput>

Simple dictionary in C++

Until I was really concerned about performance, I would use a function, that takes a base and returns its match:

char base_pair(char base)
{
    switch(base) {
        case 'T': return 'A';
        ... etc
        default: // handle error
    }
}

If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.

How to convert an integer to a string in any base?

def baseConverter(x, b):
    s = ""
    d = string.printable.upper()
    while x > 0:
        s += d[x%b]
        x = x / b
    return s[::-1]

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

use debugbar package

composer require "barryvdh/laravel-debugbar": "2.3.*"

enter image description here

How can I drop all the tables in a PostgreSQL database?

drop schema public cascade;

should do the trick.

Simple (I think) Horizontal Line in WPF?

For anyone else struggling with this: Qwertie's comment worked well for me.

<Border Width="1" Margin="2" Background="#8888"/>

This creates a vertical seperator which you can talior to suit your needs.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
    String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
    DateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
    return dateFormat.format(currentCalDate.getTime());
}

private String getDayNumberSuffix(int day) {
    if (day >= 11 && day <= 13) {
        return "th";
    }
    switch (day % 10) {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}

SFTP Libraries for .NET

For comprehensive SFTP support in .NET try edtFTPnet/PRO. It's been around a long time with support for many different SFTP servers.

We also sell an SFTP server for Windows, CompleteFTP, which is an inexpensive way to get support for SFTP on your Windows machine. Also has FTP and FTPS.

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Just to add to yamen's answer, which is perfect for images but not so much for text.

If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.

May not be perfect but works for me!

using (MemoryStream ms = new MemoryStream(wordBytes))
{
    float width = 3840;
    float height = 2160;
    var brush = new SolidBrush(Color.White);

    var rawImage = Image.FromStream(ms);
    float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
    var scaleWidth  = (int)(rawImage.Width  * scale);
    var scaleHeight = (int)(rawImage.Height * scale);
    var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);

    Graphics graph = Graphics.FromImage(scaledBitmap);
    graph.InterpolationMode = InterpolationMode.High;
    graph.CompositingQuality = CompositingQuality.HighQuality;
    graph.SmoothingMode = SmoothingMode.AntiAlias;
    graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
    graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));

    scaledBitmap.Save(fileName, ImageFormat.Png);
    return scaledBitmap;
}

How to enumerate an enum

I think you can use

Enum.GetNames(Suit)

MySQL Orderby a number, Nulls last

Something like

SELECT * FROM tablename where visible=1 ORDER BY COALESCE(position, 999999999) ASC, id DESC

Replace 999999999 with what ever the max value for the field is

Differences between utf8 and latin1

UTF-8 is prepared for world domination, Latin1 isn't.

If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).

Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4.

How can I use a JavaScript variable as a PHP variable?

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don

"getaddrinfo failed", what does that mean?

Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust

Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.

You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings

Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.

Click Ok Come back to anaconda terminal and you can try install commands

What is the best open-source java charting library? (other than jfreechart)

There aren't a lot of them because they would be in competition with JFreeChart, and it's awesome. You can get documentation and examples by downloading the developer's guide. There are also tons of free online tutorials if you search for them.

What is Node.js' Connect, Express and "middleware"?

node.js

Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.

node.js as a web server: express

Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.

Middleware and Connect

Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:

  • logger request logger with custom format support
  • csrf Cross-site request forgery protection
  • compress Gzip compression middleware
  • basicAuth basic http authentication
  • bodyParser extensible request body parser
  • json application/json parser
  • urlencoded application/x-www-form-urlencoded parser
  • multipart multipart/form-data parser
  • timeout request timeouts
  • cookieParser cookie parser
  • session session management support with bundled MemoryStore
  • cookieSession cookie-based session support
  • methodOverride faux HTTP method support
  • responseTime calculates response-time and exposes via X-Response-Time
  • staticCache memory cache layer for the static() middleware
  • static streaming static file server supporting Range and more
  • directory directory listing middleware
  • vhost virtual host sub-domain mapping middleware
  • favicon efficient favicon server (with default icon)
  • limit limit the bytesize of request bodies
  • query automatic querystring parser, populating req.query
  • errorHandler flexible error handler

Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.

What to do?

Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express will download and install express globally (check the express guide).
Running express foo in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>, then open http://localhost:3000 and see. Now you are in.

How to show the last queries executed on MySQL?

You can enable a general query log for that sort of diagnostic. Generally you don't log all SELECT queries on a production server though, it's a performance killer.

Edit your MySQL config, e.g. /etc/mysql/my.cnf - look for, or add, a line like this

[mysqld]
log = /var/log/mysql/mysql.log

Restart mysql to pick up that change, now you can

tail -f /var/log/mysql/mysql.log

Hey presto, you can watch the queries as they come in.

PHP/MySQL insert row then get 'id'

An example.

    $query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
    $query_new = $databaseConnection->prepare($query_new);
    $query_new->bind_param('s', $_POST['coursename']);
    $query_new->execute();
    $course_id = $query_new->insert_id;
    $query_new->close();

The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row. Hope this helps.

Linux/Unix command to determine if process is running?

Here is my version. Features:

  • checks for exact program name (first argument of the function). search for "mysql" will not match running "mysqld"
  • searches program arguments (second argument of the function)

script:

#!/bin/bash

# $1 - cmd
# $2 - args
# return: 0 - no error, running; 1 - error, not running
function isRunning() {
    for i in $(pidof $1); do
        cat /proc/$i/cmdline | tr '\000' ' ' | grep -F -e "$2" 1>&2> /dev/null
        if [ $? -eq 0 ]; then
            return 0
        fi
    done
    return 1
}

isRunning java "-Djava.util.logging.config.file=logging.properties"
if [ $? -ne 0 ]; then
    echo "not running, starting..."
fi

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

android.view.WindowManager$BadTokenException: Unable to add window"

Problem :

This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog.

If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.

Reason :

The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.

Solution:

Use isFinishing() method which is called by Android to check whether this activity is in the process of finishing: be it explicit finish() call or activity clean up made by Android. By using this method it is very easy to avoid opening dialog from background thread when activity is finishing.

Also maintain a weak reference for the activity (and not a strong reference so that activity can be destroyed once not needed) and check if the activity is not finishing before performing any UI using this activity reference (i.e. showing a dialog).

eg.

private class chkSubscription extends AsyncTask<String, Void, String>{

  private final WeakReference<login> loginActivityWeakRef;

  public chkSubscription (login loginActivity) {
    super();
    this.loginActivityWeakRef= new WeakReference<login >(loginActivity)
  }

  protected String doInBackground(String... params) {
    //web service call
  }

  protected void onPostExecute(String result) {
    if(page.contains("error")) //when not subscribed
    {
      if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
        builder.setCancelable(true);
        builder.setMessage(sucObject);
        builder.setInverseBackgroundForced(true);

        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){
            dialog.dismiss();
          }
        });

        builder.show();
      }
    }
  }
}

Update :

Window Tokens:

As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.

 A real-world scenario:

When an application starts up for the first time, the ActivityManagerService creates a special kind of window token called an application window token, which uniquely identifies the application's top-level container window. The activity manager gives this token to both the application and the window manager, and the application sends the token to the window manager each time it wants to add a new window to the screen. This ensures secure interaction between the application and the window manager (by making it impossible to add windows on top of other applications), and also makes it easy for the activity manager to make direct requests to the window manager.

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

SVG gradient using CSS

Here is how to set a linearGradient on a target element:

<style type="text/css">
    path{fill:url('#MyGradient')}
</style>
<defs>
    <linearGradient id="MyGradient">
        <stop offset="0%" stop-color="#e4e4e3" ></stop>
        <stop offset="80%" stop-color="#fff" ></stop>
    </linearGradient>
</defs>

Finding what branch a Git commit came from

Update December 2013:

sschuberth comments

git-what-branch (Perl script, see below) does not seem to be maintained anymore. git-when-merged is an alternative written in Python that's working very well for me.

It is based on "Find merge commit which include a specific commit".

git when-merged [OPTIONS] COMMIT [BRANCH...]

Find when a commit was merged into one or more branches.
Find the merge commit that brought COMMIT into the specified BRANCH(es).

Specifically, look for the oldest commit on the first-parent history of BRANCH that contains the COMMIT as an ancestor.


Original answer September 2010:

Sebastien Douche just twitted (16 minutes before this SO answer):

git-what-branch: Discover what branch a commit is on, or how it got to a named branch

This is a Perl script from Seth Robertson that seems very interesting:

SYNOPSIS

git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...

OVERVIEW

Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch. If a commit was made directly on a named branch, that obviously is the earliest path.

By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless --topo-order is specified).

PERFORMANCE

If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular --reference-branch --reference tag to examine will be hundreds of times faster (if you have hundreds of candidate branches).

EXAMPLES

 # git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
   v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May  5 08:59:37 2005)
   v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May  3 18:27:24 2005)
   v2.6.12-rc3-461-g84e48b6 is on master
   v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
   [...]

This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.

How to replace four spaces with a tab in Sublime Text 2?

To configure Sublime to always use tabs try the adding the following to preferences->settings-user:

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

More information here: http://www.sublimetext.com/docs/2/indentation.html

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Add this to your code for fixed height and add one scroll.

.fixedbox {
    max-height: auto;
    overflow-y: scroll;
}

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try using xmltype.createxml(xml).

As in,

select extract(xmltype.createxml(xml), '//fax').getStringVal() from mytab;

It worked for me.

If you want to improve or manipulate even further.

Try something like this.

Select *
from xmltable(xmlnamespaces('some-name-space' as "ns", 
                                  'another-name-space' as "ns1",
                           ), 
                    '/ns/ns1/foo/bar'
                    passing xmltype.createxml(xml) 
                    columns id varchar2(10) path '//ns//ns1/id',
                            idboss varchar2(500) path '//ns0//ns1/idboss',
                            etc....

                    ) nice_xml_table

Hope it helps someone.

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

Check if certain value is contained in a dataframe column in pandas

You can use any:

print any(df.column == 07311954)
True       #true if it contains the number, false otherwise

If you rather want to see how many times '07311954' occurs in a column you can use:

df.column[df.column == 07311954].count()

How to take MySQL database backup using MySQL Workbench?

For Workbench 6.0

Open MySql workbench. To take database backup you need to create New Server Instance(If not available) within Server Administration.

Steps to Create New Server Instance:

  1. Select New Server Instance option within Server Administrator.
  2. Provide connection details.

After creating new server instance , it will be available in Server Administration list. Double click on Server instance you have created OR Click on Manage Import/Export option and Select Server Instance.

Now, From DATA EXPORT/RESTORE select DATA EXPORT option,Select Schema and Schema Object for backup.

You can take generate backup file in different way as given below-

Q.1) Backup file(.sql) contains both Create Table statements and Insert into Table Statements

ANS:

  1. Select Start Export Option

Q.2) Backup file(.sql) contains only Create Table Statements, not Insert into Table statements for all tables

ANS:

  1. Select Skip Table Data(no-data) option

  2. Select Start Export Option

Q.3) Backup file(.sql) contains only Insert into Table Statements, not Create Table statements for all tables

ANS:

  1. Select Advance Option Tab, Within Tables Panel- select no-create info-Do not write CREATE TABLE statement that re-create each dumped table option.
  2. Select Start Export Option

For Workbench 6.3

  1. Click on Management tab at left side in Navigator Panel
  2. Click on Data Export Option
  3. Select Schema
  4. Select Tables
  5. Select required option from dropdown below the tables list as per your requirement
  6. Select Include Create schema checkbox
  7. Click on Advance option
  8. Select Complete insert checkbox in Inserts Panel
  9. Start Export Workbench 6.3 export

For Workbench 8.0

  1. Go to Server tab
  2. Go to Database Export

This opens up something like this

MySQL Workbench

  1. Select the schema to export in the Tables to export
  2. Click on Export to Self-Contained file
  3. Check if Advanced Options... are exactly as you want the export
  4. Click the button Start Export

Calling ASP.NET MVC Action Methods from JavaScript

You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d

jQuery post is the short version of jQuery ajax.

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

If you want more options like success callbacks and error handling, use jQuery ajax,

function addToCart(id)
{
  $.ajax({
  url: '@Url.Action("Add","Cart")',
  data: { id: id },
  success: function(data){
    //call is successfully completed and we got result in data
  },
  error:function (xhr, ajaxOptions, thrownError){
                  //some errror, some show err msg to user and log the error  
                  alert(xhr.responseText);

                }    
  });
}

When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.

This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.

Check if value is in select list with JQuery

Just in case you (or someone else) could be interested in doing it without jQuery:

var exists = false;
for(var i = 0, opts = document.getElementById('select-box').options; i < opts.length; ++i)
   if( opts[i].value === 'bar' )
   {
      exists = true; 
      break;
   }

Change Timezone in Lumen or Laravel 5

Just changing APP_TIMEZONE=Asia/Colombo in .env and run php artisan lumen-config:cache worked for me in lumen 5.7

In Bash, how do I add a string after each line in a file?

If you have it, the lam (laminate) utility can do it, for example:

$ lam filename -s "string after each line"

How do I search for files in Visual Studio Code?

If you want to see your files in Explorer tree...

when you click anywhere in the explorer tree and start typing something on the keyboard, the search keyword appears in the top right corner of the screen : ("module.ts")

enter image description here

And when you hover over the keyword with the mouse cursor, you can click on "Enable Filter on Type" to filter tree with your search !

Changing SqlConnection timeout

I found an excellent blogpost on this subject: https://improve.dk/controlling-sqlconnection-timeouts/

Basically, you either set Connect Timeout in the connection string, or you set ConnectionTimeout on the command object.

Be aware that the timeout time is in seconds.

Send HTML in email via PHP

You need to code your html using absolute path for images. By Absolute path means you have to upload the images in a server and in the src attribute of images you have to give the direct path like this <img src="http://yourdomain.com/images/example.jpg">.

Below is the PHP code for your refference :- Its taken from http://www.php.net/manual/en/function.mail.php

<?php
// multiple recipients
$to  = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
  <p>Here are the birthdays upcoming in August!</p>
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";


// Mail it
mail($to, $subject, $message, $headers);
?>

How do I get the key at a specific index from a Dictionary in Swift?

I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.

My initial thought was to wrap my dictionary in an Array. [[String: UIImage]] but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key so I went with Tuples. Now my array looks like [(String, UIImage)] so I can retrieve it by tuple.0. No more converting it to an Array. Just my 2 cents.

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.

WPF Binding StringFormat Short Date String

Some DateTime StringFormat samples I found useful. Lifted from C# Examples

DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

How to convert a Hibernate proxy to a real entity object

The way I recommend with JPA 2 :

Object unproxied  = entityManager.unwrap(SessionImplementor.class).getPersistenceContext().unproxy(proxy);

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I solved this by setting a higher timeout value for the proxy:

location / {
    proxy_read_timeout 300s;
    proxy_connect_timeout 75s;
    proxy_pass http://localhost:3000;
}

Documentation: https://nginx.org/en/docs/http/ngx_http_proxy_module.html

How to create an Explorer-like folder browser control?

It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.

Check if a value is within a range of numbers

Here is an option with only a single comparison.

// return true if in range, otherwise false
function inRange(x, min, max) {
    return ((x-min)*(x-max) <= 0);
}

console.log(inRange(5, 1, 10));     // true
console.log(inRange(-5, 1, 10));    // false
console.log(inRange(20, 1, 10));    // false

Ruby send JSON request

It's 2020 - nobody should be using Net::HTTP any more and all answers seem to be saying so, use a more high level gem such as Faraday - Github


That said, what I like to do is a wrapper around the HTTP api call,something that's called like

rv = Transporter::FaradayHttp[url, options]

because this allows me to fake HTTP calls without additional dependencies, ie:

  if InfoSig.env?(:test) && !(url.to_s =~ /localhost/)
    response_body = FakerForTests[url: url, options: options]

  else
    conn = Faraday::Connection.new url, connection_options

Where the faker looks something like this

I know there are HTTP mocking/stubbing frameworks, but at least when I researched last time they didn't allow me to validate requests efficiently and they were just for HTTP, not for example for raw TCP exchanges, this system allows me to have a unified framework for all API communication.


Assuming you just want to quick&dirty convert a hash to json, send the json to a remote host to test an API and parse response to ruby this is probably fastest way without involving additional gems:

JSON.load `curl -H 'Content-Type:application/json' -H 'Accept:application/json' -X POST localhost:3000/simple_api -d '#{message.to_json}'`

Hopefully this goes without saying, but don't use this in production.

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

Convert CString to const char*

There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):

CString str;
// ....
const char* cstr = (LPCTSTR)str;

How to set iframe size dynamically

Have you tried height="100%" in the definition of your iframe ? It seems to do what you seek, if you add height:100% in the css for "body" (if you do not, 100% will be "100% of your content").

EDIT: do not do this. The height attribute (as well as the width one) must have an integer as value, not a string.

select certain columns of a data table

Here's working example with anonymous output record, if you have any questions place a comment below:                    

public partial class Form1 : Form
{
    DataTable table;
    public Form1()
    {
        InitializeComponent();
        #region TestData
        table = new DataTable();
        table.Clear();
        for (int i = 1; i < 12; ++i)
            table.Columns.Add("Col" + i);
        for (int rowIndex = 0; rowIndex < 5; ++rowIndex)
        {
            DataRow row = table.NewRow();
            for (int i = 0; i < table.Columns.Count; ++i)
                row[i] = String.Format("row:{0},col:{1}", rowIndex, i);
            table.Rows.Add(row);
        }
        #endregion
        bind();
    }

    public void bind()
    {
        var filtered = from t in table.AsEnumerable()
                       select new
                       {
                           col1 = t.Field<string>(0),//column of index 0 = "Col1"
                           col2 = t.Field<string>(1),//column of index 1 = "Col2"
                           col3 = t.Field<string>(5),//column of index 5 = "Col6"
                           col4 = t.Field<string>(6),//column of index 6 = "Col7"
                           col5 = t.Field<string>(4),//column of index 4 = "Col3"
                       };
        filteredData.AutoGenerateColumns = true;
        filteredData.DataSource = filtered.ToList();
    }
}

How to change pivot table data source in Excel?

right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition

then you can create a new or choose a different connection

worked perfectly.

the get data button is next to the tiny button with a red arrow next to the range text input box.

Organizing a multiple-file Go project

I would recommend reviewing this page on How to Write Go Code

It documents both how to structure your project in a go build friendly way, and also how to write tests. Tests do not need to be a cmd using the main package. They can simply be TestX named functions as part of each package, and then go test will discover them.

The structure suggested in that link in your question is a bit outdated, now with the release of Go 1. You no longer would need to place a pkg directory under src. The only 3 spec-related directories are the 3 in the root of your GOPATH: bin, pkg, src . Underneath src, you can simply place your project mypack, and underneath that is all of your .go files including the mypack_test.go

go build will then build into the root level pkg and bin.

So your GOPATH might look like this:

~/projects/
    bin/
    pkg/
    src/
      mypack/
        foo.go
        bar.go
        mypack_test.go

export GOPATH=$HOME/projects

$ go build mypack
$ go test mypack

Update: as of >= Go 1.11, the Module system is now a standard part of the tooling and the GOPATH concept is close to becoming obsolete.

Access an arbitrary element in a dictionary in Python

If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:

my_dict.keys()[0]     -> key of "first" element
my_dict.values()[0]   -> value of "first" element
my_dict.items()[0]    -> (key, value) tuple of "first" element

Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.

in Python 3:

list(my_dict.keys())[0]     -> key of "first" element
list(my_dict.values())[0]   -> value of "first" element
list(my_dict.items())[0]    -> (key, value) tuple of "first" element

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!

HTML

<span class="menu">Menu</span>

SCSS

.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;
    }

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);
        }
    }
}

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

error: Your local changes to the following files would be overwritten by checkout

I encountered the same problem and solved it by

git checkout -f branch

Well, be careful with the -f switch. You will lose any uncommitted changes if you use the -f switch. While there may be some use cases where it is helpful to use -f, in most cases, you may want to stash your changes and then switch branches. The stashing procedure is explained above.

How to create relationships in MySQL

Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than

customer_id INT( 4 ) NOT NULL ,

make it

customer_id INT( 10 ) NOT NULL ,

and make sure your int column in the customers table is int(10) also.

Why aren't Xcode breakpoints functioning?

For Xcode 4:

go Product -> Debug ->  Activate Breakpoints

How to compare two lists in python?

a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']

# if you care about order
a == b # True
a == c # False

# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True

By casting a, b and c as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.

How to prevent a double-click using jQuery?

In my case, jQuery one had some side effects (in IE8) and I ended up using the following :

$(document).ready(function(){
  $("*").dblclick(function(e){
    e.preventDefault();
  });
});

which works very nicely and looks simpler. Found it there: http://www.jquerybyexample.net/2013/01/disable-mouse-double-click-using-javascript-or-jquery.html

List all tables in postgresql information_schema

For private schema 'xxx' in postgresql :

SELECT table_name FROM information_schema.tables 
 WHERE table_schema = 'xxx' AND table_type = 'BASE TABLE'

Without table_type = 'BASE TABLE' , you will list tables and views

Open new Terminal Tab from command line (Mac OS X)

With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).

How to get the bluetooth devices as a list?

You should change your code as below:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

List<String> s = new ArrayList<String>();
for(BluetoothDevice bt : pairedDevices)
   s.add(bt.getName());

setListAdapter(new ArrayAdapter<String>(this, R.layout.list, s));

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

Calling a method inside another method in same class

Recursion is a method that call itself. In this case it is a recursion. However it will be overloading until you put a restriction inside the method to stop the loop (if-condition).

What is an alternative to execfile in Python 3?

You are just supposed to read the file and exec the code yourself. 2to3 current replaces

execfile("somefile.py", global_vars, local_vars)

as

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)

See:

Displaying the Indian currency symbol on a website

use this new unicode char: &#x20b9;

What's the best way to use R scripts on the command line (terminal)?

Try smallR for writing quick R scripts in the command line:

http://code.google.com/p/simple-r/

(r command in the directory)

Plotting from the command line using smallR would look like this:

r -p file.txt

Use YAML with variables

I had this same question, and after a lot of research, it looks like it's not possible.

The answer from cgat is on the right track, but you can't actually concatenate references like that.

Here are things you can do with "variables" in YAML (which are officially called "node anchors" when you set them and "references" when you use them later):

Define a value and use an exact copy of it later:

default: &default_title This Post Has No Title
title: *default_title

{ or }

example_post: &example
  title: My mom likes roosters
  body: Seriously, she does. And I don't know when it started.
  date: 8/18/2012
first_post: *example
second_post:
  title: whatever, etc.

For more info, see this section of the wiki page about YAML: http://en.wikipedia.org/wiki/YAML#References

Define an object and use it with modifications later:

default: &DEFAULT
  URL:          stooges.com
  throw_pies?:  true  
  stooges:  &stooge_list
    larry:  first_stooge
    moe:    second_stooge
    curly:  third_stooge

development:
  <<: *DEFAULT
  URL:      stooges.local
  stooges: 
    shemp: fourth_stooge

test:
  <<: *DEFAULT
  URL:    test.stooges.qa
  stooges: 
    <<: *stooge_list
    shemp: fourth_stooge

This is taken directly from a great demo here: https://gist.github.com/bowsersenior/979804

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

How to add new elements to an array?

Apache Commons Lang has

T[] t = ArrayUtils.add( initialArray, newitem );

it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.

Find string between two substrings

source='your token _here0@df and maybe _here1@df or maybe _here2@df'
start_sep='_'
end_sep='@df'
result=[]
tmp=source.split(start_sep)
for par in tmp:
  if end_sep in par:
    result.append(par.split(end_sep)[0])

print result

must show: here0, here1, here2

the regex is better but it will require additional lib an you may want to go for python only

Maven: How to include jars, which are not available in reps into a J2EE project?

As you've said you don't want to set up your own repository, perhaps this will help.

You can use the install-file goal of the maven-install-plugin to install a file to the local repository. If you create a script with a Maven invocation for each file and keep it alongside the jars, you (and anyone else with access) can easily install the jars (and associated pom files) to their local repository.

For example:

mvn install:install-file -Dfile=/usr/jars/foo.jar -DpomFile=/usr/jars/foo.pom
mvn install:install-file -Dfile=/usr/jars/bar.jar -DpomFile=/usr/jars/bar.pom

or just

mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0 -Dpackaging=jar

You can then reference the dependencies as normal in your project.

However your best bet is still to set up an internal remote repository and I'd recommend using Nexus myself. It can run on your development box if needed, and the overhead is minimal.

Change DIV content using ajax, php and jQuery

jQuery.load()

$('#summary').load('ajax.php', function() {
  alert('Loaded.');
});

How to solve a timeout error in Laravel 5

I had a similar problem just now. However, this had nothing to do with modifying the php.ini file. It was from a for loop. If you are having nested for loops, make sure you are using the iterator properly. In my case, I was iterating the outer iterator from my inner iterator.

JavaScript post request like a form submit

Three options here.

  1. Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.

  2. Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in Using POST method in XMLHTTPRequest (Ajax).)

  3. Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.

How to use Session attributes in Spring-mvc

Isn't it easiest and shortest that way? I knew it and just tested it - working perfect here:

@GetMapping
public String hello(HttpSession session) {
    session.setAttribute("name","value");
    return "hello";
}

p.s. I came here searching for an answer of "How to use Session attributes in Spring-mvc", but read so many without seeing the most obvious that I had written in my code. I didn't see it, so I thought its wrong, but no it was not. So lets share that knowledge with the easiest solution for the main question.

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

// Purpose: to reverse bits in an unsigned short integer 
// Input: an unsigned short integer whose bits are to be reversed
// Output: an unsigned short integer with the reversed bits of the input one
unsigned short ReverseBits( unsigned short a )
{
     // declare and initialize number of bits in the unsigned short integer
     const char num_bits = sizeof(a) * CHAR_BIT;

     // declare and initialize bitset representation of integer a
     bitset<num_bits> bitset_a(a);          

     // declare and initialize bitset representation of integer b (0000000000000000)
     bitset<num_bits> bitset_b(0);                  

     // declare and initialize bitset representation of mask (0000000000000001)
     bitset<num_bits> mask(1);          

     for ( char i = 0; i < num_bits; ++i )
     {
          bitset_b = (bitset_b << 1) | bitset_a & mask;
          bitset_a >>= 1;
     }

     return (unsigned short) bitset_b.to_ulong();
}

void PrintBits( unsigned short a )
{
     // declare and initialize bitset representation of a
     bitset<sizeof(a) * CHAR_BIT> bitset(a);

     // print out bits
     cout << bitset << endl;
}


// Testing the functionality of the code

int main ()
{
     unsigned short a = 17, b;

     cout << "Original: "; 
     PrintBits(a);

     b = ReverseBits( a );

     cout << "Reversed: ";
     PrintBits(b);
}

// Output:
Original: 0000000000010001
Reversed: 1000100000000000