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
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.
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.
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');
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"
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.
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]) + ')';
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).
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.
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
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.
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()));
}
}
}
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...
A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form
Easiest ways is
var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
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:
toggleVideo
?enablejsapi=1
to YouTube's URL, to enable the featureDemo: 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>
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:
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.
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.
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.
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...)
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
To get Channel id
Ex: Apple channel ID
Select any of the video in that channel
Select iPhone - Share photos (video)
Now click on channel name Apple bottom of the video.
Now you will get channel id in browser url
Here this is Apple channel id : UCE_M8A5yxnLfW0KghEeajjw
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).
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.
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
});
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
You could use createElement()
method for creating that textbox
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.
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;
}
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());
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');
}
});
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' %}
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.
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()
}
}
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.
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 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
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));
use .css
in Jquery like $('strong').css('background','red');
$('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_
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>
This link answer your question: http://wiki.netbeans.org/FaqI18nProjectEncoding
You can change the sources encoding or runtime encoding.
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:
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.
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.
There are many plugins for doing that. I normally use datatables it works great. http://datatables.net/
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
You can use round function
round("10.221",2);
Will return 10.22
Specify /D
to change the drive also.
CD /D %root%
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);
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/
^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.
^ 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.
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/
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();
}
}
}
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
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"
provide 400 permission, execute below command
chmod 400 /Users/username/.ssh/id_rsa
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);
}
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.
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.
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
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.
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});
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.
#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_
Here is some additional help for collection changed and UI issues:
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.
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
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
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.
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.
var fs = require('fs');
function base64Encode(file) {
var body = fs.readFileSync(file);
return body.toString('base64');
}
var base64String = base64Encode('test.jpg');
console.log(base64String);
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
1) php artisan -V
2) php artisan --version
AND its define at the composer.json file
"require": {
...........
"laravel/framework": "^6.2",
...........
},
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.
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
.
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
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
.
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
.
git rm --cached doc/*
.gitignore
, you can make one right inside of your project folder: project/.gitignore
. doc/*
in the .gitignore git add project/.gitignore
git commit -m "message"
. github
.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))
}
}
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
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:
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-digitsNote 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.
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.
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;
.
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);
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! ;)
I have build such kind of application using approximatively the same approach except :
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
*
* @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();
}
}
}
<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.
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/
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.");
}
}
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;
Write like this:
.wrapper:after {
content: '';
display: block;
clear: both;
}
Check this http://jsfiddle.net/EyNnk/1/
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
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 !
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
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.)
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
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.
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:
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
if you have a macos version, cmd+shift+D can make the job for you
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
Here is a crude way to do it: Transform JSON into bash
variables to eval
them.
This only works for:
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.
(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
END0
-Marker is applied, else you will see something like END1
.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.
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.
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 <
<script>
var url= "http://www.google.com";
window.location = url;
</script>
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();
}
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.
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")
<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.
Cygwin + sftp/scp natrually
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.
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.
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
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.
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!
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)
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);
}
from Google
An .axd file is a HTTP Handler file. There are two types of .axd files.
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
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);
}
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/
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")
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)
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"))
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.
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;
}
}
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.
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
Just extract the ISO file to hard drive and it will work.
Add ID attributes with same values as name attributes and then you can do this:
$('#first_name').change(function () {
$('#firstname').val($(this).val());
});
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
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
For x and y axes:
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'hola'
}
}],
}
}
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.
No but JavaFX has it.
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);
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!
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
following should be your right solution
ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%DATE:/=%.txt
There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.
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
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
I had the same problem. Just restarting Visual Studio worked for me.
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);
There is a simple way available in Kotlin
var lst: List<Object> = ...
listOFStrings: ArrayList<String> = (lst!!.map { it.name })
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.
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);
});
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.
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 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.
Select TableName.* from TableName DESC LIMIT 5
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;} );
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'])
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();
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.
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!!
Please try adding the double quotes git commit -m "initial commit". This will solve your problem.
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.
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)
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.
For me it helped to enable the automated discovery in Properties -> C/C++-Build -> Discovery Options to resolve this problem.
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.
A good summary of LLVM is this:
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.
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
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.
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:
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.
This one's nice and simple, it's what Tim's answer is giving you.
System.Environment.UserDomainName
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.
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
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).
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;
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.
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);
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;
}
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.
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!!
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:
ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x0400)
flag. Jansi uses this option.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.
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
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "sometitle");
});
</script>
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(),
.
.
.
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);
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!
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.
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;
}
}
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>
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)
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)
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.:
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_
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
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 "$@"
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
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)
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.
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. :)
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)
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).
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).
file()
is not supported in Python 3
Use open()
instead; see Built-in Functions - open().
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.
.div::-webkit-scrollbar-thumb {
background: transparent;
}
.div:hover::-webkit-scrollbar-thumb {
background: red;
}
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.
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.
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.
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:
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
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/
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))
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.
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.
SELECT DATENAME(Quarter, CAST(CONVERT(VARCHAR(8), datecolumn) AS DATETIME))
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!
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.
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')
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).
name
attribute in IE, please add ID to the element if you want to use getElementByIdA great alternative is
All
- it is a collection. The [0] will get the elements of the first form on the page. The "form" is a valid CSS selectorIn all of the above, the .elements
can be replaced by for example .querySelectorAll("[type=text]")
to get all text elements
I think you have not installed these features. see below in picture.
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:
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.
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)
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>
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.
Test with [char]9, such as:
$Tab = [char]9
Write-Output "$Tab hello"
Output:
hello
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.
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
.
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.
#!/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
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.
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.
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.
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.
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.
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.
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 genericAnswer
.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");
}
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\>
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.
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
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).
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.