Programs & Examples On #Youtube api

The YouTube APIs and Tools enable the integration of YouTube's video content and functionality into a website, application, or device.

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

YouTube auto play works only desktop in need to work mobile just make changes in JavaScript. Like

<div id="player"></div>
                    var tag = document.createElement('script');
                    tag.src = "https://www.youtube.com/iframe_api";
                    var firstScriptTag = document.getElementsByTagName('script')[0];
                    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                    var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      videoId: 'VideoID',
      playerVars: {   
            'autoplay': 1,   
            'rel': 0,
            'showinfo': 0,
            'modestbranding': 1,
            'playsinline': 1,
            'showinfo': 0,
            'rel': 0,
            'controls': 0,
            'color':'white',
            'loop': 1,
            'mute':1,
            // 'origin': 'https://meeranblog24x7.blogspot.com/'
      },
      events: {
        'onReady': onPlayerReady,
        // 'onStateChange': onPlayerStateChange
      }
    });
  }
  function onPlayerReady(event) {
    player.playVideo();
    player.mute();
  }var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

 

See More :- YouTube auto play for 5 seconds

Use a content script to access the page context variables and functions

Underlying cause:
Content scripts are executed in an "isolated world" environment.

Solution::
To access functions/variables of the page context ("main world") you have to inject the code into the page itself using DOM. Same thing if you want to expose your functions/variables to the page context (in your case it's the state() method).

  • Note in case communication with the page script is needed:
    Use DOM CustomEvent handler. Examples: one, two, and three.

  • Note in case chrome API is needed in the page script:
    Since chrome.* APIs can't be used in the page script, you have to use them in the content script and send the results to the page script via DOM messaging (see the note above).

Safety warning:
A page may redefine or augment/hook a built-in prototype so your exposed code may fail if the page did it in an incompatible fashion. If you want to make sure your exposed code runs in a safe environment then you should either a) declare your content script with "run_at": "document_start" and use Methods 2-3 not 1, or b) extract the original native built-ins via an empty iframe, example. Note that with document_start you may need to use DOMContentLoaded event inside the exposed code to wait for DOM.

Table of contents

  • Method 1: Inject another file
  • Method 2: Inject embedded code
  • Method 2b: Using a function
  • Method 3: Using an inline event
  • Dynamic values in the injected code

Method 1: Inject another file

This is the easiest/best method when you have lots of code. Include your actual JS code in a file within your extension, say script.js. Then let your content script be as follows (explained here: Google Chome “Application Shortcut” Custom Javascript):

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.runtime.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

Note: For security reasons, Chrome prevents loading of js files. Your file must be added as a "web_accessible_resources" item (example) :

// manifest.json must include: 
"web_accessible_resources": ["script.js"],

If not, the following error will appear in the console:

Denying load of chrome-extension://[EXTENSIONID]/script.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Method 2: Inject embedded code

This method is useful when you want to quickly run a small piece of code. (See also: How to disable facebook hotkeys with Chrome extension?).

var actualCode = `// Code here.
// If you want to use a variable, use $ and curly braces.
// For example, to use a fixed random number:
var someFixedRandomValue = ${ Math.random() };
// NOTE: Do not insert unsafe variables in this way, see below
// at "Dynamic values in the injected code"
`;

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

Note: template literals are only supported in Chrome 41 and above. If you want the extension to work in Chrome 40-, use:

var actualCode = ['/* Code here. Example: */' + 'alert(0);',
                  '// Beware! This array have to be joined',
                  '// using a newline. Otherwise, missing semicolons',
                  '// or single-line comments (//) will mess up your',
                  '// code ----->'].join('\n');

Method 2b: Using a function

For a big chunk of code, quoting the string is not feasible. Instead of using an array, a function can be used, and stringified:

var actualCode = '(' + function() {
    // All code is executed in a local scope.
    // For example, the following does NOT overwrite the global `alert` method
    var alert = null;
    // To overwrite a global variable, prefix `window`:
    window.alert = null;
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

This method works, because the + operator on strings and a function converts all objects to a string. If you intend on using the code more than once, it's wise to create a function to avoid code repetition. An implementation might look like:

function injectScript(func) {
    var actualCode = '(' + func + ')();'
    ...
}
injectScript(function() {
   alert("Injected script");
});

Note: Since the function is serialized, the original scope, and all bound properties are lost!

var scriptToInject = function() {
    console.log(typeof scriptToInject);
};
injectScript(scriptToInject);
// Console output:  "undefined"

Method 3: Using an inline event

Sometimes, you want to run some code immediately, e.g. to run some code before the <head> element is created. This can be done by inserting a <script> tag with textContent (see method 2/2b).

An alternative, but not recommended is to use inline events. It is not recommended because if the page defines a Content Security policy that forbids inline scripts, then inline event listeners are blocked. Inline scripts injected by the extension, on the other hand, still run. If you still want to use inline events, this is how:

var actualCode = '// Some code example \n' + 
                 'console.log(document.documentElement.outerHTML);';

document.documentElement.setAttribute('onreset', actualCode);
document.documentElement.dispatchEvent(new CustomEvent('reset'));
document.documentElement.removeAttribute('onreset');

Note: This method assumes that there are no other global event listeners that handle the reset event. If there is, you can also pick one of the other global events. Just open the JavaScript console (F12), type document.documentElement.on, and pick on of the available events.

Dynamic values in the injected code

Occasionally, you need to pass an arbitrary variable to the injected function. For example:

var GREETING = "Hi, I'm ";
var NAME = "Rob";
var scriptToInject = function() {
    alert(GREETING + NAME);
};

To inject this code, you need to pass the variables as arguments to the anonymous function. Be sure to implement it correctly! The following will not work:

var scriptToInject = function (GREETING, NAME) { ... };
var actualCode = '(' + scriptToInject + ')(' + GREETING + ',' + NAME + ')';
// The previous will work for numbers and booleans, but not strings.
// To see why, have a look at the resulting string:
var actualCode = "(function(GREETING, NAME) {...})(Hi, I'm ,Rob)";
//                                                 ^^^^^^^^ ^^^ No string literals!

The solution is to use JSON.stringify before passing the argument. Example:

var actualCode = '(' + function(greeting, name) { ...
} + ')(' + JSON.stringify(GREETING) + ',' + JSON.stringify(NAME) + ')';

If you have many variables, it's worthwhile to use JSON.stringify once, to improve readability, as follows:

...
} + ')(' + JSON.stringify([arg1, arg2, arg3, arg4]) + ')';

Downloading video from YouTube

To all interested:

The "Coding for fun" book's chapter 4 "InnerTube: Download, Convert, and Sync YouTube Videos" deals with the topic. The code and discussion are at http://www.c4fbook.com/InnerTube.

[PLEASE BEWARE] While the overall concepts are valid some years after the publication, non-documented details of the youtube internals the project relies on can have changed (see the comment at the bottom of the page behind the second link).

How do I get video durations with YouTube API version 3?

This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.

<?php
    function getDuration($videoID){
       $apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
       $dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$videoID&key=$apikey");
       $VidDuration =json_decode($dur, true);
       foreach ($VidDuration['items'] as $vidTime)
       {
           $VidDuration= $vidTime['contentDetails']['duration'];
       }
       preg_match_all('/(\d+)/',$VidDuration,$parts);
       return $parts[0][0] . ":" .
              $parts[0][1] . ":".
              $parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS
    }

    echo getDuration("zyeubYQxHyY"); // Video ID
?>

You can get your domain's own YouTube API key on https://console.developers.google.com and generate credentials for your own requirement.

How to get HQ youtube thumbnails?

You need to get id from:

youtube.com/watch?v=VIDEO_ID

And put this in:

i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg

I hope that I helped :D

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

mine was:

<youtube-player
  [videoId]="'paxSz8UblDs'"
  [playerVars]="playerVars"
  [width]="291"
  [height]="194">
</youtube-player>

I just removed the line with playerVars, and it worked without errors on console.

How to get number of video views with YouTube API?

Use the Google PHP API Client: https://github.com/google/google-api-php-client

Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html

class YouTubeVideo
{
    // video id
    public $id;

    // generate at https://console.developers.google.com/apis
    private $apiKey = 'REPLACE_ME';

    // google youtube service
    private $youtube;

    public function __construct($id)
    {
        $client = new Google_Client();
        $client->setDeveloperKey($this->apiKey);

        $this->youtube = new Google_Service_YouTube($client);

        $this->id = $id;
    }

    /*
     * @return Google_Service_YouTube_VideoStatistics
     * Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )  
     */
    public function getStatistics()
    {
        try{
            // Call the API's videos.list method to retrieve the video resource.
            $response = $this->youtube->videos->listVideos("statistics",
                array('id' => $this->id));

            $googleService = current($response->items);
            if($googleService instanceof Google_Service_YouTube_Video) {
                return $googleService->getStatistics();
            }
        } catch (Google_Service_Exception $e) {
            return sprintf('<p>A service error occurred: <code>%s</code></p>',
                htmlspecialchars($e->getMessage()));
        } catch (Google_Exception $e) {
            return sprintf('<p>An client error occurred: <code>%s</code></p>',
                htmlspecialchars($e->getMessage()));
        }
    }
}

Getting an Embedded YouTube Video to Auto Play and Loop

Had same experience, however what did the magic for me is not to change embed to v.

So the code will look like this...

<iframe width="560" height="315" src="https://www.youtube.com/embed/cTYuscQu-Og?Version=3&loop=1&playlist=cTYuscQu-Og" frameborder="0" allowfullscreen></iframe>

Hope it helps...

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

Stop embedded youtube iframe?

Easiest ways is

var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');

How to pause a YouTube player when hiding the iframe?

The easiest way to implement this behaviour is by calling the pauseVideo and playVideo methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.

The only adjustments:

  • I have added a function, toggleVideo
  • I have added ?enablejsapi=1 to YouTube's URL, to enable the feature

Demo: http://jsfiddle.net/ZcMkt/
Code:

<script>
function toggleVideo(state) {
    // if state == 'hide', hide. Else: show video
    var div = document.getElementById("popupVid");
    var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
    div.style.display = state == 'hide' ? 'none' : '';
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>

<p><a href="javascript:;" onClick="toggleVideo();">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>

<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
   <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
   <br /><br />
   <a href="javascript:;" onClick="toggleVideo('hide');">close</a>

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I think I encountered the same problem as you. I addressed this problem with the following steps:

1) Go to Google Developers Console

2) Set JavaScript origins:

3) Set Redirect URIs:

How to embed YouTube videos in PHP?

You can simply create a php input form for Varchar date,give it a varchar length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Looks like YouTube has updated their JS API so this is available by default! You can use an existing YouTube iframe's ID...

<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>

...in your JS...

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    events: {
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerStateChange() {
  //...
}

...and the constructor will use your existing iframe instead of replacing it with a new one. This also means you don't have to specify the videoId to the constructor.

See Loading a video player

YouTube API to fetch all videos on a channel

Using API version 2, which is deprecated, the URL for uploads (of channel UCqAEtEr0A0Eo2IVcuWBfB9g) is:

https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads

There is an API version 3.

Embed YouTube Video with No Ads

Whether ads are shown on a video is up to the content owner of that video. It's not something that the embedder can control.

If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.

(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)

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

You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk

First, get the formats of the video:

?  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
137          mp4        1920x1080  DASH video 4347k , avc1.640028, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k
96           mp4        1080p      HLS , h264, aac  @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam

In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f to pass in the format you would like to watch, and -g to get that stream's URL:

?  ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8

These are your HLS m3u8 playlists, one for each camera associated with the live stream.

Without youtube-dl, your flow might look like this:

Take your video id and make a GET request to the get_video_info endpoint:

HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en

In the response, the hlsvp value will be the link to the m3u8 HLS playlist:

https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8

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

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

You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).

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

What Asaph said is right. However, not every YouTube video contains all nine thumbnails. Also, the thumbnails' image sizes depends on the video (the numbers below are based on one). There are some thumbnails guaranteed to exist:

Width | Height | URL
------|--------|----
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/1.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/2.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/3.jpg
120   | 90     | https://i.ytimg.com/vi/<VIDEO ID>/default.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq1.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq2.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mq3.jpg
320   | 180    | https://i.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/0.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq1.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq2.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hq3.jpg
480   | 360    | https://i.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg

Additionally, the some other thumbnails may or may not exist. Their presence is probably based on whether the video is high-quality.

Width | Height | URL
------|--------|----
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd1.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd2.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sd3.jpg
640   | 480    | https://i.ytimg.com/vi/<VIDEO ID>/sddefault.jpg
1280  | 720    | https://i.ytimg.com/vi/<VIDEO ID>/hq720.jpg
1920  | 1080   | https://i.ytimg.com/vi/<VIDEO ID>/maxresdefault.jpg

You can find JavaScript and PHP scripts to retrieve thumbnails and other YouTube information in:

You can also use the YouTube Video Information Generator tool to get all the information about a YouTube video by submitting a URL or video id.

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
});

Running bash script from within python

If chmod not working then you also try

import os
os.system('sh script.sh')
#you can also use bash instead of sh

test by me thanks

How to create <input type=“text”/> dynamically

You could use createElement() method for creating that textbox

How to force garbage collector to run?

GC.Collect() 

from MDSN,

Use this method to try to reclaim all memory that is inaccessible.

All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

How can I get screen resolution in java?

These three functions return the screen size in Java. This code accounts for multi-monitor setups and task bars. The included functions are: getScreenInsets(), getScreenWorkingArea(), and getScreenTotalArea().

Code:

/**
 * getScreenInsets, This returns the insets of the screen, which are defined by any task bars
 * that have been set up by the user. This function accounts for multi-monitor setups. If a
 * window is supplied, then the the monitor that contains the window will be used. If a window
 * is not supplied, then the primary monitor will be used.
 */
static public Insets getScreenInsets(Window windowOrNull) {
    Insets insets;
    if (windowOrNull == null) {
        insets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration());
    } else {
        insets = windowOrNull.getToolkit().getScreenInsets(
                windowOrNull.getGraphicsConfiguration());
    }
    return insets;
}

/**
 * getScreenWorkingArea, This returns the working area of the screen. (The working area excludes
 * any task bars.) This function accounts for multi-monitor setups. If a window is supplied,
 * then the the monitor that contains the window will be used. If a window is not supplied, then
 * the primary monitor will be used.
 */
static public Rectangle getScreenWorkingArea(Window windowOrNull) {
    Insets insets;
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        insets = Toolkit.getDefaultToolkit().getScreenInsets(ge.getDefaultScreenDevice()
                .getDefaultConfiguration());
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        insets = windowOrNull.getToolkit().getScreenInsets(gc);
        bounds = gc.getBounds();
    }
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    return bounds;
}

/**
 * getScreenTotalArea, This returns the total area of the screen. (The total area includes any
 * task bars.) This function accounts for multi-monitor setups. If a window is supplied, then
 * the the monitor that contains the window will be used. If a window is not supplied, then the
 * primary monitor will be used.
 */
static public Rectangle getScreenTotalArea(Window windowOrNull) {
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        bounds = gc.getBounds();
    }
    return bounds;
}

Adding files to java classpath at runtime

My solution:

File jarToAdd = new File("/path/to/file");

new URLClassLoader(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()) {
    @Override
    public void addURL(URL url) {
         super.addURL(url);
    }
}.addURL(jarToAdd.toURI().toURL());

HTML select dropdown list

If you want to achieve the same for the jquery-ui selectmenu control then you have to set 'display: none' in the open event handler and add '-menu' to the id string.

<select id="myid">
<option value="" disabled="disabled" selected="selected">Please select     name</option>
 <option value="Tom">Tom</option>
 <option value="Marry">Mary</option>
 <option value="Jane">Jane</option>
 <option value="Harry">Harry</option>
 </select>

$('select#listsTypeSelect').selectmenu({
  change: function( event, data ) {
    alert($(this).val());
},
open: function( event, ui ) {
    $('ul#myid-menu li:first-child').css('display', 'none');
}
});

Django: TemplateSyntaxError: Could not parse the remainder

In templates/admin/includes_grappelli/header.html, line 12, you forgot to put admin:password_change between '.

The url Django tag syntax should always be like:

{% url 'your_url_name' %}

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

android: how to use getApplication and getApplicationContext from non activity / service class

The getApplication() method is located in the Activity class, so whenever you want getApplication() in a non activity class you have to pass an Activity instance to the constructor of that non activity class.

assume that test is my non activity class:

Test test = new Test(this);

In that class i have created one constructor:

 public Class Test
 {
    public Activity activity;
    public Test (Activity act)
    {
         this.activity = act;
         // Now here you can get getApplication()
    }
 }

BULK INSERT with identity (auto-increment) column

I had this exact same problem which made loss hours so i'm inspired to share my findings and solutions that worked for me.

1. Use an excel file

This is the approach I adopted. Instead of using a csv file, I used an excel file (.xlsx) with content like below.

id  username   email                token website

    johndoe   [email protected]        divostar.com
    bobstone  [email protected]        divosays.com

Notice that the id column has no value.

Next, connect to your DB using Microsoft SQL Server Management Studio and right click on your database and select import data (submenu under task). Select Microsoft Excel as source. When you arrive at the stage called "Select Source Tables and Views", click edit mappings. For id column under destination, click on it and select ignore . Don't check Enable Identity insert unless you want to mantain ids incases where you are importing data from another database and would like to maintain the auto increment id of the source db. Proceed to finish and that's it. Your data will be imported smoothly.

2. Using CSV file

In your csv file, make sure your data is like below.

id,username,email,token,website
,johndoe,[email protected],,divostar.com
,bobstone,[email protected],,divosays.com

Run the query below:

BULK INSERT Metrics FROM 'D:\Data Management\Data\CSV2\Production Data 2004 - 2016.csv '
WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n');

The problem with this approach is that the CSV should be in the DB server or some shared folder that the DB can have access to otherwise you may get error like "Cannot opened file. The operating system returned error code 21 (The device is not ready)".

If you are connecting to a remote database, then you can upload your CSV to a directory on that server and reference the path in bulk insert.

3. Using CSV file and Microsoft SQL Server Management Studio import option

Launch your import data like in the first approach. For source, select Flat file Source and browse for your CSV file. Make sure the right menu (General, Columns, Advanced, Preview) are ok. Make sure to set the right delimiter under columns menu (Column delimiter). Just like in the excel approach above, click edit mappings. For id column under destination, click on it and select ignore .

Proceed to finish and that's it. Your data will be imported smoothly.

Replace a string in shell script using a variable

To let your shell expand the variable, you need to use double-quotes like

sed -i "s#12345678#$replace#g" file.txt

This will break if $replace contain special sed characters (#, \). But you can preprocess $replace to quote them:

replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
sed -i "s#12345678#$replace_quoted#g" file.txt

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

How do you add CSS with Javascript?

use .css in Jquery like $('strong').css('background','red');

_x000D_
_x000D_
$('strong').css('background','red');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<strong> Example_x000D_
</strong> 
_x000D_
_x000D_
_x000D_

git-diff to ignore ^M

I struggled with this problem for a long time. By far the easiest solution is to not worry about the ^M characters and just use a visual diff tool that can handle them.

Instead of typing:

git diff <commitHash> <filename>

try:

git difftool <commitHash> <filename>

How to change file encoding in NetBeans?

This link answer your question: http://wiki.netbeans.org/FaqI18nProjectEncoding

You can change the sources encoding or runtime encoding.

Unable to connect PostgreSQL to remote database using pgAdmin

Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

  1. Open PuTTY. If you already have a session set up to connect to the EC2 instance, load that, but don't connect to it just yet. If you don't have such a session, see this post.
  2. Go to Connection > SSH > Tunnels
  3. Enter 5433 in the Source Port field.
  4. Enter 127.0.0.1:5432 in the Destination field.
  5. Click the "Add" button.
  6. Go back to Session, and save your session, then click "Open" to connect.
  7. This opens a terminal window. Once you're connected, you can leave that alone.
  8. Open pgAdmin and add a connection.
  9. Enter localhost in the Host field and 5433 in the Port field. Specify a Name for the connection, and the username and password. Click OK when you're done.

Why do I get access denied to data folder when using adb?

if you know the application package you can cd directly to that folder..

eg cd data/data/com.yourapp

this will drop you into a directory that is read/writable so you can change files as needed. Since the folder is the same on the emulator, you can use that to get the folder path.

Python can't find module in the same folder

I had a similar problem, I solved it by explicitly adding the file's directory to the path list:

import os
import sys

file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)

After that, I had no problem importing from the same directory.

Display JSON Data in HTML Table

There are many plugins for doing that. I normally use datatables it works great. http://datatables.net/

The term 'ng' is not recognized as the name of a cmdlet

I was getting this error in Visual Studio Code while doing ng-build. Running below command in cmd fixed my issue

npm install -g @angular/cli@latest

PHP float with 2 decimal places: .00

You can use round function

round("10.221",2);

Will return 10.22

How to change current working directory using a batch file

Specify /D to change the drive also.

CD /D %root%

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.

Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file

$("#register-form").submit(function (event) {

    var entrance = $(this).find('input[name="IsValid"]').val();
    var password = $(this).find('input[name="objPassword"]').val();
    var namesurname = $(this).find('input[name="objNameSurname"]').val();
    var email = $(this).find('input[name="objEmail"]').val();
    var gsm = $(this).find('input[name="objGsm"]').val();
    var adres = $(this).find('input[name="objAddress"]').val();
    var termsOk = $(this).find('input[name="objAcceptTerms"]').val();

    var formURL = $(this).attr("action");


    if (request) {
        request.abort(); // cancel if any process on pending
    }

    var postData = {
        "objAskGrant": entrance,
        "objPass": password,
        "objNameSurname": namesurname,
        "objEmail": email,
        "objGsm": parseInt(gsm),
        "objAdres": adres,
        "objTerms": termsOk
    };

    $.post(formURL,postData,function(data,status){
        console.log("Data: " + data + "\nStatus: " + status);
    });

    event.preventDefault();
});

PHP Edit:

 if (isset($_POST)) {

    $fValid = clear($_POST['objAskGrant']);
    $fTerms = clear($_POST['objTerms']);

    if ($fValid) {
        $fPass = clear($_POST['objPass']);
        $fNameSurname = clear($_POST['objNameSurname']);
        $fMail = clear($_POST['objEmail']);
        $fGsm = clear(int($_POST['objGsm']));
        $fAddress = clear($_POST['objAdres']);
        $UserIpAddress = "hidden";
        $UserCityLocation = "hidden";
        $UserCountry = "hidden";

        $DateTime = new DateTime();
        $result = $date->format('d-m-Y-H:i:s');
        $krr = explode('-', $result);
        $resultDateTime = implode("", $krr);

        $data = array('error' => 'Yükleme Sirasinda Hata Olustu');

        $kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
        $retval = mysql_query( $kayit, $conn ); // Update with you connection details
            if ($retval) {
                $data = array('success' => 'Register Completed', 'postData' => $_POST);
            }

        } // valid ends
    }echo json_encode($data);

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

How to change the name of a Django app?

New in Django 1.7 is a app registry that stores configuration and provides introspection. This machinery let's you change several app attributes.

The main point I want to make is that renaming an app isn't always necessary: With app configuration it is possible to resolve conflicting apps. But also the way to go if your app needs friendly naming.

As an example I want to name my polls app 'Feedback from users'. It goes like this:

Create a apps.py file in the polls directory:

from django.apps import AppConfig

class PollsConfig(AppConfig):
    name = 'polls'
    verbose_name = "Feedback from users"

Add the default app config to your polls/__init__.py:

default_app_config = 'polls.apps.PollsConfig'

For more app configuration: https://docs.djangoproject.com/en/1.7/ref/applications/

Convert DataTable to CSV stream

You can try using something like this. In this case I used one stored procedure to get more data tables and export all of them using CSV.

using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace bo
{
class Program
{
    static private void CreateCSVFile(DataTable dt, string strFilePath)
    {
        #region Export Grid to CSV
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        int iColCount = dt.Columns.Count;

        // First we will write the headers.

        //DataTable dt = m_dsProducts.Tables[0];
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(";");
            }
        }
        sw.Write(sw.NewLine);

        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount -1 )
                {
                    sw.Write(";");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();

        #endregion
    }
    static void Main(string[] args)
    {
        string strConn = "connection string to sql";
        string direktorij = @"d:";
        SqlConnection conn = new SqlConnection(strConn); 
        SqlCommand command = new SqlCommand("sp_ado_pos_data", conn);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add('@skl_id', SqlDbType.Int).Value = 158;
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            string datoteka  = (string.Format(@"{0}tablea{1}.csv", direktorij, i));
            DataTable tabela = ds.Tables[i];
            CreateCSVFile(tabela,datoteka );
            Console.WriteLine("Generišem tabelu {0}", datoteka);
        }
        Console.ReadKey();
    }
  }
}

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

restrict edittext to single line

Now android:singleLine attribute is deprecated. Please add these attributes to your EditText for an EditText to be single line.

android:inputType="text"
android:imeOptions="actionNext"
android:maxLines="1"

ssh "permissions are too open" error

provide 400 permission, execute below command

chmod 400 /Users/username/.ssh/id_rsa

enter image description here

Format number to always show 2 decimal places

Here's also a generic function that can format to any number of decimal places:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}

Split Java String by New Line

This should cover you:

String lines[] = string.split("\\r?\\n");

There's only really two newlines (UNIX and Windows) that you need to worry about.

How to put multiple statements in one line?

Its acctualy possible ;-)

# not pep8 compatible^
sam = ['Sam',]
try: print('hello',sam) if sam[0] != 'harry' else rais
except: pass

You can do very ugly stuff in python like:

def o(s):return''.join([chr(ord(n)+(13if'Z'<n<'n'or'N'>n else-13))if n.isalpha()else n for n in s])

which is function for rot13/cesa encryption in one line with 99 characters.

TypeError: can only concatenate list (not "str") to list

Let me fix your code

inventory=["sword", "potion", "armour", "bow"]
print(inventory)
print("\ncommands: use (remove) and pickup (add)")
selection=input("choose a command [use/pickup]")

if selection == "use":
    print(inventory)
    inventory.remove(input("What do you want to use? "))
    print(inventory)
elif selection == "pickup":
    print(inventory)
    add=input("What do you want to pickup? ")
    newinv=inventory+[str(add)] #use '[str(add)]' or list(str(add))
    print(newinv)

The error is you are adding string and list, you should use list or [] to make the string become list type

Mobile Safari: Javascript focus() method on inputfield only works with click?

Please try using on-tap instead of ng-click event. I had this issue. I resolved it by making my clear-search-box button inside search form label and replaced ng-click of clear-button by on-tap. It works fine now.

Android: How can I validate EditText input?

This was nice solution from here

InputFilter filter= new InputFilter() { 
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
        for (int i = start; i < end; i++) { 
            String checkMe = String.valueOf(source.charAt(i));

            Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
            Matcher matcher = pattern.matcher(checkMe);
            boolean valid = matcher.matches();
            if(!valid){
                Log.d("", "invalid");
                return "";
            }
        } 
        return null; 
    } 
};

edit.setFilters(new InputFilter[]{filter}); 

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges happens when the object exists in the schema but do not have any access to that object.

ORA-00942: table or view does not exist happens when the object does not exist in the current schema. If the object exists in another schema, you need to access it using .. Still you can get insufficient privileges error if the owner has not given access to the calling schema.

how to change php version in htaccess in server

To switch to PHP 4.4:

AddHandler application/x-httpd-php4 .php .php4 .php3

To switch to PHP 5.0:

AddHandler application/x-httpd-php5 .php .php5 .php4 .php3

To switch to PHP 5.1:

AddHandler application/x-httpd-php51 .php .php5 .php4 .php3

To switch to PHP 5.2:

AddHandler application/x-httpd-php52 .php .php5 .php4 .php3

To switch to PHP 5.3:

AddHandler application/x-httpd-php53 .php .php5 .php4 .php3

To switch to PHP 5.4:

AddHandler application/x-httpd-php54 .php .php5 .php4 .php3

To switch to PHP 5.5:

AddHandler application/x-httpd-php55 .php .php5 .php4 .php3

To switch to the secure PHP 5.2 with Suhosin patch:

AddHandler application/x-httpd-php52s .php .php5 .php4 .php3

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

The embed URL for a channel's live stream is:

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

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

Ant is using wrong java version

According to the Ant Documentation, set JAVACMD environment variable to complete path to java.exe of the JRE version that you want to run Ant under.

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

This solution may help you if you know your problem is limited to Facades and you are running Laravel 5.5 or above.

Install laravel-ide-helper

composer require --dev barryvdh/laravel-ide-helper

Add this conditional statement in your AppServiceProvider to register the helper class.

public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

Then run php artisan ide-helper:generate to generate a file to help the IDE understand Facades. You will need to restart Visual Studio Code.

References

https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/16

https://github.com/barryvdh/laravel-ide-helper

How to know Laravel version and where is it defined?

  1)  php artisan -V

  2)  php artisan --version

AND its define at the composer.json file

"require": {
        ...........
        "laravel/framework": "^6.2",
        ...........
    },

Visual Studio popup: "the operation could not be completed"

I ran into this same problem but deleting the .suo file did not help. The only way I could get the project to load was by deleting the "Your_Project_FileName.csproj.user" file.

--

I ran into this problem again a few months later but this time deleting the "Your_Project_FileName.csproj.user" file didn't help like it did last time. I finally managed to track it down to an IIS Express issue. I removed the site from my applicationhost.config and let Visual Studio recreate it, this allowed the project to finally be loaded.

Bash script to run php script

If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this:

#!/usr/bin/php

Put that at the top of your script, make it executable (chmod +x myscript.php), and make a Cron job to execute that script (same way you'd execute a bash script).

You can also use php myscript.php.

How to redirect to previous page in Ruby On Rails?

For those who are interested, here is my implementation extending MBO's original answer (written against rails 4.2.4, ruby 2.1.5).

class ApplicationController < ActionController::Base
  after_filter :set_return_to_location

  REDIRECT_CONTROLLER_BLACKLIST = %w(
    sessions
    user_sessions
    ...
    etc.
  )

  ...

  def set_return_to_location
    return unless request.get?
    return unless request.format.html?
    return unless %w(show index edit).include?(params[:action])
    return if REDIRECT_CONTROLLER_BLACKLIST.include?(controller_name)
    session[:return_to] = request.fullpath
  end

  def redirect_back_or_default(default_path = root_path)
    redirect_to(
      session[:return_to].present? && session[:return_to] != request.fullpath ?
        session[:return_to] : default_path
    )
  end
end

Display open transactions in MySQL

You can use show innodb status (or show engine innodb status for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.

You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.

Here's what you'd want to look for:

------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status

In this case, there's just one connection to the InnoDB engine right now (my login, running the show query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594.

How to use gitignore command in git

So based on what you said, these files are libraries/documentation you don't want to delete but also don't want to push to github. Let say you have your project in folder your_project and a doc directory: your_project/doc.

  1. Remove it from the project directory (without actually deleting it): git rm --cached doc/*
  2. If you don't already have a .gitignore, you can make one right inside of your project folder: project/.gitignore.
  3. Put doc/* in the .gitignore
  4. Stage the file to commit: git add project/.gitignore
  5. Commit: git commit -m "message".
  6. Push your change to github.

Date to milliseconds and back to date in Swift

As @Travis Solution works but in some cases

var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

with error

Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

Here is Updated Answer

extension Date {
 var millisecondsSince1970:Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
        //RESOLVED CRASH HERE
    }

    init(milliseconds:Int) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
    }
}

About Int definitions.

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

Hope it is helpful to someone who also has same problem

How to escape special characters in building a JSON string?

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

Image showing the definition of a string from the JSON spec

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u followed by four-hex-digits

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.

Split List into Sublists with LINQ

The question was how to "Split List into Sublists with LINQ", but sometimes you may want those sub-lists to be references to the original list, not copies. This allows you to modify the original list from the sub-lists. In that case, this may work for you.

public static IEnumerable<Memory<T>> RefChunkBy<T>(this T[] array, int size)
{
    if (size < 1 || array is null)
    {
        throw new ArgumentException("chunkSize must be positive");
    }

    var index = 0;
    var counter = 0;

    for (int i = 0; i < array.Length; i++)
    {
        if (counter == size)
        {
            yield return new Memory<T>(array, index, size);
            index = i;
            counter = 0;
        }
        counter++;

        if (i + 1 == array.Length)
        {
            yield return new Memory<T>(array, index, array.Length - index);
        }
    }
}

Usage:

var src = new[] { 1, 2, 3, 4, 5, 6 };

var c3 = RefChunkBy(src, 3);      // {{1, 2, 3}, {4, 5, 6}};
var c4 = RefChunkBy(src, 4);      // {{1, 2, 3, 4}, {5, 6}};

// as extension method
var c3 = src.RefChunkBy(3);      // {{1, 2, 3}, {4, 5, 6}};
var c4 = src.RefChunkBy(4);      // {{1, 2, 3, 4}, {5, 6}};

var sum = c3.Select(c => c.Span.ToArray().Sum());    // {6, 15}
var count = c3.Count();                 // 2
var take2 = c3.Select(c => c.Span.ToArray().Take(2));  // {{1, 2}, {4, 5}}

Feel free to make this code better.

Best way to do a split pane in HTML

In the old days, you would use frames to achieve this. There are several reasons why this approach is not so good. See Reece's response to Why are HTML frames bad?. See also Jakob Nielson's Why Frames Suck (Most of the Time).

A somewhat newer approach is to use inline frames. This has pluses and minuses as well: Are iframes considered 'bad practice'?

An even better approach is to use fixed positioning. By placing the navigation content (e.g. the favorites links in your example) in a block element (like a div) then applying position:fixed to that element and setting the left, top and bottom properties like this:

#myNav {
    position: fixed;
    left: 0px;
    top: 0px;
    bottom: 0px;
    width: 200px;
}

... you will achieve a vertical column down the left side of the page that will not move when the user scrolls the page.

The rest of the content on the page will not "feel" the presence of this nav element, so it must take into account the 200px of space it occupies. You can do this by placing the rest for the content in another div and setting margin-left:200px;.

Is Java RegEx case-insensitive?

You can also match case insensitive regexs and make it more readable by using the Pattern.CASE_INSENSITIVE constant like:

Pattern mypattern = Pattern.compile(MYREGEX, Pattern.CASE_INSENSITIVE);
Matcher mymatcher= mypattern.matcher(mystring);

Alter user defined type in SQL Server

Simple DROP TYPE first then CREATE TYPE again with corrections/alterations?

There is a simple test to see if it is defined before you drop it ... much like a table, proc or function -- if I wasn't at work I would look what that is?

(I only skimmed above too ... if I read it wrong I apologise in advance! ;)

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

Remove an onclick listener

    /**
 * Remove an onclick listener
 *
 * @param view
 * @author [email protected]
 * @website https://github.com/androidmalin
 * @data 2016-05-16
 */
public static void unBingListener(View view) {
    if (view != null) {
        try {
            if (view.hasOnClickListeners()) {
                view.setOnClickListener(null);

            }

            if (view.getOnFocusChangeListener() != null) {
                view.setOnFocusChangeListener(null);

            }

            if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
                ViewGroup viewGroup = (ViewGroup) view;
                int viewGroupChildCount = viewGroup.getChildCount();
                for (int i = 0; i < viewGroupChildCount; i++) {
                    unBingListener(viewGroup.getChildAt(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

What does the ">" (greater-than sign) CSS selector mean?

html
<div>
    <p class="some_class">lohrem text (it will be of red color )</p>    
    <div>
        <p class="some_class">lohrem text (it will  NOT be of red color)</p> 
    </div>
    <p class="some_class">lohrem text (it will be  of red color )</p>
</div>
css
div > p.some_class{
    color:red;
}

All the direct children that are <p> with .some_class would get the style applied to them.

How to export data from Spark SQL to CSV

The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:

df.coalesce(1).
    write.
    format("com.databricks.spark.csv").
    option("header", "true").
    save("myfile.csv")

and rename the output of the lib (name "part-00000") to a desire filename.

This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/

Printing string variable in Java

You could also use BufferedReader:

import java.io.*;

public class TestApplication {
   public static void main (String[] args) {
      System.out.print("Enter a password: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String password = null;
      try {
         password = br.readLine();
      } catch (IOException e) {
         System.out.println("IO error trying to read your password!");
         System.exit(1);
      }
      System.out.println("Successfully read your password.");
   }
}

How can I add a new column and data to a datatable that already contains data?

Try this

> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like  or  or any no]["Column name in which you want to add data"] = Value;

Using :after to clear floating elements

Write like this:

.wrapper:after {
    content: '';
    display: block;
    clear: both;
}

Check this http://jsfiddle.net/EyNnk/1/

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

How to draw a filled triangle in android canvas?

You probably need to do something like :

Paint red = new Paint();

red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.

Tell me if it works please !

Inline JavaScript onclick function

This should work

 <a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>

You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block

Where do I find the definition of size_t?

In minimalistic programs where a size_t definition was not loaded "by chance" in some include but I still need it in some context (for example to access std::vector<double>), then I use that context to extract the correct type. For example typedef std::vector<double>::size_type size_t.

(Surround with namespace {...} if necessary to make the scope limited.)

PHP MySQL Query Where x = $variable

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

This was a Tomcat bug that resurfaced again with the Java 9 bytecode. The exact versions which fix this (for both Java 8/9 bytecode) are:

  • trunk for 9.0.0.M18 onwards
  • 8.5.x for 8.5.12 onwards
  • 8.0.x for 8.0.42 onwards
  • 7.0.x for 7.0.76 onwards

Why does the 'int' object is not callable error occur when using the sum() function?

You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.

To fix this, restart your interpreter.

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

If you shadow the sum builtin, you can get the error you are seeing

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Also, note that sum will work fine on the set there is no need to convert it to a list

Visual Studio : short cut Key : Duplicate Line

if you have a macos version, cmd+shift+D can make the job for you

TypeScript for ... of with index / key?

You can use the for..in TypeScript operator to access the index when dealing with collections.

var test = [7,8,9];
for (var i in test) {
   console.log(i + ': ' + test[i]);
} 

Output:

 0: 7
 1: 8
 2: 9

See Demo

Read JSON data in a shell script

Here is a crude way to do it: Transform JSON into bash variables to eval them.

This only works for:

  • JSON which does not contain nested arrays, and
  • JSON from trustworthy sources (else it may confuse your shell script, perhaps it may even be able to harm your system, You have been warned)

Well, yes, it uses PERL to do this job, thanks to CPAN, but is small enough for inclusion directly into a script and hence is quick and easy to debug:

json2bash() {
perl -MJSON -0777 -n -E 'sub J {
my ($p,$v) = @_; my $r = ref $v;
if ($r eq "HASH") { J("${p}_$_", $v->{$_}) for keys %$v; }
elsif ($r eq "ARRAY") { $n = 0; J("$p"."[".$n++."]", $_) foreach @$v; }
else { $v =~ '"s/'/'\\\\''/g"'; $p =~ s/^([^[]*)\[([0-9]*)\](.+)$/$1$3\[$2\]/;
$p =~ tr/-/_/; $p =~ tr/A-Za-z0-9_[]//cd; say "$p='\''$v'\'';"; }
}; J("json", decode_json($_));'
}

use it like eval "$(json2bash <<<'{"a":["b","c"]}')"

Not heavily tested, though. Updates, warnings and more examples see my GIST.

Update

(Unfortunately, following is a link-only-solution, as the C code is far too long to duplicate here.)

For all those, who do not like the above solution, there now is a C program json2sh which (hopefully safely) converts JSON into shell variables. In contrast to the perl snippet, it is able to process any JSON, as long as it is well formed.

Caveats:

  • json2sh was not tested much.
  • json2sh may create variables, which start with the shellshock pattern () {

I wrote json2sh to be able to post-process .bson with Shell:

bson2json()
{
printf '[';
{ bsondump "$1"; echo "\"END$?\""; } | sed '/^{/s/$/,/';
echo ']';
};

bsons2json()
{
printf '{';
c='';
for a;
do
  printf '%s"%q":' "$c" "$a";
  c=',';
  bson2json "$a";
done;
echo '}';
};

bsons2json */*.bson | json2sh | ..

Explained:

  • bson2json dumps a .bson file such, that the records become a JSON array
    • If everything works OK, an END0-Marker is applied, else you will see something like END1.
    • The END-Marker is needed, else empty .bson files would not show up.
  • bsons2json dumps a bunch of .bson files as an object, where the output of bson2json is indexed by the filename.

This then is postprocessed by json2sh, such that you can use grep/source/eval/etc. what you need, to bring the values into the shell.

This way you can quickly process the contents of a MongoDB dump on shell level, without need to import it into MongoDB first.

IOException: Too many open files

You can handle the fds yourself. The exec in java returns a Process object. Intermittently check if the process is still running. Once it has completed close the processes STDERR, STDIN, and STDOUT streams (e.g. proc.getErrorStream.close()). That will mitigate the leaks.

Bootstrap 3 Align Text To Bottom of Div

You can do this:

CSS:

#container {
    height:175px;
}

#container h3{
    position:absolute;
    bottom:0;
    left:0;
}

Then in HTML:

<div class="row">
    <div class="col-sm-6">
        <img src="//placehold.it/600x300" alt="Logo" />
    </div>
    <div id="container" class="col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

EDIT: add the <

How can I change the current URL?

<script> 
    var url= "http://www.google.com"; 
    window.location = url; 
</script> 

Open existing file, append a single line

We can use

public StreamWriter(string path, bool append);

while opening the file

string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);

First parameter is a string to hold a full file path Second parameter is Append Mode, that in this case is made true

Writing to the file can be done with:

writer.Write(string)

or

writer.WriteLine(string)

Sample Code

private void WriteAndAppend()
{
            string Path = Application.StartupPath + "\\notes.txt";
            FileInfo fi = new FileInfo(Path);
            StreamWriter SW;
            StreamReader SR;
            if (fi.Exists)
            {
                SR = new StreamReader(Path);
                string Line = "";
                while (!SR.EndOfStream) // Till the last line
                {
                    Line = SR.ReadLine();
                }
                SR.Close();
                int x = 0;
                if (Line.Trim().Length <= 0)
                {
                    x = 0;
                }
                else
                {
                    x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
                }
                x++;
                SW = new StreamWriter(Path, true);
                SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine(x.ToString() + "." + textBox1.Text);

            }
            else
            {
                SW = new StreamWriter(Path);
                SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
                SW.WriteLine("1." + textBox1.Text);
            }
            SW.Flush();
            SW.Close();
        }

List of standard lengths for database fields

I wanted to find the same and the UK Government Data Standards mentioned in the accepted answer sounded ideal. However none of these seemed to exist any more - after an extended search I found it in an archive here: http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards.aspx. Need to download the zip, extract it and then open default.htm in the html folder.

Run javascript script (.js file) in mongodb including another file inside js

Yes you can. The default location for script files is data/db

If you put any script there you can call it as

load("myjstest.js")      // or 
load("/data/db/myjstest.js")

Smooth scroll without the use of jQuery

<script>
var set = 0;

function animatescroll(x, y) {
    if (set == 0) {
        var val72 = 0;
        var val73 = 0;
        var setin = 0;
        set = 1;

        var interval = setInterval(function() {
            if (setin == 0) {
                val72++;
                val73 += x / 1000;
                if (val72 == 1000) {
                    val73 = 0;
                    interval = clearInterval(interval);
                }
                document.getElementById(y).scrollTop = val73;
            }
        }, 1);
    }
}
</script>

x = scrollTop
y = id of the div that is used to scroll

Note: For making the body to scroll give the body an ID.

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

How to add a custom right-click menu to a webpage?

You should remember if you want to use the Firefox only solution, if you want to add it to the whole document you should add contextmenu="mymenu" to the <html> tag not to the body tag.
You should pay attention to this.

How does one output bold text in Bash?

I assume bash is running on a vt100-compatible terminal in which the user did not explicitly turn off the support for formatting.

First, turn on support for special characters in echo, using -e option. Later, use ansi escape sequence ESC[1m, like:

echo -e "\033[1mSome Text"

More on ansi escape sequences for example here: ascii-table.com/ansi-escape-sequences-vt-100.php

How to get process ID of background process?

You can use the jobs -l command to get to a particular jobL

^Z
[1]+  Stopped                 guard

my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18           guard

In this case, 46841 is the PID.

From help jobs:

-l Report the process group ID and working directory of the jobs.

jobs -p is another option which shows just the PIDs.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Check in Deployment Assembly,

I have the same error, when i generate the war file with the "maven clean install" way and deploy manualy, it works fine, but when i use the runtime enviroment (eclipse) the problems come.

The solution for me (for eclipse IDE) go to: "proyect properties" --> "Deployment Assembly" --> "Add" --> "the jar you need", in my case java "build path entries". Maybe can help a litle!

PG COPY error: invalid input syntax for integer

All in python (using psycopg2), create the empty table first then use copy_expert to load the csv into it. It should handle for empty values.

import psycopg2
conn = psycopg2.connect(host="hosturl", database="db_name", user="username", password="password")
cur = conn.cursor()
cur.execute("CREATE TABLE schema.destination_table ("
            "age integer, "
            "first_name varchar(20), "
            "last_name varchar(20)"
            ");")

with open(r'C:/tmp/people.csv', 'r') as f:
    next(f)  # Skip the header row. Or remove this line if csv has no header.
    conn.cursor.copy_expert("""COPY schema.destination_table FROM STDIN WITH (FORMAT CSV)""", f)

How to convert integers to characters in C?

void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);
     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

What is an .axd file?

from Google

An .axd file is a HTTP Handler file. There are two types of .axd files.

  1. ScriptResource.axd
  2. WebResource.axd

These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.

Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere

And ofcourse it is necessary

How to Update a Component without refreshing full page - Angular

You can use a BehaviorSubject for communicating between different components throughout the app. You can define a data sharing service containing the BehaviorSubject to which you can subscribe and emit changes.

Define a data sharing service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataSharingService {
    public isUserLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
}

Add the DataSharingService in your AppModule providers entry.

Next, import the DataSharingService in your <app-header> and in the component where you perform the sign-in operation. In <app-header> subscribe to the changes to isUserLoggedIn subject:

import { DataSharingService } from './data-sharing.service';

export class AppHeaderComponent { 
    // Define a variable to use for showing/hiding the Login button
    isUserLoggedIn: boolean;

    constructor(private dataSharingService: DataSharingService) {

        // Subscribe here, this will automatically update 
        // "isUserLoggedIn" whenever a change to the subject is made.
        this.dataSharingService.isUserLoggedIn.subscribe( value => {
            this.isUserLoggedIn = value;
        });
    }
}

In your <app-header> html template, you need to add the *ngIf condition e.g.:

<button *ngIf="!isUserLoggedIn">Login</button> 
<button *ngIf="isUserLoggedIn">Sign Out</button>

Finally, you just need to emit the event once the user has logged in e.g:

someMethodThatPerformsUserLogin() {
    // Some code 
    // .....
    // After the user has logged in, emit the behavior subject changes.
    this.dataSharingService.isUserLoggedIn.next(true);
}

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Get installed applications in a system

it's worth noting that the Win32_Product WMI class represents products as they are installed by Windows Installer. not every application use windows installer

however "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" represents applications for 32 bit. For 64 bit you also need to traverse "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" and since not every software has a 64 bit version the total applications installed are a union of keys on both locations that have "UninstallString" Value with them.

but the best options remains the same .traverse registry keys is a better approach since every application have an entry in registry[including the ones in Windows Installer].however the registry method is insecure as if anyone removes the corresponding key then you will not know the Application entry.On the contrary Altering the HKEY_Classes_ROOT\Installers is more tricky as it is linked with licensing issues such as Microsoft office or other products. for more robust solution you can always combine registry alternative with the WMI.

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

How do I abort/cancel TPL Tasks?

Task are being executed on the ThreadPool (at least, if you are using the default factory), so aborting the thread cannot affect the tasks. For aborting tasks, see Task Cancellation on msdn.

How to change color of Android ListView separator line?

Or you can code it:

int[] colors = {0, 0xFFFF0000, 0}; // red for the example
myList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
myList.setDividerHeight(1);

Hope it helps

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

Just extract the ISO file to hard drive and it will work.

jQuery - passing value from one input to another

Add ID attributes with same values as name attributes and then you can do this:

$('#first_name').change(function () {
  $('#firstname').val($(this).val());
});

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

The following is quoted from Taming Lists:

There may be times when you have a list, but you don’t want any bullets, or you want to use some other character in place of the bullet. Again, CSS provides a straightforward solution. Simply add list-style: none; to your rule and force the LIs to display with hanging indents. The rule will look something like this:

ul {
   list-style: none;
   margin-left: 0;
   padding-left: 1em;
   text-indent: -1em;
}

Either the padding or the margin needs to be set to zero, with the other one set to 1em. Depending on the “bullet” that you choose, you may need to modify this value. The negative text-indent causes the first line to be moved to the left by that amount, creating a hanging indent.

The HTML will contain our standard UL, but with whatever character or HTML entity that you want to use in place of the bullet preceding the content of the list item. In our case we'll be using », the right double angle quote: ».

» Item 1
» Item 2
» Item 3
» Item 4
» Item 5 we'll make
   a bit longer so that
   it will wrap

How to set ChartJS Y axis title?

For x and y axes:

     options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'probability'
          }
        }],
        xAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'hola'
          }
        }],
      }
    }

Android: How to add R.raw to project?

If you have a res/raw folder, be sure to add a file with a valid filename, otherwise the entire folder won't show up in the R class. If there's an error with a filename, it will appear in red in the console.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Change

 mAdapter = new RecordingsListAdapter(this, recordings);

to

 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

GitLab git user password

I had this same problem when using a key of 4096 bits:

$ ssh-keygen -t rsa -C "GitLab" -b 4096
$ ssh -vT git@gitlabhost
...
debug1: Offering public key: /home/user/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/user/.ssh/id_dsa
debug1: Trying private key: /home/user/.ssh/id_ecdsa
debug1: Next authentication method: password
git@gitlabhost's password:
Connection closed by host

But with the 2048 bit key (the default size), ssh connects to gitlab without prompting for a password (after adding the new pub key to the user's gitlab ssh keys)

$ ssh-keygen -t rsa -C "GitLab"
$ ssh -vT git@gitlabhost
Welcome to GitLab, Joe User!

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

cmd line rename file with date and time

following should be your right solution

ren somefile.txt  somefile_%time:~0,2%%time:~3,2%-%DATE:/=%.txt

One DbContext per web request... why?

There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

  1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
  2. The other states that One DbContext per request is highly reccomended

Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

How to downgrade Node version

Steps to downgrade to node8

brew install node@8
brew link node@8 --force

if warning remove the folder and files as indicated in the warning then again the command :

brew link node@8 --force

Process with an ID #### is not running in visual studio professional 2013 update 3

I had the same problem. Just restarting Visual Studio worked for me.

how to print json data in console.log

If you just want to print object then

console.log(JSON.stringify(data)); //this will convert json to string;

If you want to access value of field in object then use

console.log(data.input_data);

Convert List<Object> to String[] in Java

There is a simple way available in Kotlin

var lst: List<Object> = ...
    
listOFStrings: ArrayList<String> = (lst!!.map { it.name })

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

keyCode values for numeric keypad?

You can use this to figure out keyCodes easily:

$(document).keyup(function(e) {
    // Displays the keycode of the last pressed key in the body
    $(document.body).html(e.keyCode);
});

http://jsfiddle.net/vecvc4fr/

Locking a file in Python

There is a cross-platform file locking module here: Portalocker

Although as Kevin says, writing to a file from multiple processes at once is something you want to avoid if at all possible.

If you can shoehorn your problem into a database, you could use SQLite. It supports concurrent access and handles its own locking.

SSL Connection / Connection Reset with IISExpress

Make sure to remove any previous 'localhost' certificates as those could conflict with the one generated by IIS Express. I had this same error (ERR_SSL_PROTOCOL_ERROR), and it took me many hours to finally figure it out after trying out many many "solutions". My mistake was that I had created my own 'localhost' certificate and there were two of them. I had to delete both and have IIS Express recreate it.

Here is how you can check for and remove 'localhost' certificate:

  • On Start, type ? mmc.exe
  • File ? Add/Remove Snap-in...
  • Select Certificates ? Add> ? Computer account ? Local computer
  • Check under Certificates > Personal > Certificates
  • Make sure the localhost certificate that exist has a friendly name "IIS Express Development Certificate". If not, delete it. Or if multiple, delete all.

On Visual Studio, select project and under property tab, enable SSL=true. Save, Build and Run. IIS Express will generate a new 'localhost' certificate.

Note: If it doesn't work, try these: make sure to disable IIS Express on VS project and stopping all running app on it prior to removing 'localhost' certificate. Also, you can go to 'control panel > programs' and Repair IIS Express.

How to get Top 5 records in SqLite?

Select TableName.* from  TableName DESC LIMIT 5

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

how to replace an entire column on Pandas.DataFrame

If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E'])

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

Hide vertical scrollbar in <select> element

I think you can't. The SELECT element is rendered at a point beyond the reach of CSS and HTML. Is it grayed out?

But you can try to add a "size" atribute.

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

git commit error: pathspec 'commit' did not match any file(s) known to git

Please try adding the double quotes git commit -m "initial commit". This will solve your problem.

How to prune local tracking branches that do not exist on remote anymore

I wanted something that would purge all local branches that were tracking a remote branch, on origin, where the remote branch has been deleted (gone). I did not want to delete local branches that were never set up to track a remote branch (i.e.: my local dev branches). Also, I wanted a simple one-liner that just uses git, or other simple CLI tools, rather than writing custom scripts. I ended up using a bit of grep and awk to make this simple command, then added it as an alias in my ~/.gitconfig.

[alias]
  prune-branches = !git remote prune origin && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D

Here is a git config --global ... command for easily adding this as git prune-branches:

git config --global alias.prune-branches '!git remote prune origin && git branch -vv | grep '"'"': gone]'"'"' | awk '"'"'{print $1}'"'"' | xargs -r git branch -d'

NOTE: Use of the -D flag to git branch can be very dangerous. So, in the config command above I use the -d option to git branch rather than -D; I use -D in my actual config. I use -D because I don't want to hear Git complain about unmerged branches, I just want them to go away. You may want this functionality as well. If so, simply use -D instead of -d at the end of that config command.

Most efficient way to concatenate strings in JavaScript?

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(Thanks @zAlbee for correction)

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

Eclipse CDT: Symbol 'cout' could not be resolved

For me it helped to enable the automated discovery in Properties -> C/C++-Build -> Discovery Options to resolve this problem.

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

What exactly is LLVM?

A good summary of LLVM is this:

enter image description here

At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.

At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.

How can I use a for each loop on an array?

A for each loop structure is more designed around the collection object. A For..Each loop requires a variant type or object. Since your "element" variable is being typed as a variant your "do_something" function will need to accept a variant type, or you can modify your loop to something like this:

Public Sub Example()

    Dim sArray(4) As String
    Dim i As Long

    For i = LBound(sArray) To UBound(sArray)
        do_something sArray(i)
    Next i

End Sub

Get domain name

I'm going to add an answer to try to clear up a few things here as there seems to be some confusion. The main issue is that people are asking the wrong question, or at least not being specific enough.

What does a computer's "domain" actually mean?

When we talk about a computer's "domain", there are several things that we might be referring to. What follows is not an exhaustive list, but it covers the most common cases:

  • A user or computer security principal may belong to an Active Directory domain.
  • The network stack's primary DNS search suffix may be referred to as the computer's "domain".
  • A DNS name that resolves to the computer's IP address may be referred to as the computer's "domain".

Which one do I want?

This is highly dependent on what you are trying to do. The original poster of this question was looking for the computer's "Active Directory domain", which probably means they are looking for the domain to which either the computer's security principal or a user's security principal belongs. Generally you want these when you are trying to talk to Active Directory in some way. Note that the current user principal and the current computer principal are not necessarily in the same domain.

Pieter van Ginkel's answer is actually giving you the local network stack's primary DNS suffix (the same thing that's shown in the top section of the output of ipconfig /all). In the 99% case, this is probably the same as the domain to which both the computer's security principal and the currently authenticated user's principal belong - but not necessarily. Generally this is what you want when you are trying to talk to devices on the LAN, regardless of whether or not the devices are anything to do with Active Directory. For many applications, this will still be a "good enough" answer for talking to Active Directory.

The last option, a DNS name, is a lot fuzzier and more ambiguous than the other two. Anywhere between zero and infinity DNS records may resolve to a given IP address - and it's not necessarily even clear which IP address you are interested in. user2031519's answer refers to the value of HTTP_HOST, which is specifically useful when determining how the user resolved your HTTP server in order to send the request you are currently processing. This is almost certainly not what you want if you are trying to do anything with Active Directory.

How do I get them?

Domain of the current user security principal

This one's nice and simple, it's what Tim's answer is giving you.

System.Environment.UserDomainName

Domain of the current computer security principal

This is probably what the OP wanted, for this one we're going to have to ask Active Directory about it.

System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()

This one will throw a ActiveDirectoryObjectNotFoundException if the local machine is not part of domain, or the domain controller cannot be contacted.

Network stack's primary DNS suffix

This is what Pieter van Ginkel's answer is giving you. It's probably not exactly what you want, but there's a good chance it's good enough for you - if it isn't, you probably already know why.

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName

DNS name that resolves to the computer's IP address

This one's tricky and there's no single answer to it. If this is what you are after, comment below and I will happily discuss your use-case and help you to work out the best solution (and expand on this answer in the process).

How do I check if a number is a palindrome?

For any given number:

n = num;
rev = 0;
while (num > 0)
{
    dig = num % 10;
    rev = rev * 10 + dig;
    num = num / 10;
}

If n == rev then num is a palindrome:

cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;

How to reset AUTO_INCREMENT in MySQL?

The highest rated answers to this question all recommend "ALTER yourtable AUTO_INCREMENT= value". However, this only works when value in the alter is greater than the current max value of the autoincrement column. According to the MySQL 8 documentation:

You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.

In essence, you can only alter AUTO_INCREMENT to increase the value of the autoincrement column, not reset it to 1, as the OP asks in the second part of the question. For options that actually allow you set the AUTO_INCREMENT downward from its current max, take a look at Reorder / reset auto increment primary key.

Bootstrap: Open Another Modal in Modal

Close the first Bootstrap modal and open the new modal dynamically.

$('#Modal_One').modal('hide');
setTimeout(function () {
  $('#Modal_New').modal({
    backdrop: 'dynamic',
    keyboard: true
  });
}, 500);

How to get all the AD groups for a particular user?

This is how I list all the groups (direct and indirect) for a specific Distinguished Name:

The string 1.2.840.113556.1.4.1941 specifies LDAP_MATCHING_RULE_IN_CHAIN.

This rule is limited to filters that apply to the DN. This is a special "extended" match operator that walks the chain of ancestry in objects all the way to the root until it finds a match.

This method is 25 times faster than the UserPrincipal.GetGroups() method in my testing.

Note: The primary group (typically Domain Users) is not returned by this or GetGroups() method. To get the primary group name too, I've confirmed this method works.

Additionally, I found this list of LDAP filters extremely useful.

private IEnumerable<string> GetGroupsForDistinguishedName(DirectoryEntry domainDirectoryEntry, string distinguishedName)
{
    var groups = new List<string>();
    if (!string.IsNullOrEmpty(distinguishedName))
    {
        var getGroupsFilterForDn = $"(&(objectCategory=group)(member:1.2.840.113556.1.4.1941:={distinguishedName}))";
        using (DirectorySearcher dirSearch = new DirectorySearcher(domainDirectoryEntry))
        {
            dirSearch.Filter = getGroupsFilterForDn;
            dirSearch.PropertiesToLoad.Add("name");

            using (var results = dirSearch.FindAll())
            {
                foreach (SearchResult result in results)
                {
                    if (result.Properties.Contains("name"))
                        groups.Add((string)result.Properties["name"][0]);
                }
            }
        }
    }

    return groups;
}

Add a common Legend for combined ggplots

Roland's answer needs updating. See: https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs

This method has been updated for ggplot2 v1.0.0.

library(ggplot2)
library(gridExtra)
library(grid)


grid_arrange_shared_legend <- function(...) {
    plots <- list(...)
    g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
    legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
    lheight <- sum(legend$height)
    grid.arrange(
        do.call(arrangeGrob, lapply(plots, function(x)
            x + theme(legend.position="none"))),
        legend,
        ncol = 1,
        heights = unit.c(unit(1, "npc") - lheight, lheight))
}

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
grid_arrange_shared_legend(p1, p2, p3, p4)

Note the lack of ggplot_gtable and ggplot_build. ggplotGrob is used instead. This example is a bit more convoluted than the above solution but it still solved it for me.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I had the exact same problem and since I read somewhere that the error was caused by a cached file, I fixed it by deleting all the files under the .m2 repository folder. The next time I built the project I had to download all the dependencies again but it was worth it - 0 errors!!

How to print color in console using System.out.println?

The best way to color console text is to use ANSI escape codes. In addition of text color, ANSI escape codes allows background color, decorations and more.

Unix

If you use springboot, there is a specific enum for text coloring: org.springframework.boot.ansi.AnsiColor

Jansi library is a bit more advanced (can use all the ANSI escape codes fonctions), provides an API and has a support for Windows using JNA.

Otherwise, you can manually define your own color, as shown is other responses.

Windows 10

Windows 10 (since build 10.0.10586 - nov. 2015) supports ANSI escape codes (MSDN documentation) but it's not enabled by default. To enable it:

  • With SetConsoleMode API, use ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x0400) flag. Jansi uses this option.
  • If SetConsoleMode API is not used, it is possible to change the global registry key HKEY_CURRENT_USER\Console\VirtualTerminalLevel by creating a dword and set it to 0 or 1 for ANSI processing: "VirtualTerminalLevel"=dword:00000001

Before Windows 10

Windows console does not support ANSI colors. But it's possible to use console which does.

How to use underscore.js as a template engine?

I wanted to share one more important finding.

use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.

We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance

jQuery: how to change title of document during .ready()?

<script type="text/javascript">
$(document).ready(function() {

    $(this).attr("title", "sometitle");

});
</script>

How to change status bar color in Flutter?

This is by far is the best way, it requires no extra plugins.

Widget emptyAppBar(){
  return PreferredSize(
      preferredSize: Size.fromHeight(0.0), 
      child: AppBar(
        backgroundColor: Color(0xFFf7f7f7),
        brightness: Brightness.light,
      )
  );
}

and call it in your scaffold like this

return Scaffold(
      appBar: emptyAppBar(),
     .
     .
     .

Get all directories within directory nodejs

graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

const names = directory.children  // <--
    .filter(node => node.is.directory)
    .map(directory => directory.name);

jquery - Check for file extension before uploading

If you don't want to use $(this).val(), you can try:

var file_onchange = function () {
  var input = this; // avoid using 'this' directly

  if (input.files && input.files[0]) {
    var type = input.files[0].type; // image/jpg, image/png, image/jpeg...

    // allow jpg, png, jpeg, bmp, gif, ico
    var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;

    if (type_reg.test(type)) {
      // file is ready to upload
    } else {
      alert('This file type is unsupported.');
    }
  }
};

$('#file').on('change', file_onchange);

Hope this helps!

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

Adding items to end of linked list

class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d ;
        next = n ;
       }

   public static Node addLast(Node header, Object x) {
       // save the reference to the header so we can return it.
       Node ret = header;

       // check base case, header is null.
       if (header == null) {
           return new Node(x, null);
       }

       // loop until we find the end of the list
       while ((header.next != null)) {
           header = header.next;
       }

       // set the new node to the Object x, next will be null.
       header.next = new Node(x, null);
       return ret;
   }
}

Hidden TextArea

but is the css style tag the correct way to get cross browser compatibility?

 <textarea style="display:none;" ></textarea>

or what I learned long ago....

     <textarea hidden ></textarea>

or
the global hidden element method:

    <textarea hidden="hidden" ></textarea>       

displayname attribute vs display attribute

Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)

//using statements
using System;
using System.ComponentModel.DataAnnotations;  //needed for Display annotation
using System.ComponentModel;  //needed for DisplayName annotation

public class Whatever
{
    //Property
    [Display(Name ="Release Date")]
    public DateTime ReleaseDate { get; set; }
}


//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)

How to create custom view programmatically in swift having controls text field, button etc

Swift 3 / Swift 4 Update:

let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)

Is it not possible to stringify an Error using JSON.stringify?

We needed to serialise an arbitrary object hierarchy, where the root or any of the nested properties in the hierarchy could be instances of Error.

Our solution was to use the replacer param of JSON.stringify(), e.g.:

_x000D_
_x000D_
function jsonFriendlyErrorReplacer(key, value) {_x000D_
  if (value instanceof Error) {_x000D_
    return {_x000D_
      // Pull all enumerable properties, supporting properties on custom Errors_x000D_
      ...value,_x000D_
      // Explicitly pull Error's non-enumerable properties_x000D_
      name: value.name,_x000D_
      message: value.message,_x000D_
      stack: value.stack,_x000D_
    }_x000D_
  }_x000D_
_x000D_
  return value_x000D_
}_x000D_
_x000D_
let obj = {_x000D_
    error: new Error('nested error message')_x000D_
}_x000D_
_x000D_
console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))_x000D_
console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer))
_x000D_
_x000D_
_x000D_

Is there a Subversion command to reset the working copy?

Very quick and simple and does exactly what you want

svn status | awk '{if($2 !~ /(config|\.ini)/ && !system("test -e \"" $2 "\"")) {print $2; system("rm -Rf \"" $2 "\"");}}'

The /(config|.ini)/ is for my own purposes.

And might be a good idea to add --no-ignore to the svn command

Reload .profile in bash shell script (in unix)?

Try:

#!/bin/bash
# .... some previous code ...
# help set exec | less
set -- 1 2 3 4 5  # fake command line arguments
exec bash --login -c '
echo $0
echo $@
echo my script continues here
' arg0 "$@"

Trim Cells using VBA in Excel

This works well for me. It uses an array so you aren't looping through each cell. Runs much faster over large worksheet sections.

Sub Trim_Cells_Array_Method()

Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long

  lRows = Selection.Rows.count
  lCols = Selection.Columns.count

  ReDim arrData(1 To lRows, 1 To lCols)
  ReDim arrReturnData(1 To lRows, 1 To lCols)

  Set rng = Selection
  arrData = rng.value

  For j = 1 To lCols
    For i = 1 To lRows
      arrReturnData(i, j) = Trim(arrData(i, j))
    Next i
  Next j

  rng.value = arrReturnData

  Set rng = Nothing
End Sub

Difference between a class and a module

namespace: modules are namespaces...which don't exist in java ;)

I also switched from Java and python to Ruby, I remember had exactly this same question...

So the simplest answer is that module is a namespace, which doesn't exist in Java. In java the closest mindset to namespace is a package.

So a module in ruby is like what in java:
class? No
interface? No
abstract class? No
package? Yes (maybe)

static methods inside classes in java: same as methods inside modules in ruby

In java the minimum unit is a class, you can't have a function outside of a class. However in ruby this is possible (like python).

So what goes into a module?
classes, methods, constants. Module protects them under that namespace.

No instance: modules can't be used to create instances

Mixed ins: sometimes inheritance models are not good for classes, but in terms of functionality want to group a set of classes/ methods/ constants together

Rules about modules in ruby:
- Module names are UpperCamelCase
- constants within modules are ALL CAPS (this rule is the same for all ruby constants, not specific to modules)
- access methods: use . operator
- access constants: use :: symbol

simple example of a module:

module MySampleModule
  CONST1 = "some constant"

  def self.method_one(arg1)
    arg1 + 2
  end
end

how to use methods inside a module:

puts MySampleModule.method_one(1) # prints: 3

how to use constants of a module:

puts MySampleModule::CONST1 # prints: some constant

Some other conventions about modules:
Use one module in a file (like ruby classes, one class per ruby file)

Credit card payment gateway in PHP?

Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php

Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

How do I compare two strings in Perl?

print "Matched!\n" if ($str1 eq $str2)

Perl has seperate string comparison and numeric comparison operators to help with the loose typing in the language. You should read perlop for all the different operators.

Make scrollbars only visible when a Div is hovered over?

.div::-webkit-scrollbar-thumb {
    background: transparent;
}

.div:hover::-webkit-scrollbar-thumb {
    background: red;
}

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

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

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

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

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

Linux command line howto accept pairing for bluetooth device without pin

Try setting security to none in /etc/bluetooth/hcid.conf

http://linux.die.net/man/5/hcid.conf

This will probably only work for HCI devices (mouse, keyboard, spaceball, etc.). If you have a different kind of device, there's probably a different but similar setting to change.

Error: Uncaught SyntaxError: Unexpected token <

This is a browser issue rather than a javascript or JQuery issue; it's attempting to interpret the angle bracket as an HTML tag.

Try doing this when setting up your javascripts:

<script>
//<![CDATA[

    // insert teh codez

//]]>
</script>

Alternatively, move your javascript to a separate file.

Edit: Ahh.. with that link I've tracked it down. What I said was the issue wasn't the issue at all. this is the issue, stripped from the website:

<script type="text/javascript"
    $(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });

Can you spot the error? It's in the first line: the <script tag isn't closed. It should be <script type="text/javascript">

My previous suggestion still stands, however: you should enclose intra-tagged scripts in a CDATA block, or move them to a separately linked file.

That wasn't the issue here, but it would have shown the real issue faster.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

If you have Android Studio then it is very very simple. Just create a MapActivity using Android Studio and after creating it go into google_maps_api.xml. In there there will be a link given in comments. If you paste it in your browser, it will ask a few details to be filled in and after that your API will be generated. There is no need of using keytool and all.

Screen shot:

Enter image description here

including parameters in OPENQUERY

Just try it this way, should work, easy! In your WHERE clause, after column name and equal to sign:- add TWO single quotes, your search value and then THREE single quotes. Close the bracket.

SELECT * FROM OPENQUERY([NameOfLinkedSERVER], 'SELECT * FROM TABLENAME where field1=''your search value''') T1 INNER JOIN MYSQLSERVER.DATABASE.DBO.TABLENAME T2 ON T1.PK = T2.PK

Dockerfile copy keep subdirectory structure

If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.

COPY . destinatio-directory/ 

Writing a Python list of lists to a csv file

If you don't want to import csv module for that, you can write a list of lists to a csv file using only Python built-ins

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

Oracle DB : java.sql.SQLException: Closed Connection

You have to validate the connection.

If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.

The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with

pool.setValidateConnectionOnBorrow(true);

But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with

if (connection == null || !((ValidConnection) connection).isValid())

See the Oracle documentation for further details.

How to get calendar Quarter from a date in TSQL

SELECT DATENAME(Quarter, CAST(CONVERT(VARCHAR(8), datecolumn) AS DATETIME))

Fastest way to convert JavaScript NodeList to Array?

The most fast and cross browser is

for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);

As I compared in

http://jsbin.com/oqeda/98/edit

*Thanks @CMS for the idea!

Chromium (Similar to Google Chrome) Firefox Opera

The backend version is not supported to design database diagrams or tables

I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.

Select Pandas rows based on list index

There are many ways of solving this problem, and the ones listed above are the most commonly used ways of achieving the solution. I want to add two more ways, just in case someone is looking for an alternative.

index_list = [1,3]

df.take(pos)

#or

df.query('index in @index_list')

CSS hexadecimal RGBA?

Charming Prince:

Only internet explorer allows the 4 byte hex color in the format of ARGB, where A is the Alpha channel. It can be used in gradient filters for example:

filter  : ~"progid:DXImageTransform.Microsoft.Gradient(GradientType=@{dir},startColorstr=@{color1},endColorstr=@{color2})";

Where dir can be: 1(horizontal) or 0(vertical) And the color strings can be hex colors(#FFAAD3) or argb hex colors(#88FFAAD3).

How to use document.getElementByName and getElementByTag?

  • document.getElementById('frmMain').elements
    assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById



A great alternative is


In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements

How to word wrap text in HTML?

Try this

div {display: inline;}

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

Based on Cameron's initial answer, here is what I've just added at my enhanced version of SilverFlow library's FloatingWindowHost (copying from FloatingWindowHost.cs at http://clipflair.codeplex.com source code)

    public int MaxZIndex
    {
      get {
        return FloatingWindows.Aggregate(-1, (maxZIndex, window) => {
          int w = Canvas.GetZIndex(window);
          return (w > maxZIndex) ? w : maxZIndex;
        });
      }
    }

    private void SetTopmost(UIElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        Canvas.SetZIndex(element, MaxZIndex + 1);
    }

Worth noting regarding the code above that Canvas.ZIndex is an attached property available for UIElements in various containers, not just used when being hosted in a Canvas (see Controlling rendering order (ZOrder) in Silverlight without using the Canvas control). Guess one could even make a SetTopmost and SetBottomMost static extension method for UIElement easily by adapting this code.

max(length(field)) in mysql

Use:

  SELECT mt.name 
    FROM MY_TABLE mt
GROUP BY mt.name
  HAVING MAX(LENGTH(mt.name)) = 18

...assuming you know the length beforehand. If you don't, use:

  SELECT mt.name 
    FROM MY_TABLE mt
    JOIN (SELECT MAX(LENGTH(x.name) AS max_length
            FROM MY_TABLE x) y ON y.max_length = LENGTH(mt.name)

Twitter Bootstrap and ASP.NET GridView

Add property of show header in gridview

 <asp:GridView ID="dgvUsers" runat="server" **showHeader="True"** CssClass="table table-hover table-striped" GridLines="None" 
AutoGenerateColumns="False">

and in columns add header template

<HeaderTemplate>
                   //header column names
</HeaderTemplate>

Understanding events and event handlers in C#

Great technical answers in the post! I have nothing technically to add to that.

One of the main reasons why new features appear in languages and software in general is marketing or company politics! :-) This must not be under estimated!

I think this applies to certain extend to delegates and events too! i find them useful and add value to the C# language, but on the other hand the Java language decided not to use them! they decided that whatever you are solving with delegates you can already solve with existing features of the language i.e. interfaces e.g.

Now around 2001 Microsoft released the .NET framework and the C# language as a competitor solution to Java, so it was good to have NEW FEATURES that Java doesn't have.

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

Install dependencies globally and locally using package.json

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

For example:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

So actually my npm install executes npm install again .. which is weird but seems to work.

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.

How to prevent a click on a '#' link from jumping to top of page?

Just use <input type="button" /> instead of <a> and use CSS to style it to look like a link if you wish.

Buttons are made specifically for clicking, and they don't need any href attributes.

The best way is to use onload action to create the button and append it where you need via javascript, so with javascript disabled, they will not show at all and do not confuse the user.

When you use href="#" you get tons of different links pointing to the same location, which won't work when the agent does not support JavaScript.

Bash script to calculate time elapsed

    #!/bin/bash

    time_elapsed(){
    appstop=$1; appstart=$2

    ss_strt=${appstart:12:2} ;ss_stop=${appstop:12:2}
    mm_strt=${appstart:10:2} ;mm_stop=${appstop:10:2}
     hh_strt=${appstart:8:2} ; hh_stop=${appstop:8:2}
     dd_strt=${appstart:6:2} ; dd_stop=${appstop:6:2}
     mh_strt=${appstart:4:2} ; mh_stop=${appstop:4:2}
     yy_strt=${appstart:0:4} ; yy_stop=${appstop:0:4}

    if [ "${ss_stop}" -lt "${ss_strt}" ]; then ss_stop=$((ss_stop+60)); mm_stop=$((mm_stop-1)); fi
    if [ "${mm_stop}" -lt "0" ]; then mm_stop=$((mm_stop+60)); hh_stop=$((hh_stop-1)); fi
    if [ "${mm_stop}" -lt "${mm_strt}" ]; then mm_stop=$((mm_stop+60)); hh_stop=$((hh_stop-1)); fi
    if [ "${hh_stop}" -lt "0" ]; then hh_stop=$((hh_stop+24)); dd_stop=$((dd_stop-1)); fi
    if [ "${hh_stop}" -lt "${hh_strt}" ]; then hh_stop=$((hh_stop+24)); dd_stop=$((dd_stop-1)); fi

    if [ "${dd_stop}" -lt "0" ]; then dd_stop=$((dd_stop+$(mh_days $mh_stop $yy_stop))); mh_stop=$((mh_stop-1)); fi
    if [ "${dd_stop}" -lt "${dd_strt}" ]; then dd_stop=$((dd_stop+$(mh_days $mh_stop $yy_stop))); mh_stop=$((mh_stop-1)); fi

    if [ "${mh_stop}" -lt "0" ]; then mh_stop=$((mh_stop+12)); yy_stop=$((yy_stop-1)); fi
    if [ "${mh_stop}" -lt "${mh_strt}" ]; then mh_stop=$((mh_stop+12)); yy_stop=$((yy_stop-1)); fi

    ss_espd=$((10#${ss_stop}-10#${ss_strt})); if [ "${#ss_espd}" -le "1" ]; then ss_espd=$(for((i=1;i<=$((${#ss_stop}-${#ss_espd}));i++)); do echo -n "0"; done; echo ${ss_espd}); fi
    mm_espd=$((10#${mm_stop}-10#${mm_strt})); if [ "${#mm_espd}" -le "1" ]; then mm_espd=$(for((i=1;i<=$((${#mm_stop}-${#mm_espd}));i++)); do echo -n "0"; done; echo ${mm_espd}); fi
    hh_espd=$((10#${hh_stop}-10#${hh_strt})); if [ "${#hh_espd}" -le "1" ]; then hh_espd=$(for((i=1;i<=$((${#hh_stop}-${#hh_espd}));i++)); do echo -n "0"; done; echo ${hh_espd}); fi
    dd_espd=$((10#${dd_stop}-10#${dd_strt})); if [ "${#dd_espd}" -le "1" ]; then dd_espd=$(for((i=1;i<=$((${#dd_stop}-${#dd_espd}));i++)); do echo -n "0"; done; echo ${dd_espd}); fi
    mh_espd=$((10#${mh_stop}-10#${mh_strt})); if [ "${#mh_espd}" -le "1" ]; then mh_espd=$(for((i=1;i<=$((${#mh_stop}-${#mh_espd}));i++)); do echo -n "0"; done; echo ${mh_espd}); fi
    yy_espd=$((10#${yy_stop}-10#${yy_strt})); if [ "${#yy_espd}" -le "1" ]; then yy_espd=$(for((i=1;i<=$((${#yy_stop}-${#yy_espd}));i++)); do echo -n "0"; done; echo ${yy_espd}); fi

    echo -e "${yy_espd}-${mh_espd}-${dd_espd} ${hh_espd}:${mm_espd}:${ss_espd}"
    #return $(echo -e "${yy_espd}-${mh_espd}-${dd_espd} ${hh_espd}:${mm_espd}:${ss_espd}")
    }

    mh_days(){
    mh_stop=$1; yy_stop=$2; #also checks if it's leap year or not

    case $mh_stop in
     [1,3,5,7,8,10,12]) mh_stop=31
     ;;
     2) (( !(yy_stop % 4) && (yy_stop % 100 || !(yy_stop % 400) ) )) && mh_stop=29 || mh_stop=28
     ;;
     [4,6,9,11]) mh_stop=30
     ;;
    esac

    return ${mh_stop}
    }

    appstart=$(date +%Y%m%d%H%M%S); read -p "Wait some time, then press nay-key..." key; appstop=$(date +%Y%m%d%H%M%S); elapsed=$(time_elapsed $appstop $appstart); echo -e "Start...: ${appstart:0:4}-${appstart:4:2}-${appstart:6:2} ${appstart:8:2}:${appstart:10:2}:${appstart:12:2}\nStop....: ${appstop:0:4}-${appstop:4:2}-${appstop:6:2} ${appstop:8:2}:${appstop:10:2}:${appstop:12:2}\n$(printf '%0.1s' "="{1..30})\nElapsed.: ${elapsed}"

    exit 0


-------------------------------------------- return
Wait some time, then press nay-key...
Start...: 2017-11-09 03:22:17
Stop....: 2017-11-09 03:22:18
==============================
Elapsed.: 0000-00-00 00:00:01

How can I get the domain name of my site within a Django template?

If you want the actual HTTP Host header, see Daniel Roseman's comment on @Phsiao's answer. The other alternative is if you're using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you're looking for:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

you'd have to put the current_site object into a template context yourself if you want to use it. If you're using it all over the place, you could package that up in a template context processor.

Android Studio with Google Play Services

Google Play services Integration in Android studio.

Step 1:

SDK manager->Tools Update this

1.Google play services
2.Android Support Repository

Step 2:

chance in build.gradle 
defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:4.0.+'
}

Step 3:

 android.manifest.xml
<uses-sdk
        android:minSdkVersion="8" />

Step 4:

Sync project file with grandle.
wait for few minute.

Step 5:

File->Project Structure find error with red bulb images,click on go to add dependencies select your app module.
Save

Please put comment if you have require help. Happy coding.

Cannot issue data manipulation statements with executeQuery()

For Delete query - Use @Modifying and @Transactional before the @Query like:-

@Repository
public interface CopyRepository extends JpaRepository<Copy, Integer> {

    @Modifying
    @Transactional
    @Query(value = "DELETE FROM tbl_copy where trade_id = ?1 ; ", nativeQuery = true)
    void deleteCopyByTradeId(Integer id);

}

It won't give the java.sql.SQLException: Can not issue data manipulation statements with executeQuery() error.

Edit:

Since this answer is getting many upvotes, I shall refer you to the documentation as well for more understanding.

@Transactional

By default, CRUD methods on repository instances are transactional. For read operations, 
the transaction configuration readOnly flag is set to true. 
All others are configured with a plain @Transactional so that default transaction 
configuration applies.

@Modifying

Indicates a query method should be considered as modifying query as that changes the way 
it needs to be executed. This annotation is only considered if used on query methods defined 
through a Query annotation). It's not applied on custom implementation methods or queries 
derived from the method name as they already have control over the underlying data access 
APIs or specify if they are modifying by their name.

Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL 
statements.

USB Debugging option greyed out

Try selecting the default mode as Internet connection.

Go to Settings -> Connectivity -> Default Mode -> Internet Connection.

Now enable the USB Debugging mode under Applications -> Development -> USB Debugging.

It worked for me.

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

How to display list of repositories from subversion server

Doesn't your access to SVN work just like a Web service? When I access the top directory of my SVN server, I get a page that's essentially a Table Of Contents of the whole works. It's an Unordered List that I can simply scan through.

EDIT: Here's how I would do it from the command line:

wget http://user:password@svn-url/ -O - | grep \<li\>

How to install both Python 2.x and Python 3.x in Windows

You can install multiple versions of Python one machine, and during setup, you can choose to have one of them associate itself with Python file extensions. If you install modules, there will be different setup packages for different versions, or you can choose which version you want to target. Since they generally install themselves into the site-packages directory of the interpreter version, there shouldn't be any conflicts (but I haven't tested this). To choose which version of python, you would have to manually specify the path to the interpreter if it is not the default one. As far as I know, they would share the same PATH and PYTHONPATH variables, which may be a problem.

Note: I run Windows XP. I have no idea if any of this changes for other versions, but I don't see any reason that it would.

How to hide only the Close (x) button?

Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}

then you create a menu strip item to exit the application.

cheers

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

If after following the steps as described by Surjeet you still can't connect, try turning your computer's Wi-Fi off and on again. This worked for me.

Also, be sure to trust the developer certificate on the iOS device (Settings - General - Profiles & Device Management - Developer App).

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar problem but with a different cause:

In my case the problem was that in the interface defining the repository

public interface ItemRepository extends Repository {..}

I was omitting the types of the template. Setting them right:

public interface ItemRepository extends Repository<Item,Long> {..}

did the trick.