To keep the promise chain going, you can't use setTimeout()
the way you did because you aren't returning a promise from the .then()
handler - you're returning it from the setTimeout()
callback which does you no good.
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t)
});
}
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
Here you're returning a promise from the .then()
handler and thus it is chained appropriately.
You can also add a delay method to the Promise object and then directly use a .delay(x)
method on your promises like this:
function delay(t, v) {_x000D_
return new Promise(function(resolve) { _x000D_
setTimeout(resolve.bind(null, v), t)_x000D_
});_x000D_
}_x000D_
_x000D_
Promise.prototype.delay = function(t) {_x000D_
return this.then(function(v) {_x000D_
return delay(t, v);_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_
console.log(v);_x000D_
});
_x000D_
Or, use the Bluebird promise library which already has the .delay()
method built-in.
Found an easy solution for Spring-Boot, Spring-Security and Java-based config:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
return new CorsConfiguration().applyPermitDefaultValues();
}
});
}
}
Use querySelector insted of getElementById();
var c = document.querySelector('#mainContent');
c.appendChild(document.createElement('div'));
Modify the_script.php like this.
<script>
the_function() {
alert("You win");
}
</script>
*Updated
jQuery
version would be something like below:
function load(recieving_id){
$('#roommate_but').prop('disabled', true);
$.get('include.inc.php?i=' + recieving_id, function(data) {
$("#roommate_but").html(data);
});
}
My mistake was that I was keeping the Javascript file ( tag) above the html declaration.
It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js
and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open()
and before your send()
I tried about three different ways of intercepting the construction of the Ajax object:
xhrFields
, but that only allows for one listener, only attaches to download (not upload) progress, and requires what seems like unnecessary copy-and-paste. progress
function to the returned promise, but I had to maintain my own array of handlers. I could not find a good object to attach the handlers because one place I'd access to the XHR and another I'd have access to the jQuery XHR, but I never had access to the deferred object (only its promise). ajax
with my own. The only potential shortcoming is you can no longer use your own xhr()
setting. You can allow for that by checking to see whether options.xhr
is a function.I actually call my promise.progress
function xhrProgress
so I can easily find it later. You might want to name it something else to separate your upload and download listeners. I hope this helps someone even if the original poster already got what he needed.
(function extend_jQuery_ajax_with_progress( window, jQuery, undefined )
{
var $originalAjax = jQuery.ajax;
jQuery.ajax = function( url, options )
{
if( typeof( url ) === 'object' )
{options = url;url = undefined;}
options = options || {};
// Instantiate our own.
var xmlHttpReq = $.ajaxSettings.xhr();
// Make it use our own.
options.xhr = function()
{return( xmlHttpReq );};
var $newDeferred = $.Deferred();
var $oldPromise = $originalAjax( url, options )
.done( function done_wrapper( response, text_status, jqXHR )
{return( $newDeferred.resolveWith( this, arguments ));})
.fail( function fail_wrapper( jqXHR, text_status, error )
{return( $newDeferred.rejectWith( this, arguments ));})
.progress( function progress_wrapper()
{
window.console.warn( "Whoa, jQuery started actually using deferred progress to report Ajax progress!" );
return( $newDeferred.notifyWith( this, arguments ));
});
var $newPromise = $newDeferred.promise();
// Extend our own.
$newPromise.progress = function( handler )
{
xmlHttpReq.addEventListener( 'progress', function download_progress( evt )
{
//window.console.debug( "download_progress", evt );
handler.apply( this, [evt]);
}, false );
xmlHttpReq.upload.addEventListener( 'progress', function upload_progress( evt )
{
//window.console.debug( "upload_progress", evt );
handler.apply( this, [evt]);
}, false );
return( this );
};
return( $newPromise );
};
})( window, jQuery );
It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.
Use fileOrBlob.text()
as follows:
<input type="file" onchange="this.files[0].text().then(t => console.log(t))">
When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.
Here's a more verbose version:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await file.text();
console.log(text);
}
</script>
Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
On older browsers, this should work:
<input type="file" onchange="loadFile(this.files[0])">
<script>
async function loadFile(file) {
let text = await (new Response(file)).text();
console.log(text);
}
</script>
Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.
Why don't you style it out:
<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
Your browser does not support the canvas element.
</canvas>
$(document).ready(function() {
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
});
<form id="form1" name="form1">
Field 1: <input id="field1" type="text" class="required">
<input id="btn" type="submit" value="Validate">
</form>
You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.
Here is an example of how to achieve what you need:
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// begin custom shape
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
// complete custom shape
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = 'blue';
context.stroke();
</script>
_x000D_
Convert canvas image to URL format (base64)
var dataURL = canvas.toDataURL();
Send it to your server via Ajax
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file, you just saved
// and than put the image in your browser.
});
_x000D_
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
Try creating a javascript function which runs this:
document.getElementById("youriframeid").contentWindow.location.reload(true);
Or maybe use an HTML workaround:
<html>
<body>
<center>
<a href="pagename.htm" target="middle">Refresh iframe</a>
<p>
<iframe src="pagename.htm" name="middle">
</p>
</center>
</body>
</html>
Both might be what you're looking for...
My approach: use a div
instead of a pop-up window.
See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/
Or save the code below as test.html and try it locally.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$('.btnChoice').on('click', function(){
$('#divChoices').show()
thefield = $(this).prev()
$('.btnselect').on('click', function(){
theselected = $(this).prev()
thefield.val( theselected.val() )
$('#divChoices').hide()
})
})
$('#divChoices').css({
'border':'2px solid red',
'position':'fixed',
'top':'100',
'left':'200',
'display':'none'
})
});
</script>
</head>
<body>
<div class="divform">
<input type="checkbox" name="kvi1" id="kvi1" value="1">
<label>Field 1: </label>
<input size="10" type="number" id="sku1" name="sku1">
<button id="choice1" class="btnChoice">?</button>
<br>
<input type="checkbox" name="kvi2" id="kvi2" value="2">
<label>Field 2: </label>
<input size="10" type="number" id="sku2" name="sku2">
<button id="choice2" class="btnChoice">?</button>
</div>
<div id="divChoices">
Select something:
<br>
<input size="10" type="number" id="ch1" name="ch1" value="11">
<button id="btnsel1" class="btnselect">Select</button>
<label for="ch1">bla bla bla</label>
<br>
<input size="10" type="number" id="ch2" name="ch2" value="22">
<button id="btnsel2" class="btnselect">Select</button>
<label for="ch2">ble ble ble</label>
</div>
</body>
</html>
clean and simple.
On Debian i found out to run on port 80 you need to issue the command as root i.e
sudo node app.js
I hope it helps
loadXMLDoc JS function should return false, otherwise it will result in postback.
I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.
export default class ScriptLoader {
constructor (options) {
const { src, global, protocol = document.location.protocol } = options
this.src = src
this.global = global
this.protocol = protocol
this.isLoaded = false
}
loadScript () {
return new Promise((resolve, reject) => {
// Create script element and set attributes
const script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = `${this.protocol}//${this.src}`
// Append the script to the DOM
const el = document.getElementsByTagName('script')[0]
el.parentNode.insertBefore(script, el)
// Resolve the promise once the script is loaded
script.addEventListener('load', () => {
this.isLoaded = true
resolve(script)
})
// Catch any errors while loading the script
script.addEventListener('error', () => {
reject(new Error(`${this.src} failed to load.`))
})
})
}
load () {
return new Promise(async (resolve, reject) => {
if (!this.isLoaded) {
try {
await this.loadScript()
resolve(window[this.global])
} catch (e) {
reject(e)
}
} else {
resolve(window[this.global])
}
})
}
}
Usage is like this:
const loader = new Loader({
src: 'cdn.segment.com/analytics.js',
global: 'Segment',
})
// scriptToLoad will now be a reference to `window.Segment`
const scriptToLoad = await loader.load()
My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.
$(function() {
callPlayer($('#iframe')[0], 'unMute');
});
function callPlayer(iframe, func, args) {
if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
} ), '*');
}
}
No need to write your own...
The jQuery-CSV library has a function called $.csv.toObjects(csv)
that does the mapping automatically.
Note: The library is designed to handle any CSV data that is RFC 4180 compliant, including all of the nasty edge cases that most 'simple' solutions overlook.
Like @Blazemonger already stated, first you need to add line breaks to make the data valid CSV.
Using the following dataset:
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
Use the code:
var data = $.csv.toObjects(csv):
The output saved in 'data' will be:
[
{ heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1" }
{ heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
Note: Technically, the way you wrote the key-value mapping is invalid JavaScript. The objects containing the key-value pairs should be wrapped in brackets.
If you want to try it out for yourself, I suggest you take a look at the Basic Usage Demonstration under the 'toObjects()' tab.
Disclaimer: I'm the original author of jQuery-CSV.
Update:
Edited to use the dataset that the op provided and included a link to the demo where the data can be tested for validity.
Update2:
Due to the shuttering of Google Code. jquery-csv has moved to GitHub
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
I do it like this and it's work for me, I hope this will help :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>
I have accomplished this with a hidden iframe. I use perl, not php, so will just give concept, not code solution.
Client sends Ajax request to server, causing the file content to be generated. This is saved as a temp file on the server, and the filename is returned to the client.
Client (javascript) receives filename, and sets the iframe src to some url that will deliver the file, like:
$('iframe_dl').src="/app?download=1&filename=" + the_filename
Server slurps the file, unlinks it, and sends the stream to the client, with these headers:
Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'
Works like a charm.
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
function loadpage (page_request, containerid)
{
var loading = document.getElementById ( "loading" ) ;
// when connecting to server
if ( page_request.readyState == 1 )
loading.style.visibility = "visible" ;
// when loaded successfully
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById(containerid).innerHTML=page_request.responseText ;
loading.style.visibility = "hidden" ;
}
}
Modify your Jquery in following way:
$.ajax({
url: someurl,
contentType: 'application/json',
data: JSONObject,
headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
dataType: 'json',
type: 'POST',
success: function (Data) {....}
});
If the server responds to an OPTIONS method and to GET and POST (whichever of them you're using) with a header like:
Access-Control-Allow-Origin: *
It might work OK. Seems to in FireFox 3.5 and rekonq 0.4.0. Apparently, with that header and the initial response to OPTIONS, the server is saying to the browser, "Go ahead and let this cross-domain request go through."
I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:
Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
and then I put it like this:
Route::get('Mensajes/modificar', 'MensajeriaController@modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');
Is http://api.xxx.com/
part of your domain? If not, you are being blocked by the same origin policy.
You may want to check out the following Stack Overflow post for a few possible workarounds:
For people looking this up now:
It seems that now setting the User-Agent
header is allowed since Firefox 43. See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name for the current list of forbidden headers.
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
If your string is a file path, as in your example, you can also use Unix style file paths:
string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";
But the other answers have the more general solutions to string escaping in C#.
You can do this:
var getValue = function (input, defaultValue) {
return input.value || defaultValue;
};
For anyone having issues with Visual Studio 2019:
I had to first open menu Test ? Windows ? Test Explorer, and run the tests from there, before the option to Run / Debug tests would show up on the right click menu.
This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.
The fields of this exception are :
protected static final java.lang.String BASE_SUPPORT_URL
public static final java.lang.String DRIVER_INFO
public static final java.lang.String SESSION_ID
About your individual usecase, the error tells it all :
WebDriverException: Element is not clickable at point (x, y). Other element would receive the click
It is clear from your code block that you have defined the wait
as WebDriverWait wait = new WebDriverWait(driver, 10);
but you are calling the click()
method on the element before the ExplicitWait
comes into play as in until(ExpectedConditions.elementToBeClickable)
.
The error Element is not clickable at point (x, y)
can arise from different factors. You can address them by either of the following procedures:
1. Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions
Class:
WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
2. Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor
to bring the element within the Viewport:
WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
3. The page is getting refreshed before the element gets clickable.
In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.
4. Element is present in the DOM but not clickable.
In this case induce ExplicitWait with ExpectedConditions
set to elementToBeClickable
for the element to be clickable:
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));
5. Element is present but having temporary Overlay.
In this case, induce ExplicitWait
with ExpectedConditions
set to invisibilityOfElementLocated
for the Overlay to be invisible.
WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
6. Element is present but having permanent Overlay.
Use JavascriptExecutor
to send the click directly on the element.
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
I have had the same problem and came acrosse this site.
the solution to just set another "filename" in the
... for output as ... command was very simple and useful.
in addition (beyond the Application.GetSaveAsFilename() Dialog)
it is very simple to set a** new filename** just using
the replace command, so you may change the filename/extension
eg. (as from the first post)
sFileName = "C:\filelocation"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
content = (...edit the content)
Close iFileNum
now just set:
newFilename = replace(sFilename, ".txt", ".csv") to change the extension
or
newFilename = replace(sFilename, ".", "_edit.") for a differrent filename
and then just as before
iFileNum = FreeFile
Open newFileName For Output As iFileNum
Print #iFileNum, content
Close iFileNum
I surfed over an hour to find out how to rename a txt-file,
with many different solutions, but it could be sooo easy :)
From SQL Server point of view:
Clustering will give you an active - passive configuration. Meaning in a 2 node cluster, one of them will be the active (serving) and the other one will be passive (waiting to take over when the active node fails). It's a high availability from hardware point of view.
You can have an active-active cluster, but it will require multiple instances of SQL Server running on each node. (i.e. Instance 1 on Node A failing over to Instance 2 on Node B, and instance 1 on Node B failing over to instance 2 on Node A).
Load balancing (at least from SQL Server point of view) does not exists (at least in the same sense of web server load balancing). You can't balance load that way. However, you can split your application to run on some database on server 1 and also run on some database on server 2, etc. This is the primary mean of "load balancing" in SQL world.
I have one other way to do this same thing works perfectly. so the idea behind to show all markers on the screen we need a center lat long and zoom level. here is the function which will give you both and need all marker's Latlng objects as input.
public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) {
float max = 0;
if (l == null || l.length == 0) {
return null;
}
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
b.include(l[count]);
}
LatLng center = b.build().getCenter();
float distance = 0;
for (int count = 0; count < l.length; count++) {
if (l[count] == null) {
continue;
}
distance = distance(center, l[count]);
if (distance > max) {
max = distance;
}
}
double scale = max / 1000;
int zoom = ((int) (16 - Math.log(scale) / Math.log(2)));
return new Pair<LatLng, Integer>(center, zoom);
}
This function return Pair object which you can use like
Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));
you can instead of using padding to keep away your markers from screen boundaries, you can adjust zoom by -1.
justify-content
only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content
will do nothing.
Some examples where it would have an effect:
if your flex items are all inflexible (flex: none
or flex: 0 0 auto
), and smaller than the container.
if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width
on each of the flexible items.
In both of those cases, justify-content
would be in charge of distributing the excess space.
In your example, though, you have flex items that have flex: 1
or flex: 6
with no max-width
limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content
to do anything with.
public static class GlobalVariables
{
// readonly variable
public static string Foo
{
get
{
return "foo";
}
}
// read-write variable
public static string Bar
{
get
{
return HttpContext.Current.Application["Bar"] as string;
}
set
{
HttpContext.Current.Application["Bar"] = value;
}
}
}
You probably shouldn't tell a six-year old about closures, but if you do, you might say that closure gives an ability to gain access to a variable declared in some other function scope.
function getA() {
var a = [];
// this action happens later,
// after the function returned
// the `a` value
setTimeout(function() {
a.splice(0, 0, 1, 2, 3, 4, 5);
});
return a;
}
var a = getA();
out('What is `a` length?');
out('`a` length is ' + a.length);
setTimeout(function() {
out('No wait...');
out('`a` length is ' + a.length);
out('OK :|')
});
_x000D_
<pre id="output"></pre>
<script>
function out(k) {
document.getElementById('output').innerHTML += '> ' + k + '\n';
}
</script>
_x000D_
Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:
@import 'base/_reset';
@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';
@import 'base/_typography';
@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';
@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';
@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';
@import 'vendors/_ui-grid';
@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';
And you can watch them with gulp/grunt/webpack etc, like:
gulpfile.js
// SASS Task
var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('styles', function(){
return gulp
.src('sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./build/css/'));
});
gulp.task('watch', function () {
gulp.watch('sass/**/*.scss', ['styles']);
});
gulp.task('default', ['watch']);
I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta
table. You can find the corresponding products within wp_posts
table.
After some serious searching it seems i've found the answer to my question:
from: http://www.brunildo.org/test/Overflowxy2.html
In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.
also the W3C spec says:
The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.
Short Version:
If you are using visible
for either overflow-x
or overflow-y
and something other than visible
for the other, the visible
value is interpreted as auto
.
They are useful if you are (for some reason) using column names with certain characters for example.
Select First Name From People
would not work, but putting square brackets around the column name would work
Select [First Name] From People
In short, it's a way of explicitly declaring a object name; column, table, database, user or server.
So, something like this
phpunit --filter 'EscalationGroupTest::testSaveAndDrop' EscalationGroupTest escalation/EscalationGroupTest.php
Without =
and with '
I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.
I created an angularjs directive using @Russ's and @Alex's answers
Could be interesting in 2014 and beyond :P
html
<div ng-app="croppy">
<cropped-image src="http://placehold.it/200x200" width="100" height="100"></cropped-image>
</div>
js
angular.module('croppy', [])
.directive('croppedImage', function () {
return {
restrict: "E",
replace: true,
template: "<div class='center-cropped'></div>",
link: function(scope, element, attrs) {
var width = attrs.width;
var height = attrs.height;
element.css('width', width + "px");
element.css('height', height + "px");
element.css('backgroundPosition', 'center center');
element.css('backgroundRepeat', 'no-repeat');
element.css('backgroundImage', "url('" + attrs.src + "')");
}
}
});
Here, give this a shot (this is just a pseudocode)
using System;
using System.Data;
using System.Data.SqlClient;
public class PullDataTest
{
// your data table
private DataTable dataTable = new DataTable();
public PullDataTest()
{
}
// your method to pull data from database to datatable
public void PullData()
{
string connString = @"your connection string here";
string query = "select * from table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
}
}
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
There is a good library that can be used in case permissions need to be asked when permission is needed by a background service. Although a limitation of library is that it can not be used to just determine whether permissions are currently given to the app or not. It always asks the user if app doesn't already have them.
Do give it a try as it makes life simpler: Android Permissions
Another option is Array.isArray()
if(! Array.isArray(classNames) ){
classNames = [classNames]
}
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
Think differently, You can use the following library to convert pdf to image using javascript
For code indentation first select the lines of code then press:
command + alt + [
command + alt + ]
Java code for modifying the datatype of the DataFrame from String to Integer
df.withColumn("col_name", df.col("col_name").cast(DataTypes.IntegerType))
It will simply cast the existing(String datatype) to Integer.
What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.
var getString = (function() {
var DIV = document.createElement("div");
if ('outerHTML' in DIV)
return function(node) {
return node.outerHTML;
};
return function(node) {
var div = DIV.cloneNode();
div.appendChild(node.cloneNode(true));
return div.innerHTML;
};
})();
// getString(el) == "<p>Test</p>"
You'll find my jQuery plugin here: Get selected element's outer HTML
In bash version 4 associative arrays were introduced.
declare -A arr
arr["key1"]=val1
arr+=( ["key2"]=val2 ["key3"]=val3 )
The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.
for key in ${!arr[@]}; do
echo ${key} ${arr[${key}]}
done
Will loop over all key values and echo them out.
Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
The given code given will work absolutely fine if we run from console. and there is no package name in the class
You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.
Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.
A text box on a sheet you can though.
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue
And same thing for an excel cell
Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True
If this isn't what you're after you will need to provide more information in your question.
EDIT: posted this after the comment sorry
On the site in IIS:
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output --> Rogue One
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
The easiest way would be to use a library like this one and specifically you want noStrings
to be true
export class CustomValidator{ // Number only validation
static numeric(control: AbstractControl) {
let val = control.value;
const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});
if (hasError) return null;
return val;
}
}
I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
Let's consider your DOM as
<a>
<!-- some other icons and texts -->
<span>Close</span>
</a>
Now that you need to select parent tag 'a' based on <span>
text, then use
driver.findElement(By.xpath("//a[.//span[text()='Close']]"));
Explanation: Select the node based on its child node's value
Here It is actually returning tuple
.
If you execute this code in Python 3:
def get():
a = 3
b = 5
return a,b
number = get()
print(type(number))
print(number)
Output :
<class 'tuple'>
(3, 5)
But if you change the code line return [a,b]
instead of return a,b
and execute :
def get():
a = 3
b = 5
return [a,b]
number = get()
print(type(number))
print(number)
Output :
<class 'list'>
[3, 5]
It is only returning single object which contains multiple values.
There is another alternative to return
statement for returning multiple values, use yield
( to check in details see this What does the "yield" keyword do in Python?)
Sample Example :
def get():
for i in range(5):
yield i
number = get()
print(type(number))
print(number)
for i in number:
print(i)
Output :
<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4
I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)
This helped for me:
All you need to do, is to specify a envirnoment variable called JAVA_TOOL_OPTIONS. If you set this variable to -Dfile.encoding=UTF8, everytime a JVM is started, it will pick up this information.
That's no struts related problem but rather plain HMTL/CSS.
I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.
workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
}
});
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!
For PowerShell 3.0 and later, there is one built in :)
foreach ($item in $array) {
$array.IndexOf($item)
}
This is called Double checked locking mechanism, first, we will check whether the instance is created or not. If not then only we will synchronize the method and create the instance. It will drastically improve the performance of the application. Performing lock is heavy. So to avoid the lock first we need to check the null value. This is also thread safe and it is the best way to achieve the best performance. Please have a look at the following code.
public sealed class Singleton
{
private static readonly object Instancelock = new object();
private Singleton()
{
}
private static Singleton instance = null;
public static Singleton GetInstance
{
get
{
if (instance == null)
{
lock (Instancelock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
I have fixed the same issue with below steps
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === 'the-provided-hash-code') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php php -r "unlink('composer-setup.php');"
Everything is working fine now because the composer.phar
file is available within the current project directory.
Copied from https://stackoverflow.com/questions/21670709/running-composer-returns-could-not-open-input-file-composer-phar/51907013#51907013
thanks
You're missing a close parenthesis, I.E. you aren't closing Range()
.
Try this Range(cells(1, 1), cells(lastRow, lastColumn)).Select
But you should really look at the other answer from Dick Kusleika for possible alternatives that may serve you better. Specifically, ActiveSheet.UsedRange.Select
which has the same end result as your code.
This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ...
as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.
$lastCell = 11
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7
$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row
$phoneData = for ($i=1; $i -le $endRow; $i++)
{
$pModel = $sh.Cells.Item($startRow,$model).Value2
$pMAC = $sh.Cells.Item($startRow,$mac).Value2
$nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
$extension = $sh.Cells.Item($startRow,$ext).Value2
New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
$startRow++
}
I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.
One sub and two functions. The sub builds your path and use the functions to check if the path exists and create if not. If the full path exists already, it will just pass on by. This will work on PC, but you will have to check what needs to be modified to work on Mac as well.
'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()
Dim strComp As String, strPart As String, strPath As String
strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:\Images\"
If Not FolderExists(strPath & strComp) Then
'company doesn't exist, so create full path
FolderCreate strPath & strComp & "\" & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strComp & "\" & strPart) Then
FolderCreate strPath & strComp & "\" & strPart
End If
End If
End Sub
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExists = True
End Function
Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
CleanName = Replace(strName, "/","")
CleanName = Replace(CleanName, "*","")
etc...
End Function
Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}
In other case to get rid of that defining parent percentage you can use
body{height:100vh}
vh stands for viewport height
I think it help
This is the configuration file for Maven. It can be specified at two levels:
User Level. This settings.xml file provides configuration for a single user, and is normally provided in ${user.home}/.m2/settings.xml.
NOTE: This location can be overridden with the CLI option:
-s /path/to/user/settings.xml
Global Level. This settings.xml file provides configuration for all Maven users on a machine (assuming they're all using the same Maven installation). It's normally provided in ${maven.home}/conf/settings.xml.
NOTE: This location can be overridden with the CLI option:
-gs /path/to/global/settings.xml
One of the main motivations for using an abstract class is to enable polymorphism within your application -- i.e: you can substitute a different version at runtime. In fact, this is very much the same thing as using an interface except the abstract class provides some common plumbing, often referred to as a Template pattern.
From a unit testing perspective, there are two things to consider:
Interaction of your abstract class with it related classes. Using a mock testing framework is ideal for this scenario as it shows that your abstract class plays well with others.
Functionality of derived classes. If you have custom logic that you've written for your derived classes, you should test those classes in isolation.
edit: RhinoMocks is an awesome mock testing framework that can generate mock objects at runtime by dynamically deriving from your class. This approach can save you countless hours of hand-coding derived classes.
I had reinstalled nvidia driver: run these commands in root
mode:
systemctl isolate multi-user.target
modprobe -r nvidia-drm
Reinstall Nvidia driver: chmod +x NVIDIA-Linux-x86_64–410.57.run
systemctl start graphical.target
and finally check nvidia-smi
Thanks to: How To Install Nvidia Drivers and CUDA-10.0 for RTX 2080 Ti GPU on Ubuntu-16.04/18.04
Which process uses port in unix;
root> netstat -Aan | grep 3872
output> f1000e000bb5c3b8 tcp 0 0 *.3872 . LISTEN
output> The socket 0xf1000e000bb5c008 is being held by proccess 13959354 (java).
use the following code:
$homepage = file_get_contents("https://www.google.com",false,
stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
]
])
);
echo $homepage;
This would be a good candidate for MetaWhere if you're using Rails 3.0+, but it doesn't work on Rails 3.1. You might want to try out squeel instead. It's made by the same author. Here's how'd you'd perform an OR based chain:
Person.where{(name == "John") | (lastname == "Smith")}
You can mix and match AND/OR, among many other awesome things.
To answer TJJ: But is it also possible to do this without copying the whole file? So, just to somehow create an additional vmdk-metafile, that references the raw dd-image.
Yes, it's possible. Here's how to use a flat disk image in VirtualBox:
First you create an image with dd in the usual way:
dd bs=512 count=60000 if=/dev/zero of=usbdrv.img
Then you can create a file for VirtualBox that references this image:
VBoxManage internalcommands createrawvmdk -filename "usbdrv.vmdk" -rawdisk "usbdrv.img"
You can use this image in VirtualBox as is, but depending on the guest OS it might not be visible immediately. For example, I experimented on using this method with a Windows guest OS and I had to do the following to give it a drive letter:
You might want to access your files on Linux. First dismount it from the guest OS to be sure and remove it from the virtual machine. Now we need to create a virtual device that references the partition.
sfdisk -d usbdrv.img
Response:
label: dos
label-id: 0xd367a714
device: usbdrv.img
unit: sectors
usbdrv.img1 : start= 63, size= 48132, type=4
Take note of the start position of the partition: 63. In the command below I used loop4 because it was the first available loop device in my case.
sudo losetup -o $((63*512)) loop4 usbdrv.img
mkdir usbdrv
sudo mount /dev/loop4 usbdrv
ls usbdrv -l
Response:
total 0
-rwxr-xr-x. 1 root root 0 Apr 5 17:13 'Test file.txt'
Yay!
In case you want to use it globally on all custom inputs use following jQuery code:
$(document).ready(function () {
$('.custom-file-input').on('change', function (e) {
e.target.nextElementSibling.innerHTML = e.target.files[0].name;
});
});
I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.
// With jQuery
$('#selectbox').focus(function(e) {
$(this).blur();
});
Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.
If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:
ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';
Will accept this line as 4 fields
1,some text\, with comma in it,123,more text
var tabsHeight = 650;
$("tabs").attr('style', 'height: '+ tabsHeight +'px !important');
OR
#CSS
.myclass{height:650px !important;}
then
$("tabs").addClass("myclass");
Use the IP instead:
DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';
For more possibilities, see this link.
To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):
mysqladmin -u root password 'mynewpassword'
You can use cut
:
cut -c N- file.txt > new_file.txt
-c:
characters
file.txt:
input file
new_file.txt:
output file
N-:
Characters from N to end to be cut and output to the new file.
Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.
This will perform the operation to each line of the input file.
Did you include "bootstrap-theme.css" files on your code?
In "bootstrap-theme.min.css" files, background-image about ".active" is existed for "navbar" (check this screenshot: http://i.imgur.com/1etLIyY.png).
It will re-declare your style code, and then it will be effected on your code.
So after you delete or re-declare them (background-image), you can use your background color style about the ".active" tag.
Disclaimer: this is an update to Cascabel's answer, which I'm writing to save the curious some time.
I tried in vain to replicate (in Git 2.0.1) the remote HEAD is ambiguous
message that Cascabel mentions in his answer; so I did a bit of digging (by cloning https://github.com/git/git and searching the log). It used to be that
Determining HEAD is ambiguous since it is done by comparing SHA1s. In the case of multiple matches we return refs/heads/master if it matches, else we return the first match we encounter. builtin-remote needs all matches returned to it, so add a flag for it to request such.
(Commit 4229f1fa325870d6b24fe2a4c7d2ed5f14c6f771
, dated Feb 27, 2009, found with git log --reverse --grep="HEAD is ambiguous"
)
However, the ambiguity in question has since been lifted:
One long-standing flaw in the pack transfer protocol used by "git clone" was that there was no way to tell the other end which branch "HEAD" points at, and the receiving end needed to guess. A new capability has been defined in the pack protocol to convey this information so that cloning from a repository with more than one branches pointing at the same commit where the HEAD is at now reliably sets the initial branch in the resulting repository.
(Commit 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
, dated Nov 8, 2013, found with git log --grep="ambiguous" --grep="HEAD" --all-match
)
Edit (thanks to torek):
$ git name-rev --name-only 9196a2f8bd46d36a285bdfa03b4540ed3f01f671
tags/v1.8.4.3~3
This means that, if you're using Git v1.8.4.3 or later, you shouldn't run into any ambiguous-remote-HEAD problem.
Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).
One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream
and a FileOutputStream
, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.
The list of unstaged modified can be obtained using git status
and the grep
command like below. Something like git status -s | grep M
:
root@user-ubuntu:~/project-repo-directory# git status -s | grep '^ M'
M src/.../file1.js
M src/.../file2.js
M src/.../file3.js
....
Console.ReadLine()
to wait for the user to Enter or Console.ReadKey
to wait for any key.
Know this is an old post, but here's another short, effective way:
len -= String(num).length;
else, it's all good
function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}
str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']
Oneliner for doing all of the above operations:
for i in `ls -A .`; do if [ $i != ".git" ]; then rm -rf $i; fi; done; mv .git/* .; rm -rf .git; git config --bool core.bare true
(don't blame me if something blows up and you didn't have backups :P)
It needs you to add a Web Form, just go to add on properties -> new item -> Web Form. Then wen you run it, it will work. Simple
Ref : Youtube Video Download (Android/Java)
private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();
initTypeMap(); call first
class Meta {
public String num;
public String type;
public String ext;
Meta(String num, String ext, String type) {
this.num = num;
this.ext = ext;
this.type = type;
}
}
class Video {
public String ext = "";
public String type = "";
public String url = "";
Video(String ext, String type, String url) {
this.ext = ext;
this.type = type;
this.url = url;
}
}
public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
throws IOException {
if (ytUrl == null) {
return null;
}
// Remove any query params in query string after the watch?v=<vid> in
// e.g.
// http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
int andIdx = ytUrl.indexOf('&');
if (andIdx >= 0) {
ytUrl = ytUrl.substring(0, andIdx);
}
// Get the HTML response
/* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
/* HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
userAgent);
HttpGet request = new HttpGet(ytUrl);
HttpResponse response = client.execute(request);*/
String html = "";
HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line.replace("\\u0026", "&"));
}
in.close();
html = str.toString();
// Parse the HTML response and extract the streaming URIs
if (html.contains("verify-age-thumb")) {
Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
return null;
}
if (html.contains("das_captcha")) {
Log.e("Downloader", "Captcha found, please try with different IP address.");
return null;
}
Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
// Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
Matcher m = p.matcher(html);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}
if (matches.size() != 1) {
Log.e("Downloader", "Found zero or too many stream maps.");
return null;
}
String urls[] = matches.get(0).split(",");
HashMap<String, String> foundArray = new HashMap<String, String>();
for (String ppUrl : urls) {
String url = URLDecoder.decode(ppUrl, "UTF-8");
Log.e("URL","URL : "+url);
Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
Matcher m1 = p1.matcher(url);
String itag = null;
if (m1.find()) {
itag = m1.group(1);
}
Pattern p2 = Pattern.compile("signature=(.*?)[&]");
Matcher m2 = p2.matcher(url);
String sig = null;
if (m2.find()) {
sig = m2.group(1);
} else {
Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
Matcher m23 = p23.matcher(url);
if (m23.find()) {
sig = m23.group(1);
}
}
Pattern p3 = Pattern.compile("url=(.*?)[&]");
Matcher m3 = p3.matcher(ppUrl);
String um = null;
if (m3.find()) {
um = m3.group(1);
}
if (itag != null && sig != null && um != null) {
Log.e("foundArray","Adding Value");
foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
+ "signature=" + sig);
}
}
Log.e("foundArray","Size : "+foundArray.size());
if (foundArray.size() == 0) {
Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
return null;
}
ArrayList<Video> videos = new ArrayList<Video>();
for (String format : typeMap.keySet()) {
Meta meta = typeMap.get(format);
if (foundArray.containsKey(format)) {
Video newVideo = new Video(meta.ext, meta.type,
foundArray.get(format));
videos.add(newVideo);
Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
+ ", type:" + newVideo.type + ", url:" + newVideo.url);
}
}
return videos;
}
private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(webViewActivity.this, "",
"Connecting to YouTube...", true);
}
@Override
protected ArrayList<Video> doInBackground(String... params) {
ArrayList<Video> fVideos = new ArrayList<>();
String url = params[0];
try {
ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
/* Log.e("Downloader","Size of Video : "+videos.size());*/
if (videos != null && !videos.isEmpty()) {
for (Video video : videos)
{
Log.e("Downloader", "ext : " + video.ext);
if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
ext = video.ext.toLowerCase();
fVideos.add(new Video(video.ext,video.type,video.url));
}
}
return fVideos;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
}
Log.e("Downloader", "Couldn't get stream URI for " + url);
return null;
}
@Override
protected void onPostExecute(ArrayList<Video> streamingUrl) {
super.onPostExecute(streamingUrl);
progressDialog.dismiss();
if (streamingUrl != null) {
if (!streamingUrl.isEmpty()) {
//Log.e("Steaming Url", "Value : " + streamingUrl);
for (int i = 0; i < streamingUrl.size(); i++) {
Video fX = streamingUrl.get(i);
Log.e("Founded Video", "URL : " + fX.url);
Log.e("Founded Video", "TYPE : " + fX.type);
Log.e("Founded Video", "EXT : " + fX.ext);
}
//new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
}
}
}
}
public void initTypeMap()
{
typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}
Edit 2:
Some time This Code Not worked proper
Same-origin policy
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1].
url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts // DASH: contains video or audio stream
Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this
url // direct HTTP link to a video
itag // code specifying the quality
s // signature, security measure to counter downloading
Each URL will be encoded so you will need to decode them. Now the tricky part.
YouTube has at least 3 security levels for their videos
unsecured // as expected, you can download these with just the unencoded URL
s // see below
RTMPE // uses "rtmpe://" protocol, no known method for these
The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.
The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as
AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this
function mo(a) {
a = a.split("");
a = lo.rw(a, 1);
a = lo.rw(a, 32);
a = lo.IC(a, 1);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 44);
return a.join("")
}
This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as
http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js
this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header
Access-Control-Allow-Origin: http://www.youtube.com
and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests
Access-Control-Allow-Origin: *
So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.
In my case, when using IntelliJ, I had multiple modules in the project. The main module was dependent on another module which had the maven dependencies on Spring.
The main module had Entity
s and so did the second module. But when I ran the main module, only the Entity
s from the second module got recognized as managed classes.
I then added Spring dependencies on the main module as well, and guess what? It recognized all the Entity
s.
Going on the assumption you're using TNSNAMES naming, here's a couple of things to do:
> SERVICENAME_alias = > (DESCRIPTION = > (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.XYZi.com)(PORT = 1521)) > (CONNECT_DATA = (SERVICE_NAME = SERVICENAME))
This is assuming you're using the standard Oracle port of 1521. Note that servicename_alias can be any name you want to use on the local system. You may also find that you need to specify (SID = SERVICENAME) instead of (SERVICENAME=SERVICENAME).
For those Who Still Need This Here Is The Solution
$(function(){_x000D_
var t;_x000D_
document.addEventListener('scroll',function(e){_x000D_
clearTimeout(t);_x000D_
checkScroll();_x000D_
});_x000D_
_x000D_
function checkScroll(){_x000D_
t = setTimeout(function(){_x000D_
alert('Done Scrolling');_x000D_
},500); /* You can increase or reduse timer */_x000D_
}_x000D_
});
_x000D_
Short answer: 400-800 pixels.
What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.
Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.
There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.
I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).
Hope this advice helps.
In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
.
inside require
...If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.
A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/
Use FilenameUtils.removeExtension
from Apache Commons IO
Example:
You can provide full path name or only the file name.
String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"
Hope this helps ..
To print the current working Directory i.e. pwd just type command like:
echo "the PWD is : ${pwd}"
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
Public Sub EmptyTxt(ByVal Frm As Form)
Dim Ctl As Control
For Each Ctl In Frm.Controls
If TypeOf Ctl Is TextBox Then Ctl.Text = ""
If TypeOf Ctl Is GroupBox Then
Dim Ctl1 As Control
For Each Ctl1 In Ctl.Controls
If TypeOf Ctl1 Is TextBox Then
Ctl1.Text = ""
End If
Next
End If
Next
End Sub
add this code in form and call this function
EmptyTxt(Me)
Just for completion the data.table solution:
library(data.table)
mydf <- structure(list(ID = c(110L, 111L, 121L, 131L, 141L),
MONTH.YEAR = c("JAN. 2012", "JAN. 2012",
"FEB. 2012", "FEB. 2012",
"MAR. 2012"),
VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)),
.Names = c("ID", "MONTH.YEAR", "VALUE"),
class = "data.frame", row.names = c(NA, -5L))
setDT(mydf)
mydf[, .(`Number of rows` = .N), by = MONTH.YEAR]
MONTH.YEAR Number of rows
1: JAN. 2012 2
2: FEB. 2012 2
3: MAR. 2012 1
If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.
Databases are heavily optimized for common usage scenarios (and LIKE is one of those).
You won't find a faster way of doing your search if you want to stay on the DB-level.
This is an old post, but I thought I would add another method to do this:
var win = window.open("http://www.google.com");
var winClosed = setInterval(function () {
if (win.closed) {
clearInterval(winClosed);
foo(); //Call your function here
}
}, 250);
You don't have to modify the contents or use any event handlers from the child window.
li a[aria-expanded="true"] span{_x000D_
color: red;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
li a[aria-expanded="true"]{_x000D_
background: yellow;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
For devs needing something that works in the view source and the CLI, especially useful when debugging unit tests.
echo vd([['foo'=>1, 'bar'=>2]]);
function vd($in) {
ob_start();
var_dump($in);
return "\n" . preg_replace("/=>[\r\n\s]+/", "=> ", ob_get_clean());
}
Yields:
array(1) {
[0] => array(2) {
'foo' => int(1)
'bar' => int(2)
}
}
#include <stdio.h>
#include <stdlib.h>
// ....
system("my_bash_script.sh");
I had a similar issue using like pattern '%_%'
did not work - as the question indicates :-)
Using '%\_%'
did not work either as this first \
is interpreted "before the like".
Using '%\\_%'
works. The \\
(double backslash) is first converted to single \
(backslash) and then used in the like pattern.
loadXMLDoc JS function should return false, otherwise it will result in postback.
When creating a layout, it's easier to work with one control at a time, instead of adding them all at once.
From the Layouts Palette, drag a ConstraintLayout to the screen.
Move your desired controls inside the ConstraintLayout.
So the ConstraintLayout will now be the control's parents, and if you switch to the xml code, the controls will be nested under the ConstraintLayout.
Right click on your control, select Constraint from the menu, and select how you want to align it to the parent ConstraintLayout, top, start, etc.
If you need to align two controls relative to each other, select both controls at the same time with the Ctrl key, then right click to open the constrain menu.
More info: https://developer.android.com/training/constraint-layout
You can specify the constraint separation distance in the Constraint Layout tab:
You can find the last commit which deleted file as follows:
git rev-list -n 1 HEAD -- [file_path]
Further information is available here
I make all of the solutions in here with no result, so i look in another place and i found a way to trick the IDE, so you have to put a line in the Mainfest to make the Gradle use a different one, the one that you put on build.gradle the line is:
<uses-sdk tools:node="replace" />
just it, and it work.
I hope it helps.
Use a generator function to generate an iterator.
def foo_gen():
n = 0
while True:
n+=1
yield n
Then use it like
foo = foo_gen().next
for i in range(0,10):
print foo()
If you want an upper limit:
def foo_gen(limit=100000):
n = 0
while n < limit:
n+=1
yield n
If the iterator terminates (like the example above), you can also loop over it directly, like
for i in foo_gen(20):
print i
Of course, in these simple cases it's better to use xrange :)
Here is the documentation on the yield statement.
The MSDN documentation for environment variables tells you what to do:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.
try this
var insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);
Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter
Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.
Use a JSON parser. There are plenty of JSON parsers written in Java.
Look under the Java section and find one you like.
Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
If session.cookie_lifetime
is 0, the session cookie lives until the browser is quit.
EDIT: Others have mentioned the session.gc_maxlifetime
setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime
seconds. To set the time-to-live for the session cookie, call session_set_cookie_params()
or define the session.cookie_lifetime
PHP setting. If this setting is greater than session.gc_maxlifetime
, you should increase session.gc_maxlifetime
to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.
The easiest way is to use a StringContent
, with the JSON representation of your JSON object.
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"]
is set.
In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
If you are using Eclipse then please note that while running on XDebug mode the magic constant __FILE__ will always be evaluated to:
xdebug://debug-eval
So the following check will return true if your session is under XDebug:
$is_xdebug = false !== strpos(__FILE__,'xdebug'); // true while on XDebug
This is a very simple problem. You just iterate backwards:
for (NSInteger i = array.count - 1; i >= 0; i--) {
ElementType* element = array[i];
if ([element shouldBeRemoved]) {
[array removeObjectAtIndex:i];
}
}
This is a very common pattern.
This will show only Cart Items Count.
global $woocommerce;
echo $woocommerce->cart->cart_contents_count;
Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:
Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);
If you're using ctx.drawImage()
function, you can do the following:
var img = loadImage('../yourimage.png', callback);
function loadImage(src, callback) {
var img = new Image();
img.onload = callback;
img.setAttribute('crossorigin', 'anonymous'); // works for me
img.src = src;
return img;
}
And in your callback you can now use ctx.drawImage
and export it using toDataURL
Here is a really useful guide which solved my problem(OSX 10.13.6).
codesign -fs gdbc /usr/local/bin/gdb
in terminal: this asks for the root passwordOne line code for Done button:-
[yourTextField setReturnKeyType:UIReturnKeyDone];
And add action method on valueChanged of TextField and add this line-
[yourTextField resignFirstResponder];
You can't control the timeout due to UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.
But I find it hard to believe that you are really getting an UnknownHostException
when you specify an IP address rather than a hostname.
EDIT To control Java's DNS timeouts see this answer.
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
Try this:
<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">
$scope.ageFilter = function (player) {
return (player.age > $scope.min_age && player.age < $scope.max_age);
}
using value get input name
$('input[value="1"]').attr('name');
using id get input name
$('input[class="id"]').attr('name');
$('#id').attr('name');
using class get input name
$('input[value="classname"]').attr('name');
$('.classname').attr('name'); //if classname have unique value
Open Terminal:
sudo gem update --system
It works!
Powershell also accept the C/C++/C* not operator
if ( !(Test-Path C:\Code) ){ write "it doesn't exist!" }
I use it often because I'm used to C*...
allows code compression/simplification...
I also find it more elegant...
There is an easier way to fix this issue with Mac OS and Homebrew:
Install homebrew if it is not installed yet
$brew install libpng
$pngfix --strip=color --out=file2.png file.png
or to do it with every file in the current directory:
mkdir tmp; for f in ./*.png; do pngfix --strip=color --out=tmp/"$f" "$f"; done
It will create a fixed copy for each png file in the current directory and put it in the the tmp subdirectory. After that, if everything is OK, you just need to override the original files.
Another tip is to use the Keynote and Preview applications to create the icons. I draw them using Keynote, in the size of about 120x120 pixels, over a slide with a white background (the option to make polygons editable is great!). Before exporting to Preview, I draw a rectangle around the icon (without any fill or shadow, just the outline, with the size of about 135x135) and copy everything to the clipboard. After that, you just need to open it with the Preview tool using "New from Clipboard", select a 128x128 pixels area around the icon, copy, use "New from Clipboard" again, and export it to PNG. You won't need to run the pngfix tool.
As an additional note, there is no need for the for loop because of R's vectorization.
This:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01))
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
}
is equivalent to:
P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
Because r
is a vector, the expression above containing it is performed for all values of the vector.
With the new Tensorflow 2.1 release, the default tensorflow
pip package contains both CPU and GPU versions of TF. In previous TF versions, not finding the CUDA libraries would emit an error and raise an exception, while now the library dynamically searches for the correct CUDA version and, if it doesn't find it, emits the warning (The W in the beginning stands for warnings, errors have an E (or F for fatal errors) and falls back to CPU-only mode. In fact, this is also written in the log as an info message right after the warning (do note that if you have a higher minimum log level that the default, you might not see info messages). The full log is (emphasis mine):
2020-01-20 12:27:44.554767: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-01-20 12:27:44.554964: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
If you don't have a CUDA-enabled GPU on your machine, or if you don't care about not having GPU acceleration, no need to worry. If, on the other hand, you installed tensorflow and wanted GPU acceleration, check your CUDA installation (TF 2.1 requires CUDA 10.1, not 10.2 or 10.0).
If you just want to get rid of the warning, you can adapt TF's logging level to suppress warnings, but that might be overkill, as it will silence all warnings.
Your CUDA setup is broken, ensure you have the correct version installed.
.nav-menu li:not(:last-child){
// write some style here
}
this code should apply the style to all
Another alternative is that you are allowed to have multiple classes in a tag. Consider:
<div class="button big">This is a big button</div>
<div class="button small">This is a small button</div>
And the CSS:
.button {
/* all your common button styles */
}
.big {
height: 60px;
width: 100px;
}
.small {
height: 40px;
width: 70px;
}
and so on.
The !=
operator serves this purpose for bool
values.
Font Squirrel has a wonderful web font generator.
I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.
This does cause "funky characters":
System.out.println( "Mr. Foo".trim().replace('.','\0'));
produces:
Mr[] Foo
in my Eclipse console, where the [] is shown as a square box. As others have posted, use String.replace()
.
In Python 2.x just put a ,
at the end of your print
statement. If you want to avoid the blank space that print
puts between items, use sys.stdout.write
.
import sys
sys.stdout.write('hi there')
sys.stdout.write('Bob here.')
yields:
hi thereBob here.
Note that there is no newline or blank space between the two strings.
In Python 3.x, with its print() function, you can just say
print('this is a string', end="")
print(' and this is on the same line')
and get:
this is a string and this is on the same line
There is also a parameter called sep
that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep
)
E.g.,
Python 2.x
print 'hi', 'there'
gives
hi there
Python 3.x
print('hi', 'there', sep='')
gives
hithere
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Like this:
sed 's/aaa=.*/aaa=xxx/'
If you want to guarantee that the aaa=
is at the start of the line, make it:
sed 's/^aaa=.*/aaa=xxx/'
You can simply pass your dataframe into the following function:
def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
return(frame)
Example:
I have a dataframe (awards_frame) as follows:
...and I want to create a new column that shows the sum of awards for each row:
Usage:
I simply pass my awards_frame into the function, also specifying the name of the new column, and a list of column names that are to be summed:
sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])
Result:
sender
refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs
is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler
or EventHandler<T>
as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
Several choices to do this...
Set background to green:
v.setBackgroundColor(0x00FF00);
Set background to green with Alpha:
v.setBackgroundColor(0xFF00FF00);
Set background to green with Color.GREEN constant:
v.setBackgroundColor(Color.GREEN);
Set background to green defining in Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="myGreen">#00FF00</color>
<color name="myGreenWithAlpha">#FF00FF00</color>
</resources>
and using:
v.setBackgroundResource(R.color.myGreen);
and:
v.setBackgroundResource(R.color.myGreenWithAlpha);
or the longer winded:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));
and:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));
Here is a modern approach, using globalThis
, we took for our React Native app.
globalThis
is now included in...
appGlobals.ts
// define our parent property accessible via globalThis. Also apply the TypeScript type.
var app: globalAppVariables;
// define the child properties and their types.
type globalAppVariables = {
messageLimit: number;
// more can go here.
};
// set the values.
globalThis.app = {
messageLimit: 10,
// more can go here.
};
// Freeze so these can only be defined in this file.
Object.freeze(globalThis.app);
App.tsx (our main entry point file)
import './appGlobals'
// other code
anyWhereElseInTheApp.tsx
const chatGroupQuery = useQuery(GET_CHAT_GROUP_WITH_MESSAGES_BY_ID, {
variables: {
chatGroupId,
currentUserId: me.id,
messageLimit: globalThis.app.messageLimit, // used here.
},
});
print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]]
I was facing this problem after adding a jar which is already in the SVN and I added the new Version of it with the same name.
In Eclipse I tried this
Using above steps I am able to Synchronize.
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
You have an extra closing }
in your function.
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <== remove this brace
}, false);
};
You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.
This answer is for those of you looking to Install Bootstrap 3 in your Rails app without using a gem. There are two simple ways to do this that take less than 10 minutes. Pick the one that suites your needs best. Glyphicons and Javascript work and I've tested them with the latest beta of Rails 4.1.0 as well.
Using Bootstrap 3 with Rails 4 - The Bootstrap 3 files are copied into the vendor directory of your application.
Adding Bootstrap from a CDN to your Rails application - The Bootstrap 3 files are served from the Bootstrap CDN.
Number 2 above is the most flexible. All you need to do is change the version number that is stored in a layout helper. So you can run the Bootstrap version of your choice, whether that is 3.0.0, 3.0.3 or even older Bootstrap 2 releases.
CentOS (RHEL) 7, has changed the firewall to use firewall-cmd
which has a notion of zones which is like a Windows version of Public, Home, and Private networks. You should look here to figure out which one you think you should use. EL7 uses public
by default so that is what my examples below use.
You can check which zone you are using with firewall-cmd --list-all
and change it with firewall-cmd --set-default-zone=<zone>
.
You will then know what zone to allow a service (or port) on:
firewall-cmd --permanent --zone=<zone> --add-service=http
firewall-cmd --permanent --zone=<zone> --add-port=80/tcp
You can check if the port has actually be opened by running:
firewall-cmd --zone=<zone> --query-port=80/tcp
firewall-cmd --zone=<zone> --query-service=http
According to the documentation,
When making changes to the firewall settings in Permanent mode, your selection will only take effect when you reload the firewall or the system restarts.
You can reload the firewall settings with: firewall-cmd --reload
.
Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html
You can use the clearfix
to do "layout preserving" the same way overflow: hidden
does.
.clearfix:before,
.clearfix:after {
content: ".";
display: block;
height: 0;
overflow: hidden;
}
.clearfix:after { clear: both; }
.clearfix { zoom: 1; } /* IE < 8 */
add class="clearfix"
class to the parent, and remove overflow: hidden;
I got this issue solved in the 'Windows' way. After checking all my settings, cleaning the solution and rebuilding it, I simply close the solution and reopened it. Then it worked, so VS probably didn't get rid of some stuff during cleaning. When logical solutions don't work, I usually turn to illogical (or seemingly illogical) ones. Windows doesn't let me down. :)
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
The EclipsePasteAsJavaString plug-in allows you to insert text as a Java string by Ctrl + Shift + V
Paste as usual via Ctrl+V:
some text with tabs
and new
lines
Paste as Java string via Ctrl+Shift+V
"some text\twith tabs\r\n" +
"and new \r\n" +
"lines"
What's wrong with
func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)
and so on?
This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.
public static void AutoFitExcelSheets()
{
Microsoft.Office.Interop.Excel.Application _excel = null;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
try
{
string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
_excel = new Microsoft.Office.Interop.Excel.Application();
_excel.Visible = false;
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
excelWorkbook = _excel.Workbooks.Open(ExcelPath,
0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
{
string Name = currentSheet.Name;
Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
excelCells.Columns.AutoFit();
}
}
catch (Exception ex)
{
ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
}
finally
{
excelWorkbook.Close(true, Type.Missing, Type.Missing);
GC.Collect();
GC.WaitForPendingFinalizers();
releaseObject(excelWorkbook);
releaseObject(_excel);
}
}
In terms of direct values a regular char is used when the values are known to be between CHAR_MIN
and CHAR_MAX
while an unsigned char provides double the range on the positive end. For example, if CHAR_BIT
is 8, the range of regular char
is only guaranteed to be [0, 127] (because it can be signed or unsigned) while unsigned char
will be [0, 255] and signed char
will be [-127, 127].
In terms of what it's used for, the standards allow objects of POD (plain old data) to be directly converted to an array of unsigned char. This allows you to examine the representation and bit patterns of the object. The same guarantee of safe type punning doesn't exist for char or signed char.
In Android Studio, by pressing ALT + INSERT (or ? + N for MacOS), you will have following choices (including your solution!):
Note: Some methods are auto implemented but you can select
Override Methods...
option to implement other unimplemented methods.
You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.
filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')
lines = f.readlines() # get all lines as a list (array)
# Iterate over each line, printing each line and then move to the next
for line in lines:
print line
f.close()
There are 4 methods you can use:
Consider the following sample TABLE
with test data:
/** Create test table */
CREATE TEMPORARY TABLE dupes(word text, num int, id int);
/** Add test data with duplicates */
INSERT INTO dupes(word, num, id)
VALUES ('aaa', 100, 1)
,('bbb', 200, 2)
,('ccc', 300, 3)
,('bbb', 400, 4)
,('bbb', 200, 5) -- duplicate
,('ccc', 300, 6) -- duplicate
,('ddd', 400, 7)
,('bbb', 400, 8) -- duplicate
,('aaa', 100, 9) -- duplicate
,('ccc', 300, 10); -- duplicate
This is the most simple and straight forward, but also the most limited way:
SELECT DISTINCT word, num
FROM dupes
ORDER BY word, num;
/*
word|num|
----|---|
aaa |100|
bbb |200|
bbb |400|
ccc |300|
ddd |400|
*/
Grouping allows you to add aggregated data, like the min(id)
, max(id)
, count(*)
, etc:
SELECT word, num, min(id), max(id), count(*)
FROM dupes
GROUP BY word, num
ORDER BY word, num;
/*
word|num|min|max|count|
----|---|---|---|-----|
aaa |100| 1| 9| 2|
bbb |200| 2| 5| 2|
bbb |400| 4| 8| 2|
ccc |300| 3| 10| 3|
ddd |400| 7| 7| 1|
*/
Using a subquery, you can first identify the duplicate rows to ignore, and then filter them out in the outer query with the WHERE NOT IN (subquery)
construct:
/** Find the higher id values of duplicates, distinct only added for clarity */
SELECT distinct d2.id
FROM dupes d1
INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
WHERE d2.id > d1.id
/*
id|
--|
5|
6|
8|
9|
10|
*/
/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT *
FROM dupes
WHERE id NOT IN (
SELECT d2.id
FROM dupes d1
INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
WHERE d2.id > d1.id
)
ORDER BY word, num;
/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
In the Common Table Expression (CTE), select the ROW_NUMBER(), partitioned by the group column and ordered in the desired order. Then SELECT only the records that have ROW_NUMBER() = 1
:
WITH CTE AS (
SELECT *
,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
FROM dupes
)
SELECT word, num, id
FROM cte
WHERE row_num = 1
ORDER BY word, num;
/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/
I fully agree with Mikko, but if you still want to do it, here is the way:
csrutil disable
This is what I get from console on Windows 10:
C:\>find /?
Searches for a text string in a file or files.
FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]
/V Displays all lines NOT containing the specified string.
/C Displays only the count of lines containing the string.
/N Displays line numbers with the displayed lines.
/I Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string" Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.
If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.
Here is an elegant library that records video in all supported browsers and supports uploading:
If I understand your question correctly, then you probably want a density estimate along with the histogram:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE) # prob=TRUE for probabilities not counts
lines(density(X)) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted") # add another "smoother" density
Edit a long while later:
Here is a slightly more dressed-up version:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2)
along with the graph it produces:
Just make the anchor display: block
and width/height: 100%
. Eg:
.button a {
display: block;
width: 100%;
height: 100%;
}
jsFiddle: http://jsfiddle.net/4mHTa/
Using a nested .each()
means that your inner loop is doing one td at a time, so you can't set the productId
and product
and quantity
all in the inner loop.
Also using function(key, val)
and then val[key].innerHTML
isn't right: the .each()
method passes the index (an integer) and the actual element, so you'd use function(i, element)
and then element.innerHTML
. Though jQuery also sets this
to the element, so you can just say this.innerHTML
.
Anyway, here's a way to get it to work:
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
});
See How to Make Dialogs.
You can use:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.
Assuming cloud is int cloud[10]
you can do it like this:
int *p = max_element(cloud, cloud + 10);
You can also use
$('#myModal').hasClass('show');
Verifiable code should not be able to corrupt memory, so there's something unsafe going on. Are you using any unsafe code anywhere, such as in buffer processing? Also, the stuff about PInvoke may not be irrelevant, as PInvoke involves a transition to unmanaged code and associated marshaling.
My best recommendation is to attach to a crashed instance and use WinDBG and SOS to dig deeper into what's happening at the time of the crash. This is not for the faint of heart, but at this point you may need to break out more powerful tools to determine what, exactly, is going wrong.
I get this problem caused for a package that don't update correctly with wildcards, I use directly the last version and it works finally.
"l3/cas-bundle": "~1.0" -------> "l3/cas-bundle": "1.1.13"
TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1
Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0
You should consider an upgrade.
You can also use unlist()
, which is often useful for handling lists:
> mylist <- list(A = c(1:3), B = c(4:6), C = c(7:9))
> mylist
$A
[1] 1 2 3
$B
[1] 4 5 6
$C
[1] 7 8 9
> unlist(mylist)
A1 A2 A3 B1 B2 B3 C1 C2 C3
1 2 3 4 5 6 7 8 9
> length(unlist(mylist))
[1] 9
unlist() is a simple way of executing other functions on lists as well, such as:
> sum(mylist)
Error in sum(mylist) : invalid 'type' (list) of argument
> sum(unlist(mylist))
[1] 45
All you need is
e.preventDefault();
on child element.
What fixed it for me was upgrading the MS.Test nuget packages
Run the following command to get it solved :
autopep8 -i <filename>.py
This will update your code and solve all indentation Errors :)
Hope this will solve
I am late but complete solution;: Example Class, Use Context like this :-
public class SingletonSampleClass {
// Your cute context
private Context context;
private static SingletonSampleClass instance;
// Pass as Constructor
private SingletonSampleClass(Context context) {
this.context = context;
}
public synchronized static SingletonSampleClass getInstance(Context context) {
if (instance == null) instance = new SingletonSampleClass(context);
return instance;
}
//At end, don't forgot to relase memory
public void onDestroy() {
if(context != null) {
context = null;
}
}
}
Warning (Memory Leaks)
How to solve this?
Option 1: Instead of passing activity context i.e. this to the singleton class, you can pass applicationContext().
Option 2: If you really have to use activity context, then when the activity is destroyed, ensure that the context you passed to the singleton class is set to null.
Hope it helps..????
For bootstrap 4 we have new classes named with following notation
m - for classes that set margin
p - for classes that set padding
Specify Top, bottom,left, right, left & right, top & bottom using below letters
t - for classes that set margin-top (mt) or padding-top (pt)
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
Specify size using following numbers
0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
Actual Code from bootstrap 4 css file
.mt-0 {
margin-top: 0 !important;
}
.ml-1 {
margin-left: ($spacer * .25) !important;
}
.px-2 {
padding-left: ($spacer * .5) !important;
padding-right: ($spacer * .5) !important;
}
.p-3 {
padding: $spacer !important;
}
Usage
So when you need some padding left just add any class from pl-0
to pl-5
based on your need
If you need margin on top just add any class from mt-0
to mt-5
based on your need
<div class="col-sm-6 mt-5"> this div will have margin top added </div>
<div class="col-sm-6 pl-5"> this div will have padding left added </div>
you can use QString::fromAscii()
QByteArray data = entity->getData();
QString s_data = QString::fromAscii(data.data());
with data()
returning a char*
for QT5, you should use fromCString()
instead, as fromAscii()
is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872
How is it noone has mentioned..
document.activeElement.id
I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..
if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
// action here
}
Use window.intro
inside of $(document).ready()
.
Yes.. It is possible using css
<a class="disable-me" href="page.html">page link</a>
.disable-me {
pointer-events: none;
}
The first thing is to make a comparison of functions of SHA and opt for the safest algorithm that supports your programming language (PHP).
Then you can chew the official documentation to implement the hash()
function that receives as argument the hashing algorithm you have chosen and the raw password.
sha256 => 64 bits
sha384 => 96 bits
sha512 => 128 bits
The more secure the hashing algorithm is, the higher the cost in terms of hashing and time to recover the original value from the server side.
$hashedPassword = hash('sha256', $password);
You can do this using -T
option in cp
.
See Man page for cp
.
-T, --no-target-directory
treat DEST as a normal file
So as per your example, following is the file structure.
$ tree test
test
|-- bar
| |-- a
| `-- b
`-- foo
|-- a
`-- b
2 directories, 4 files
You can see the clear difference when you use -v
for Verbose.
When you use just -R
option.
$ cp -Rv foo/ bar/
`foo/' -> `bar/foo'
`foo/b' -> `bar/foo/b'
`foo/a' -> `bar/foo/a'
$ tree
|-- bar
| |-- a
| |-- b
| `-- foo
| |-- a
| `-- b
`-- foo
|-- a
`-- b
3 directories, 6 files
When you use the option -T
it overwrites the contents, treating the destination like a normal file and not directory.
$ cp -TRv foo/ bar/
`foo/b' -> `bar/b'
`foo/a' -> `bar/a'
$ tree
|-- bar
| |-- a
| `-- b
`-- foo
|-- a
`-- b
2 directories, 4 files
This should solve your problem.
You can use tabindex
<div tabindex="-1" id="tries"></div>
The tabindex value can allow for some interesting behaviour.
Style is an attribute so css
won't work for it.U can use attr
Change:
$('.handle').css({'style':'left: 300px'});
T0:
$('.handle').attr('style','left: 300px');//Use `,` Comma instead of `:` colon
Open sFileName For Input As iFileNum
Dim LineNum As Long
LineNum = 0
Do While Not EOF(iFileNum)
LineNum = LineNum + 1
Line Input #iFileNum, Fields
If LineNum > 2 Then
DoStuffWith(Fields)
End If
Loop
If you're using Spring 5.2.5 and Spring Boot 2.2.6 and want to override just a few properties instead of the whole file. You can use the new annotation: @DynamicPropertySource
@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
@DynamicPropertySource
static void neo4jProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
}
}
MYSQL_HOME variable value:C:\Program Files\MySQL\MySQL Server 5.0\bin %MYSQL_HOME%\bin
See the problem? This resolves to a path of C:\Program Files\MySQL\MySQL Server 5.0\bin\bin
Had the same issue, resolved by actually enabling the extension in the php.ini with the right file name. It was listed as php_pdo_mysql.so but the module name in /lib/php/modules was called just pdo_mysql.so
So just remove the "php_" prefix from the php.ini file and then restart the httpd service and it worked like a charm.
Please note that I'm using Arch and thus path names and services may be different depending on your distrubution.
It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:
Hard reset
git reset --hard [HEAD]
completely remove all staged and unstaged changes to tracked files.
I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.
Clean
git clean [-f]
Remove files that are not tracked.
For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.
The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.
Git clean will not touch files, that are already being tracked.
Checkout "dot"
git checkout .
I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:
"undo all changes in my working tree".
I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.
Stashing
Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.
To sum up
Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD
followed by git clean -f
will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).
All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)
I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard
was that you had never staged anything. Had you staged a change, neither git checkout .
nor git clean -f
would have reverted that.
Hope this covers.
Basically you should not mess the question with answer, because it is confusing.
Then you could specify what convert mean and pick one of this solution
List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));
List<String> valueList = Collections.list(Collections.enumeration(map.values()));
You have to be careful about the xib file. I tried all the above and nothing worked for me. I was using custom UIButtons defined in the xib, and realized it might be related to the fact that I had assigned attributes there which were not changing programmatically. If you've defined images or text there, remove them. When I did, my programmatic changes began to take effect.
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Creating a dummy blank repositories.cfg works on Windows 7 as well. After waiting for a couple of minutes the installation finishes and you get the message on your cmd window -- done
You can use this code snippet:
var New1 = EmpList.OrderBy(z => z.Age).ToList();
where New1
is a List<Employee>
.
EmpList
is variable of a List<Employee>
.
z
is a variable of Employee
type.
If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.
It looks like there's something else called Afisho_rankimin
in your DB so the function is not being created. Try calling your function something else. E.g.
CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
Note that you need to call this only once, not every time you call the function. After that try calling
SELECT dbo.Afisho_rankimin1(5) AS Rankimi
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel
And you will surely get Interactive Plot. Happy Coding!
This might look stupid, but check if you haven't already added the folder/files you are trying to ignore to the index before. If you did, it does not matter what you put in your .gitignore file, the folders/files will still be staged.
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.
Sorry for resurrecting an old thread, but I was with the same problem today. The simplest way that I have found is the following:
# Expand right side of clipping rect to make room for the legend
par(xpd=T, mar=par()$mar+c(0,0,0,6))
# Plot graph normally
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
# Plot legend where you want
legend(3.2,1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))
# Restore default clipping rect
par(mar=c(5, 4, 4, 2) + 0.1)
Found here: http://www.harding.edu/fmccown/R/
I solved it by going in /etc/yum.repository.d/. For my case i comment out mirrorlist and uncomenting entries with baseurl. as well as added sslverify=false.
https://serverfault.com/questions/637549/epel-repo-for-centos-6-causing-error