Get the Youtube Video id.
@param {string} str - the url from which you want to extract the id
@returns {string|undefined}
767759
function youtube(str) {
	// shortcode
	var shortcode = /youtube:\/\/|https?:\/\/youtu\.be\//g;

	if (shortcode.test(str)) {
		var shortcodeid = str.split(shortcode)[1];
		return stripParameters(shortcodeid);
	}

	// /v/ or /vi/
	var inlinev = /\/v\/|\/vi\//g;

	if (inlinev.test(str)) {
		var inlineid = str.split(inlinev)[1];
		return stripParameters(inlineid);
	}

	// v= or vi=
	var parameterv = /v=|vi=/g;

	if (parameterv.test(str)) {
		var arr = str.split(parameterv);
		return arr[1].split('&')[0];
	}

	// v= or vi=
	var parameterwebp = /\/an_webp\//g;

	if (parameterwebp.test(str)) {
		var webp = str.split(parameterwebp)[1];
		return stripParameters(webp);
	}

	// embed
	var embedreg = /\/embed\//g;

	if (embedreg.test(str)) {
		var embedid = str.split(embedreg)[1];
		return stripParameters(embedid);
	}

	// user
	var userreg = /\/user\/(?!.*videos)/g;

	if (userreg.test(str)) {
		var elements = str.split('/');
		return stripParameters(elements.pop());
	}

	// attribution_link
	var attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/;

	if (attrreg.test(str)) {
		return str.match(attrreg)[1];
	}
}
1102568
def _get_video_id(self, url=None):
        
        if url:
            html_data = self.http.request("get", url).text
        else:
            html_data = self.get_urldata()
        html_data = self.get_urldata()
        match = re.search(r'data-video-id="([0-9]+)"', html_data)
        if match:
            return match.group(1)
        match = re.search(r'data-videoid="([0-9]+)', html_data)
        if match:
            return match.group(1)
        match = re.search(r'"mediaGuid":"([0-9]+)"', html_data)
        if match:
            return match.group(1)

        clips = False
        slug = None
        match = re.search('params":({.*}),"query', self.get_urldata())
        if match:
            jansson = json.loads(match.group(1))
            if "seasonNumberOrVideoId" in jansson:
                season = jansson["seasonNumberOrVideoId"]
                match = re.search(r"\w-(\d+)$", season)
                if match:
                    season = match.group(1)
            else:
                match = self._conentpage(self.get_urldata())
                if match:  # this only happen on the program page?
                    janson2 = json.loads(match.group(1))
                    if janson2["formatPage"]["format"]:
                        season = janson2["formatPage"]["format"]["seasonNumber"]
                        return janson2["formatPage"]["format"]["videos"][str(season)]["program"][0]["id"]
                return None
            if "videoIdOrEpisodeNumber" in jansson:
                videp = jansson["videoIdOrEpisodeNumber"]
                match = re.search(r'(\w+)-(\d+)', videp)
                if match:
                    episodenr = match.group(2)
                else:
                    episodenr = videp
                    clips = True
                match = re.search(r'(s\w+)-(\d+)', season)
                if match:
                    season = match.group(2)
            else:
                # sometimes videoIdOrEpisodeNumber does not work.. this is a workaround
                match = re.search(r'(episode|avsnitt)-(\d+)', self.url)
                if match:
                    episodenr = match.group(2)
                else:
                    episodenr = season
            if "slug" in jansson:
                slug = jansson["slug"]

            if clips:
                return episodenr
            else:
                match = self._conentpage(self.get_urldata())
                if match:
                    janson = json.loads(match.group(1))
                    for i in janson["formatPage"]["format"]["videos"].keys():
                        if "program" in janson["formatPage"]["format"]["videos"][str(i)]:
                            for n in janson["formatPage"]["format"]["videos"][i]["program"]:
                                if str(n["episodeNumber"]) and int(episodenr) == n["episodeNumber"] and int(season) == n["seasonNumber"]:
                                    if slug is None or slug == n["formatSlug"]:
                                        return n["id"]
                                elif n["id"] == episodenr:
                                    return episodenr

        parse = urlparse(self.url)
        match = re.search(r'/\w+/(\d+)', parse.path)
        if match:
            return match.group(1)
        match = re.search(r'iframe src="http://play.juicyplay.se[^\"]+id=(\d+)', html_data)
        if match:
            return match.group(1)

        match = re.search(r'<meta property="og:image" content="([\S]+)"', html_data)
        if match:
            return match.group(1).split("/")[-2]

        return None
864957
def get_embed_url(self):
        
        embed_url = None
        youtube_embed_url = 'https://www.youtube.com/embed/{}'
        vimeo_embed_url = 'https://player.vimeo.com/video/{}'

        # Get video ID from url.
        if re.match(YOUTUBE_URL_RE, self.url):
            embed_url = youtube_embed_url.format(re.match(YOUTUBE_URL_RE, self.url).group(2))
        if re.match(VIMEO_URL_RE, self.url):
            embed_url = vimeo_embed_url.format(re.match(VIMEO_URL_RE, self.url).group(3))
        return embed_url
21924
function getVideoStatistics(auth, youtube, items, count, callback) {

  // Convert the video ID:s of the provided videos to the appropriate format
  var IDs = "";
  if (Array.isArray(items)) {
    for (var i = 0; i < items.length; i++) {
      if (i != 0) {
        IDs += ", "
      }
      IDs += items[i].id.videoId;
    }
  }

  youtube.videos.list( // Call the Youtube API
  {
    auth: auth,
    part: "statistics",
    id: IDs,
    maxResults: count //integer 0-50, default 5
  },
  function(err, res) {
    if (err) {
      console.log("The API returned an error: " + err);
    } else {
      var formatedVideos = formatVideosJson(items, res.data.items); // Format the recieved JSON object filled with videos
      callback(formatedVideos);
    }
  });
}
581844
def fill_subparser(subparser):
    
    subparser.add_argument(
        '--youtube-id', type=str, required=True,
        help=("The YouTube ID of the video from which to extract audio, "
              "usually an 11-character string.")
    )
    return download
165268
function (str) {
        // here:xx:xxx??inline
        var matches = /^<!--\s*here\:(.*?)\s*-->$/.exec(str.trim())
        if (!matches || !matches[1]) return null
        var expr = matches[1]
        var parts = expr.split('??')
        var query = querystring.parse(parts[1] || '')
        var isInline = ('inline' in query) && query.inline != 'false'
        var isWrapping = query.wrap !== 'false'
        var namespace = ''
        var reg

        expr = parts[0]
        parts = expr.split(':')
        if (parts.length > 1) {
            namespace = parts.shift()
        }
        reg = new RegExp(parts.pop())

        return {
            regexp: reg,          // resource match validate regexp
            namespace: namespace, // resource namespace match
            inline: isInline,      // whether inline resource or not
            wrap: isWrapping
        }
    }
1352797
def get_url(song_input, auto):
    '''
    
    '''
    youtube_list = OrderedDict()
    num = 0  # List of songs index

    html = requests.get("https://www.youtube.com/results",
                        params={'search_query': song_input})
    soup = BeautifulSoup(html.text, 'html.parser')

    # In all Youtube Search Results

    for i in soup.findAll('a', {'rel': YOUTUBECLASS}):
        song_url = 'https://www.youtube.com' + (i.get('href'))
        song_title = (i.get('title'))
        # Adds title and song url to dictionary
        youtube_list.update({song_title: song_url})

        if not auto:
            print('(%s) %s' % (str(num + 1), song_title))  # Prints list
            num = num + 1

        elif auto:
            print(song_title)
            return list(youtube_list.values())[0], list(youtube_list.keys())[0]

    # Checks if YouTube search return no results
    if youtube_list == {}:
        log.log_error('No match found!')
        exit()

    # Gets the demanded song title and url
    song_url, song_title = prompt(youtube_list)

    return song_url, song_title
618877
def obtainInfo(self):

        

        try:
            info = self.ytdl.extract_info(self.yid, download=False)
        except youtube_dl.utils.DownloadError:
            raise ConnectionError

        if not self.preferences['stream']:
            self.url = (info['requested_formats'][0]['url'], info['requested_formats'][1]['url'])
            return True

        # else:
        for f in info['formats']:
            if 'filesize' not in f or not f['filesize']:
                f['filesize'] = float('inf') # next line won't fail, infinity, because unknown filesize is the least preferred

        # - for easy sorting - we'll get best quality and lowest filsize
        aud = {(-int(f['abr']),    f['filesize'], f['url']) for f in info['formats'] if f.get('abr') and not f.get('height')}
        vid = {(-int(f['height']), f['filesize'], f['url']) for f in info['formats'] if not f.get('abr') and f.get('height')}
        full= {(-int(f['height']), f['filesize'], f['url']) for f in info['formats'] if f.get('abr') and f.get('height')}

        try:
            _f = int( self.preferences.get('format') ) # if valid format is present, then choose closes value
            _k = lambda x: abs(x[0] + _f) # +, because x[0] is negative

        except (ValueError, TypeError):
            _k = lambda d: d

        if self.preferences['audio'] and self.preferences['video']: fm = sorted(full, key=_k)
        elif self.preferences['audio']: fm = sorted(aud, key=_k)
        elif self.preferences['video']: fm = sorted(vid, key=_k)

        filesize = 0
        i = -1

        try:
            while filesize == 0: # some videos are problematic, we will try to find format with non-zero filesize

                i += 1

                self.url = fm[i][2]
                if fm[i][1] == float('inf'):
                    filesize = int(self.r_session.head(self.url).headers['content-length'])
                else:
                    filesize = int(fm[i][1])

        except IndexError: # finding filesize failed for every format

            self.url = (info['requested_formats'][0]['url'], info['requested_formats'][1]['url'])
            self.preferences['stream'] = False # hopefully non-stream download will work

            return True

        self.filesize = filesize

        return True
831749
public function getVideoId()
    {
        if ($this->getMajorProtocolVersion() == 2) {
            $videoId = $this->getMediaGroup()->getVideoId()->text;
        } else {
            $fullId = $this->getId()->getText();
            $position = strrpos($fullId, '/');
            if ($position === false) {
                require_once 'Zend/Gdata/App/Exception.php';
                throw new Zend_Gdata_App_Exception(
                    'Slash not found in atom:id of ' . $fullId);
            } else {
                $videoId = substr($fullId, $position + 1);
            }
        }
        return $videoId;
    }
1223488
function _getVideo(element) {
		var videoElement = null;

		if (element.tagName === 'VIDEO') {
			videoElement = element;
		}
		else {
			var videos = element.getElementsByTagName('video');
			if (videos[0]) {
				videoElement = videos[0];
			}
		}

		return videoElement;
	}
869001
function getPenId() {
	var url = getParsedUrl();
	var splitPath = url.path.split('/');
	var id = splitPath[splitPath.length - 1];
	return id;
}
903072
public function getVideoId($url)
    {
        // looks like there are, now let's only do this for YouTube and Vimeo
        if($this->getInfo($url)->type == 'video' && ($this->isYouTube($url) || $this->isVimeo($url)))
        {
            if ($this->isYouTube($url))
            {
                return $this->getYouTubeId($url);
            }
            else if ($this->isVimeo($url))
            {
                return $this->getVimeoId($url);
            }
        }
        else
        {
            // return empty string
            return '';
        }
    }
566668
function getPemBody(str) {
    const pemStr = Buffer.isBuffer(str) ? str.toString() : str;
    return pemStr.replace(/(\s*-----(BEGIN|END) ([A-Z0-9- ]+)-----|\r|\n)*/g, '');
}
32533
public static function get_url_id($url)
    {
        $service = self::identify_service($url);
        //TODO use a function for this, it is duplicated
        if ($service == self::YOUTUBE) {
            return self::get_youtube_id($url);
        } elseif ($service == self::VIMEO) {
            return self::get_vimeo_id($url);
        } elseif ($service == self::TWENTYTHREE) {
            return self::get_vimeo_id($url);
        }
        return null;
    }
1228631
protected function _getId($watchUrl) {
        $query = array();
        if (!$watchUrl) {
            throw new Garp_Model_Behavior_YouTubeable_Exception_NoUrl(self::EXCEPTION_NO_URL);
        }

        $url = parse_url($watchUrl);
        if (empty($url['query']) && $url['host'] == 'youtu.be') {
            $videoId = substr($url['path'], 1);
        } elseif (isset($url['query'])) {
            parse_str($url['query'], $query);
            if (isset($query['v']) && $query['v']) {
                $videoId = $query['v'];
            }
        }

        if (!isset($videoId)) {
            throw new Garp_Model_Behavior_YouTubeable_Exception_InvalidUrl(
                sprintf(self::EXCEPTION_INVALID_YOUTUBE_URL, $watchUrl)
            );
        }
        return $videoId;
    }
398045
function parse (str) {
	var params = str.split('_')
	return {
		float: params[0] === 'F',
		signed: params[0] === 'S',
		bitDepth: parseInt(params[1]),
		byteOrder: params[2],
		channels: parseInt(params[3]),
		sampleRate: parseInt(params[4]),
		interleaved: params[5] === 'I'
	}
}
171439
public static function getId($url)
    {
        if (strpos($url, 'youtube.com') !== false) {
            $url = parse_url($url);

            if (empty($url['query'])) {
                return false;
            }

            parse_str($url['query'], $url);

            return empty($url['v']) ? false : $url['v'];
        }

        if (preg_match('/youtu\.be\/([^?]+)/', $url, $matches)) {
            return $matches[1];
        }

        return false;
    }