Edit 2 (2017):
In all modern browsers you can simply call: console.trace();
(MDN Reference)
Edit 1 (2013):
A better (and simpler) solution as pointed out in the comments on the original question is to use the stack
property of an Error
object like so:
function stackTrace() {
var err = new Error();
return err.stack;
}
This will generate output like this:
DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
Giving the name of the calling function along with the URL, its calling function, and so on.
Original (2009):
A modified version of this snippet may somewhat help:
function stacktrace() {
function st2(f) {
return !f ? [] :
st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
}
return st2(arguments.callee.caller);
}
from superuser accepted answer:
sudo mysql -u root
use mysql;
update user set plugin='' where User='root';
flush privileges;
exit;
Explanation: You can *ngFor on the arrays. You have your users declared as the array. But, the response from the Get returns you an object. You cannot ngFor on the object. You should have an array for that. You can explicitly cast the object to array and that will solve the issue. data to [data]
Solution
getusers() {
this.http.get(`https://api.github.com/
search/users?q=${this.input1.value}`)
.map(response => response.json())
.subscribe(
data => this.users = [data], //Cast your object to array. that will do it.
error => console.log(error)
)
Try this command,
sudo service mysql start
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait
object.
boolean isDialogPresent(WebDriver driver) {
IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
return (alert != null);
}
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
You can get value by using id for that element in onclick function
function dosomething(){
var buttonValue = document.getElementById('buttonId').value;
}
If you handle "adding tag" via JScript:
<form ...>
<button onclick="...">any text you want</button>
</form>
Or above if handle via page reload
If Your problem is due to multiple (versions of) xcode
Then follow following steps
1. Cleaning Derived Data
Go to Xcode preferences -> Select location tab -> select little gray arrow on /Users/apple/Library/Developer/Xcode/DerivedData. You will be redirect to folder From there select Derived Data folder and Delete.
2. Completely Quite The Xcode and reopen
This will solve your problem. Happy coding :)
You can simply use:
document.getElementById(button_id).innerText = 'Your text here';
If you want to use HTML formatting, use the innerHTML
property instead.
The problem lies that you haven't added Model
to either the bootstrap
(which will make it a singleton), or to the providers
array of your component definition:
@Component({
selector: "testWidget",
template: "<div>This is a test and {{param1}} is my param.</div>",
providers : [
Model
]
})
export class testWidget {
constructor(private model: Model) {}
}
And yes, you should define Model
above the Component
. But better would be to put it in his own file.
But if you want it to be just a class from which you can create multiple instances, you better just use new
.
@Component({
selector: "testWidget",
template: "<div>This is a test and {{param1}} is my param.</div>"
})
export class testWidget {
private model: Model = new Model();
constructor() {}
}
Sheet.getPhysicalNumberOfRows()
does not involve some empty rows.
If you want to loop for all rows, do not use this to know the loop size.
For Xamarin.iOS (C#):
myButton.VerticalAlignment = UIControlContentVerticalAlignment.Fill;
myButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Fill;
myButton.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
I think you may use the callback from a JSONP request or maybe just the pure JSON data using an external service but based on the output of javascript location.host
that way:
$.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
console.warn('Fetching JSON data...');
// Log output to console
console.info(JSON.stringify(data, null, 2));
});
I'll use this code for my personal needs, as first I was coming on this site for the same reason.
You may use another external service instead the one I'm using for my needs. A very nice list exist and contains tests done here https://stackoverflow.com/a/35123097/5778582
it is just that add below code in the index.html head tag
<html>
<head>
<base href="/">
...
that worked like a charm for me.
J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.
For Python version < 2.6, here's the best I can come up with:
from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()
Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:
from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))
UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:
from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()
Since diawi.com have added some limitations for free accounds.
Next best available and easy to use alternative is
Microsoft
https://firebase.google.com/docs/app-distribution/ios/distribute-console
Others
Happy build sharing!
Do like jQuery does! (the essence)
function parseJSON(data) {
return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))();
}
// testing
obj = parseJSON('{"name":"John"}');
alert(obj.name);
This way you don't need any external library and it still works on old browsers.
This single line will do the trick:
Array.from(String(12345), Number);
const numToSeparate = 12345;
const arrayOfDigits = Array.from(String(numToSeparate), Number);
console.log(arrayOfDigits); //[1,2,3,4,5]
_x000D_
1- String(numToSeparate)
will convert the number 12345 into a string, returning '12345'
2- The Array.from()
method creates a new Array instance from an array-like or iterable object, the string '12345' is an iterable object, so it will create an Array from it.
3- But, in the process of automatically creating this new array, the Array.from()
method will first pass any iterable element (every character in this case eg: '1', '2') to the function we set to him as a second parameter, which is the Number
function in this case
4- The Number
function will take any string character and will convert it into a number eg: Number('1')
; will return 1
.
5- These numbers will be added one by one to a new array and finally this array of numbers will be returned.
Summary
The code line Array.from(String(numToSeparate), Number);
will convert the number into a string, take each character of that string, convert it into a number and put in a new array. Finally, this new array of numbers will be returned.
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
I know it's a very late answer but I'd like to share what I did as per this link:
I added the below code to the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
And this Advice Controller in order to get the version as model attribute:
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class CommonControllerAdvice
{
@Autowired
BuildProperties buildProperties;
@ModelAttribute("version")
public String getVersion() throws IOException
{
String version = buildProperties.getVersion();
return version;
}
}
The answer by @hybrid is quite informative, except it doesn't explain the purpose as mentioned by @ashitaka "What if you use the Mobile First approach? So, we have the mobile CSS first and then use min-width to target larger sites. We shouldn't use the only keyword in that context, right? "
Want to add in here that the purpose is simply to prevent non supporting browsers to use that Other device style as if it starts from "screen" without it will take it for a screen whereas if it starts from "only" style will be ignored.
Answering to ashitaka consider this example
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />
If we don't use "only" it will still work as desktop-style will also be used striking android styles but with unnecessary overhead. In this case, IF a browser is non-supporting it will fallback to the second Style-sheet ignoring the first.
Try this:
1) Plug your iOS device into your Mac using a lightning cable. You may need to select to Trust This Computer on your device.
2) Open Xcode and go to Window > Devices and Simulators.
3) Select your device and then select the Connect via network checkbox to pair your device.
4) Run your project after removing your lighting cable.
The problem with using querySelectorAll
and a for
loop is that it creates a whole new event handler for each element in the array.
Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target
to refer to the specific element which triggered the event:
document.body.addEventListener("click", function (event) {
if (event.target.classList.contains("delete")) {
var title = event.target.getAttribute("title");
if (!confirm("sure u want to delete " + title)) {
event.preventDefault();
}
}
});
In this example we only create one event handler which is attached to the body
element. Whenever an element inside the body
is clicked, the click
event bubbles up to our event handler.
function chunkArrayInGroups(arr, size) {
var newArr=[];
for (var i=0; i < arr.length; i+= size){
newArr.push(arr.slice(i,i+size));
}
return newArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);
An iframe is used to embed another document inside a html page.
If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.
Set the target attribute of the form to the name of the iframe tag.
<form action="action" method="post" target="output_frame">
<!-- input elements here -->
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>
Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files
The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.
Exmaple
<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });
function startUpload()
{
$("#uploadDialog").dialog("open");
}
function stopUpload()
{
$("#uploadDialog").dialog("close");
}
</script>
<div id="uploadDialog" title="Please Wait!!!">
<center>
<img src="/imagePath/loading.gif" width="100" height="100"/>
<br/>
Loading Details...
</center>
</div>
<FORM ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()">
<!-- input file elements here-->
</FORM>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">
</iframe>
There is a new one: http://hayatbiralem.com/blog/2015/05/15/responsive-bootstrap-tabs/
And also Codepen sample available here: http://codepen.io/hayatbiralem/pen/KpzjOL
No needs plugin. It uses just a little css and jquery.
Here's a sample tabs markup:
<ul class="nav nav-tabs nav-tabs-responsive">
<li class="active">
<a href="#tab1" data-toggle="tab">
<span class="text">Tab 1</span>
</a>
</li>
<li class="next">
<a href="#tab2" data-toggle="tab">
<span class="text">Tab 2</span>
</a>
</li>
<li>
<a href="#tab3" data-toggle="tab">
<span class="text">Tab 3</span>
</a>
</li>
...
</ul>
.. and jQuery codes are also here:
(function($) {
'use strict';
$(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
var $target = $(e.target);
var $tabs = $target.closest('.nav-tabs-responsive');
var $current = $target.closest('li');
var $parent = $current.closest('li.dropdown');
$current = $parent.length > 0 ? $parent : $current;
var $next = $current.next();
var $prev = $current.prev();
var updateDropdownMenu = function($el, position){
$el
.find('.dropdown-menu')
.removeClass('pull-xs-left pull-xs-center pull-xs-right')
.addClass( 'pull-xs-' + position );
};
$tabs.find('>li').removeClass('next prev');
$prev.addClass('prev');
$next.addClass('next');
updateDropdownMenu( $prev, 'left' );
updateDropdownMenu( $current, 'center' );
updateDropdownMenu( $next, 'right' );
});
})(jQuery);
The Trace messages can occur in the output window as well, even if you're not in debug mode. You just have to make sure the the TRACE compiler constant is defined.
var thisList = new List<string>{ "a", "b", "c" };
var otherList = new List<string> {"a", "b"};
var theOnesThatDontMatch = thisList
.Where(item=> otherList.All(otherItem=> item != otherItem))
.ToList();
var theOnesThatDoMatch = thisList
.Where(item=> otherList.Any(otherItem=> item == otherItem))
.ToList();
Console.WriteLine("don't match: {0}", string.Join(",", theOnesThatDontMatch));
Console.WriteLine("do match: {0}", string.Join(",", theOnesThatDoMatch));
//Output:
//don't match: c
//do match: a,b
Adapt the list types and lambdas accordingly, and you can filter out anything.
session.flush() is synchronise method means to insert data in to database sequentially.if we use this method data will not store in database but it will store in cache,if any exception will rise in middle we can handle it. But commit() it will store data in database,if we are storing more amount of data then ,there may be chance to get out Of Memory Exception,As like in JDBC program in Save point topic
The EOF pattern needs a prime read to 'bootstrap' the EOF checking process. Consider the empty file will not initially have its EOF set until the first read. The prime read will catch the EOF in this instance and properly skip the loop completely.
What you need to remember here is that you don't get the EOF until the first attempt to read past the available data of the file. Reading the exact amount of data will not flag the EOF.
I should point out if the file was empty your given code would have printed since the EOF will have prevented a value from being set to x on entry into the loop.
So add a prime read and move the loop's read to the end:
int x;
iFile >> x; // prime read here
while (!iFile.eof()) {
cerr << x << endl;
iFile >> x;
}
For those of you running into the DirectoryNotFoundException, add this check:
if (Directory.Exists(path)) Directory.Delete(path, true);
m/ /g
just give space in / /
, and it will work. Or use \S
— it will replace all the special characters like tab, newlines, spaces, and so on.
http://www.w3schools.com/cssref/pr_list-style-type.asp
You need to use list-style-type:
to change bullet type/style and the above link has all of the options listed. As others have stated the color is changed using the color
property on the ul
itself
To create 'black filled' bullets, use 'disc' instead of 'circle',i.e.:
list-style-type:disc
You can use Microsoft.Office.Interop.Excel
assembly to process excel files.
Add reference
. Add the
Microsoft.Office.Interop.Excel assembly. using
Microsoft.Office.Interop.Excel;
to make use of assembly.Here is the sample code:
using Microsoft.Office.Interop.Excel;
//create the Application object we can use in the member functions.
Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application();
_excelApp.Visible = true;
string fileName = "C:\\sampleExcelFile.xlsx";
//open the workbook
Workbook workbook = _excelApp.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
//select the first sheet
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
//find the used range in worksheet
Range excelRange = worksheet.UsedRange;
//get an object array of all of the cells in the worksheet (their values)
object[,] valueArray = (object[,])excelRange.get_Value(
XlRangeValueDataType.xlRangeValueDefault);
//access the cells
for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row)
{
for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col)
{
//access each cell
Debug.Print(valueArray[row, col].ToString());
}
}
//clean up stuffs
workbook.Close(false, Type.Missing, Type.Missing);
Marshal.ReleaseComObject(workbook);
_excelApp.Quit();
Marshal.FinalReleaseComObject(_excelApp);
I used this SparkContext constructor instead, and errors were gone:
val sc = new SparkContext("local[*]", "MyApp")
I also encountered this problem. It confused me several hours. I tried many of solutions which were suggested in this topic. At last, I found it was due to the Java Element Filters.
//Disable right click script via java script code
<script language=JavaScript>
//Disable right click script
var message = "";
///////////////////////////////////
function clickIE() {
if (document.all) {
(message);
return false;
}
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2 || e.which == 3) {
(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false")
</script>
If you want to see which IP addresses are in use on a specific subnet then there are several different IP Address managers.
Try Angry IP Scanner or Solarwinds or Advanced IP Scanner
START_STICKY
: It will restart the service in case if it terminated and the Intent data which is passed to the onStartCommand()
method is NULL
. This is suitable for the service which are not executing commands but running independently and waiting for the job.START_NOT_STICKY
: It will not restart the service and it is useful for the services which will run periodically. The service will restart only when there are a pending startService()
calls. It’s the best option to avoid running a service in case if it is not necessary.START_REDELIVER_INTENT
: It’s same as STAR_STICKY
and it recreates the service, call onStartCommand()
with last intent that was delivered to the service.var arr = new Array();
$('li').each(function() {
arr.push(this.innerHTML);
})
This maybe too late but No one provided a clear explanation of how the algorithm works
The idea of Dijkstra is simple, let me show this with the following pseudocode.
Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.
At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.
The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.
If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.
Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.
Credits to Lars Vogel
#include <stdio.h>
#include <string.h>
int main ()
{
char buf[] ="abc/qwe/ccd";
int i = 0;
char *p = strtok (buf, "/");
char *array[3];
while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, "/");
}
for (i = 0; i < 3; ++i)
printf("%s\n", array[i]);
return 0;
}
jXPanel6.setVisible(jXPanel6.isVisible());
or in your form:
jXPanel6.setVisible(jXPanel6.isVisible()?true:false);
That is a standard way to define template functions. I think there are three methods I read for defining templates. Or probably 4. Each with pros and cons.
Define in class definition. I don't like this at all because I think class definitions are strictly for reference and should be easy to read. However it is much less tricky to define templates in class than outside. And not all template declarations are on the same level of complexity. This method also makes the template a true template.
Define the template in the same header, but outside of the class. This is my preferred way most of the times. It keeps your class definition tidy, the template remains a true template. It however requires full template naming which can be tricky. Also, your code is available to all. But if you need your code to be inline this is the only way. You can also accomplish this by creating a .INL file at the end of your class definitions.
Include the header.h and implementation.CPP into your main.CPP. I think that's how its done. You won't have to prepare any pre instantiations, it will behave like a true template. The problem I have with it is that it is not natural. We don't normally include and expect to include source files. I guess since you included the source file, the template functions can be inlined.
This last method, which was the posted way, is defining the templates in a source file, just like number 3; but instead of including the source file, we pre instantiate the templates to ones we will need. I have no problem with this method and it comes in handy sometimes. We have one big code, it cannot benefit from being inlined so just put it in a CPP file. And if we know common instantiations and we can predefine them. This saves us from writing basically the same thing 5, 10 times. This method has the benefit of keeping our code proprietary. But I don't recommend putting tiny, regularly used functions in CPP files. As this will reduce the performance of your library.
Note, I am not aware of the consequences of a bloated obj file.
Little sum up for searching by row:
This can be useful if you don't know the column values ??or if columns have non-numeric values
if u want get index number as integer u can also do:
item = df[4:5].index.item()
print(item)
4
it also works in numpy / list:
numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]
in [x] u pick number in range [4:7], for example if u want 6:
numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6
for DataFrame:
df[4:7]
A B
4 5 0.894525
5 6 0.978174
6 7 0.859449
or:
df[(df.index>=4) & (df.index<7)]
A B
4 5 0.894525
5 6 0.978174
6 7 0.859449
Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.
After importing PDFKit, you should initialize a PDFView
with a local or a remote URL and display it in your view.
if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
let pdfView = PDFView(frame: view.frame)
pdfView.document = PDFDocument(url: url)
view.addSubview(pdfView)
}
Read more about PDFKit in the Apple Developer documentation.
For some git-commands you can specify --verbose
,
git 'command' --verbose
or
git 'command' -v
.
Make sure the switch is after the actual git command. Otherwise - it won't work!
Also useful:
git 'command' --dry-run
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
Here is an easy way to get only unique raw values from array. If you convert the array to Set and after this, do the conversion from Set to array. This conversion works only for raw values, for objects in the array it is not valid. Try it by yourself.
let myObj1 = {
name: "Dany",
age: 35,
address: "str. My street N5"
}
let myObj2 = {
name: "Dany",
age: 35,
address: "str. My street N5"
}
var myArray = [55, 44, 65, myObj1, 44, myObj2, 15, 25, 65, 30];
console.log(myArray);
var mySet = new Set(myArray);
console.log(mySet);
console.log(mySet.size === myArray.length);// !! The size differs because Set has only unique items
let uniqueArray = [...mySet];
console.log(uniqueArray);
// Here you will see your new array have only unique elements with raw
// values. The objects are not filtered as unique values by Set.
// Try it by yourself.
Just call these method to finish current activity or to go back by onBackPressed
finish();
OR
onBackPressed();
If visible menu
menu.findItem(R.id.id_name).setVisible(true);
If hide menu
menu.findItem(R.id.id_name).setVisible(false);
Implement Comparable interface to Fruit.
public class Fruit implements Comparable<Fruit> {
It implements the method
@Override
public int compareTo(Fruit fruit) {
//write code here for compare name
}
Then do call sort method
Collections.sort(fruitList);
I also used bcp and found a couple other helpful posts that would benefit others if finding this thread
Don't use VARCHAR(MAX)
as your @sql
or @cmd
variable for xp_cmdshell; you will get and error
Msg 214, Level 16, State 201, Procedure xp_cmdshell, Line 1 Procedure expects parameter 'command_string' of type 'varchar'.
http://www.sqlservercentral.com/Forums/Topic1071530-338-1.aspx
Use NULLIF
to get blanks for the csv file instead of a NUL
(viewable in hex editor, or notepad++). I used that in the SELECT
statement for bcp
How to make Microsoft BCP export empty string instead of a NUL char?
You may checkout this library for the same purpose also:
http://angular-route-segment.com
It looks like what you are looking for, and it is much simpler to use than ui-router. From the demo site:
JS:
$routeSegmentProvider.
when('/section1', 's1.home').
when('/section1/:id', 's1.itemInfo.overview').
when('/section2', 's2').
segment('s1', {
templateUrl: 'templates/section1.html',
controller: MainCtrl}).
within().
segment('home', {
templateUrl: 'templates/section1/home.html'}).
segment('itemInfo', {
templateUrl: 'templates/section1/item.html',
controller: Section1ItemCtrl,
dependencies: ['id']}).
within().
segment('overview', {
templateUrl: 'templates/section1/item/overview.html'}).
Top-level HTML:
<ul>
<li ng-class="{active: $routeSegment.startsWith('s1')}">
<a href="/section1">Section 1</a>
</li>
<li ng-class="{active: $routeSegment.startsWith('s2')}">
<a href="/section2">Section 2</a>
</li>
</ul>
<div id="contents" app-view-segment="0"></div>
Nested HTML:
<h4>Section 1</h4>
Section 1 contents.
<div app-view-segment="1"></div>
Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth #maybe not, because I cannot apply cmd "cd auth" if I do so.
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
#run
sudo sendmailconfig
Change localhost:8080 to localhost:3306.
Success!
I had similar problems and tried re-installing several times, but no joy. I was looking at installing individual packages from the ISO and all of the fiddling around - not happy at all.
I finally got it to "install" by simply selecting "repair" rather than "uninstall" in control panel / programs. It took quite a while to do the "repair" though. In the end it is installed and working.
This worked for me. It may help others - easier to try than many other options, anyway.
Hosting asp.net 4.5/4.5.1 Web application on Local IIS 1)Be Sure IIS Installation before Visual Installation Installataion then aspnet_regiis will already registerd with IIS
If Not Install IIS and then Register aspnet_regiis with IIS by cmd Editor
For VS2012 and 32 bit OS Run Below code on command editor :
1)Install IIS First & then
2)
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
C:\Windows\Microsoft.NET\Framework\v4.0.30319> aspnet_regiis -i
For VS2012 and 64 bit OS Below code on command editor:
1)Install IIS First & then
2)
cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
C:\Windows\Microsoft.NET\Framework64\v4.0.30319> aspnet_regiis -i
BY Following Above Steps Current Version of VS2012 registered with IIS Hosting (VS2012 Web APP)
Create VS2012 Web Application(WebForm/MVC) then Build Application Right Click On WebApplication(WebForm/MVC) go to 'Properties' Click On 'Web' Tab on then 'Use Local IIS Web Server' Then Uncheck 'Use IIS Express' (If Visul Studio 2013 Select 'Local IIS' from Dropdown) Provide Project Url like "http://localhost/MvcDemoApp" Then Click On 'Create Virtual Directory' Button Then Open IIS by Prssing 'Window + R' Run Command and type 'inetmgr' and 'Enter' (or 'OK' Button) Then Expand 'Sites->Default Web Site' you Hosted Successfully. If Still Gets any Server Error like 'The resource cannot be found.' Then Include following code in web.config
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
And Run Application
If still problem occurs Check application pool by : In iis Right click on application->Manage Application->Advanced setting->General. you see the application pool. then close advance setting window. click on 'Application Pools' you will see the all application pools in middle window. Right click on application pool in which application hosted(DefaultAppPool). click 'Basic Setting' -> Change .Net FrameWork Version to->.Net FrameWork v4.0.30349
I know this is a pretty old question but this was my solution that helped with visualizing the table so you can create a class structure. This is also using the HTML Agility Pack
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
var table = doc.DocumentNode.SelectSingleNode("//table");
var tableRows = table.SelectNodes("tr");
var columns = tableRows[0].SelectNodes("th/text()");
for (int i = 1; i < tableRows.Count; i++)
{
for (int e = 0; e < columns.Count; e++)
{
var value = tableRows[i].SelectSingleNode($"td[{e + 1}]");
Console.Write(columns[e].InnerText + ":" + value.InnerText);
}
Console.WriteLine();
}
In this specific context, your example doesn't make a lot of sense.
When a Being picks up an Item, the item retains an individual existence. It doesn't disappear because it's been picked up. It still exists, but it's (a) in the same location as the Being, and (b) no longer eligible to be picked up. While it's had a state change, it still exists.
There is a two-way association between Being and Item. The Being has the Item in a collection. The Item is associated with a Being.
When an Item is picked up by a Being, two things have to happen.
The Being how adds the Item in some set
of items. Your bag
attribute, for example, could be such a set
. [A list
is a poor choice -- does order matter in the bag?]
The Item's location changes from where it used to be to the Being's location. There are probably two classes os Items - those with an independent sense of location (because they move around by themselves) and items that have to delegate location to the Being or Place where they're sitting.
Under no circumstances does any Python object ever need to get deleted. If an item is "destroyed", then it's not in a Being's bag. It's not in a location.
player.bag.remove(cat)
Is all that's required to let the cat out of the bag. Since the cat is not used anywhere else, it will both exist as "used" memory and not exist because nothing in your program can access it. It will quietly vanish from memory when some quantum event occurs and memory references are garbage collected.
On the other hand,
here.add( cat )
player.bag.remove(cat)
Will put the cat in the current location. The cat continues to exist, and will not be put out with the garbage.
Place your scripts in this order:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
SQL is a standard and there are many database vendors like Microsoft,Oracle who implements this standard using their own proprietary language.
Microsoft uses T-SQL to implement SQL standard to interact with data whereas oracle uses PL/SQL.
You probably have not installed make. Restart the cygwin installer, search for make, select it and it should be installed. By default the cygwin installer does not install everything for what I remember.
A workaround is to add the domain names you use as "subjectAltName" (X509v3 Subject Alternative Name). This can be done by changing your OpenSSL configuration (/etc/ssl/openssl.cnf
on Linux) and modify the v3_req
section to look like this:
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = myserver.net
DNS.2 = sub1.myserver.net
With this in place, not forget to use the -extensions v3_req
switch when generating your new certificate. (see also How can I generate a self-signed certificate with SubjectAltName using OpenSSL?)
You have basically two options:
You merge. That is actually quite simple, and a perfectly local operation:
git checkout b1
git merge master
# repeat for b2 and b3
This leaves the history exactly as it happened: You forked from master, you made changes to all branches, and finally you incorporated the changes from master into all three branches.
git
can handle this situation really well, it is designed for merges happening in all directions, at the same time. You can trust it be able to get all threads together correctly. It simply does not care whether branch b1
merges master
, or master
merges b1
, the merge commit looks all the same to git. The only difference is, which branch ends up pointing to this merge commit.
You rebase. People with an SVN, or similar background find this more intuitive. The commands are analogue to the merge case:
git checkout b1
git rebase master
# repeat for b2 and b3
People like this approach because it retains a linear history in all branches. However, this linear history is a lie, and you should be aware that it is. Consider this commit graph:
A --- B --- C --- D <-- master
\
\-- E --- F --- G <-- b1
The merge results in the true history:
A --- B --- C --- D <-- master
\ \
\-- E --- F --- G +-- H <-- b1
The rebase, however, gives you this history:
A --- B --- C --- D <-- master
\
\-- E' --- F' --- G' <-- b1
The point is, that the commits E'
, F'
, and G'
never truly existed, and have likely never been tested. They may not even compile. It is actually quite easy to create nonsensical commits via a rebase, especially when the changes in master
are important to the development in b1
.
The consequence of this may be, that you can't distinguish which of the three commits E
, F
, and G
actually introduced a regression, diminishing the value of git bisect
.
I am not saying that you shouldn't use git rebase
. It has its uses. But whenever you do use it, you need to be aware of the fact that you are lying about history. And you should at least compile test the new commits.
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
In MySQL query browser go to Tools tab>MySQL Administrator > User Administration and then give the privileges to user.
You can also write a little wrapper function like this
const onEnter = (event, callback) => event.key === 'Enter' && callback()
Then consume it on your inputs
<input
type="text"
placeholder="Title of todo"
onChange={e => setName(e.target.value)}
onKeyPress={e => onEnter(e, addItem)}/>
There is a comment by @afr0 asking how to filter on folders..
There is two ways using the GetDirectoryReference
or looping through a containers blobs and checking the type. The code below is in C#
CloudBlobContainer container = blobClient.GetContainerReference("photos");
//Method 1. grab a folder reference directly from the container
CloudBlobDirectory folder = container.GetDirectoryReference("directoryName");
//Method 2. Loop over container and grab folders.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof(CloudBlobDirectory))
{
// we know this is a sub directory now
CloudBlobDirectory subFolder = (CloudBlobDirectory)item;
Console.WriteLine("Directory: {0}", subFolder.Uri);
}
}
read this for more in depth coverage: http://www.codeproject.com/Articles/297052/Azure-Storage-Blobs-Service-Working-with-Directori
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
How about something like this:
var MyNamespace = {
convertToBoolean: function (value) {
//VALIDATE INPUT
if (typeof value === 'undefined' || value === null) return false;
//DETERMINE BOOLEAN VALUE FROM STRING
if (typeof value === 'string') {
switch (value.toLowerCase()) {
case 'true':
case 'yes':
case '1':
return true;
case 'false':
case 'no':
case '0':
return false;
}
}
//RETURN DEFAULT HANDLER
return Boolean(value);
}
};
Then you can use it like this:
MyNamespace.convertToBoolean('true') //true
MyNamespace.convertToBoolean('no') //false
MyNamespace.convertToBoolean('1') //true
MyNamespace.convertToBoolean(0) //false
I have not tested it for performance, but converting from type to type should not happen too often otherwise you open your app up to instability big time!
this will sort it for you
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but1=(Button)findViewById(R.id.button1);
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent int1= new Intent(MainActivity.this,xxactivity.class);
startActivity(int1);
}
});
}
You just need to amend the xxactivity to the name of your second activity
Try adding this in your vhost config:
RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
Nowdays that's possible with native JS
var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs
var comment = document.getElementsByClassName("button");_x000D_
_x000D_
function showComment() {_x000D_
var place = document.getElementById('textfield');_x000D_
var commentBox = document.createElement('textarea');_x000D_
place.appendChild(commentBox);_x000D_
}_x000D_
_x000D_
for (var i in comment) {_x000D_
comment[i].onclick = function() {_x000D_
showComment();_x000D_
};_x000D_
}
_x000D_
<input type="button" class="button" value="1">_x000D_
<input type="button" class="button" value="2">_x000D_
<div id="textfield"></div>
_x000D_
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
Comprehensions are usually faster, and this has the advantage of not editing mydict
during the iteration:
mydict = dict((k, v if v else '') for k, v in mydict.items())
cmd >>file.txt 2>&1
Bash executes the redirects from left to right as follows:
>>file.txt
: Open file.txt
in append mode and redirect stdout
there.2>&1
: Redirect stderr
to "where stdout
is currently going". In this case, that is a file opened in append mode. In other words, the &1
reuses the file descriptor which stdout
currently uses.Try this:
export CURLNAME="john:@31&3*J"
curl -d -u "${CURLNAME}" https://www.example.com
Try the following code:
//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
System.out.println(e.getText());
}
It will returns with the whole content of the <li>
tags, like:
<a class="extra">Vše</a> (950)</li>
But you can easily get the number now from it, for example by using split()
and/or substring()
.
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
If you want insert all data from one table to another table there is a very simply sql
INSERT INTO destinationTable (SELECT * FROM sourceDbName.SourceTableName);
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
I'm not sure that I understand what you mean by "rights of ownership".
If User B owns a stored procedure, User B can grant User A permission to run the stored procedure
GRANT EXECUTE ON b.procedure_name TO a
User A would then call the procedure using the fully qualified name, i.e.
BEGIN
b.procedure_name( <<list of parameters>> );
END;
Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name.
CREATE SYNONYM procedure_name FOR b.procedure_name;
BEGIN
procedure_name( <<list of parameters>> );
END;
C# doesn't support enumerated strings, but for most situations you can use a List or Dictionary to get the desired effect.
E.g. To print pass/fail results:
List<string> PassFail = new List<string> { "FAIL", "PASS" };
bool result = true;
Console.WriteLine("Test1: " + PassFail[result.GetHashCode()]);
Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.
UPDATE:
onActivityCreated()
is deprecated from API Level 28.
onCreate():
The onCreate()
method in a Fragment
is called after the Activity
's onAttachFragment()
but before that Fragment
's onCreateView()
.
In this method, you can assign variables, get Intent
extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity
's onCreate()
is not finished, and so trying to access the View hierarchy here may result in a crash.
onCreateView():
After the onCreate()
is called (in the Fragment
), the Fragment
's onCreateView()
is called. You can assign your View
variables and do any graphical initialisations. You are expected to return a View
from this method, and this is the main UI view, but if your Fragment
does not use any layouts or graphics, you can return null
(happens by default if you don't override).
onActivityCreated():
As the name states, this is called after the Activity
's onCreate()
has completed. It is called after onCreateView()
, and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.
To sum up...
... they are all called in the Fragment
but are called at different times.
The onCreate()
is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View
variables you want to use in onCreateView()
. Afterwards, use onActivityCreated()
to do any final initialisations you want to do once everything has completed.
If you want to view the official Android documentation, it can be found here:
There are also some slightly different, but less developed questions/answers here on Stack Overflow:
ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go
This is the way I do it:
num = 123.456
split_num = str(num).split('.')
int_part = int(split_num[0])
decimal_part = int(split_num[1])
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
PHP - curl:
$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
PHP - POST in WordPress:
$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$username:$password")
)
));
...
You need to ensure that C:\Python35\Sripts
is in your system path. Follow the top answer instructions here to do that:
You run the command in windows command prompt, not in the python interpreter that you have open.
Press:
Win + R
Type CMD
in the run window which has opened
Type pip install openpyxl
in windows command prompt.
I have opened a (trivial) bug for this at m2e. Vote for it if you want the warning message to be gone for good...
P (Polynomial Time): As name itself suggests, these are the problems which can be solved in polynomial time.
NP (Non-deterministic-polynomial Time): These are the decision problems which can be verified in polynomial time. That means, if I claim that there is a polynomial time solution for a particular problem, you ask me to prove it. Then, I will give you a proof which you can easily verify in polynomial time. These kind of problems are called NP problems. Note that, here we are not talking about whether there is a polynomial time solution for this problem or not. But we are talking about verifying the solution to a given problem in polynomial time.
NP-Hard: These are at least as hard as the hardest problems in NP. If we can solve these problems in polynomial time, we can solve any NP problem that can possibly exist. Note that these problems are not necessarily NP problems. That means, we may/may-not verify the solution to these problems in polynomial time.
NP-Complete: These are the problems which are both NP and NP-Hard. That means, if we can solve these problems, we can solve any other NP problem and the solutions to these problems can be verified in polynomial time.
"Sleep" state connections are most often created by code that maintains persistent connections to the database.
This could include either connection pools created by application frameworks, or client-side database administration tools.
As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.
(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
In most browsers, you need the Range
and Selection
objects. You specify each of the selection boundaries as a node and an offset within that node. For example, to set the caret to the fifth character of the second line of text, you'd do the following:
function setCaret() {
var el = document.getElementById("editable")
var range = document.createRange()
var sel = window.getSelection()
range.setStart(el.childNodes[2], 5)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
}
_x000D_
<div id="editable" contenteditable="true">
text text text<br>text text text<br>text text text<br>
</div>
<button id="button" onclick="setCaret()">focus</button>
_x000D_
IE < 9 works completely differently. If you need to support these browsers, you'll need different code.
jsFiddle example: http://jsfiddle.net/timdown/vXnCM/
Sounds like you want a view instead of altering actual table data.
Coalesce(NullIf(rtrim(Address.Country),''),'United States')
This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.
Using ints.sum()
has two problems:
customerssalary
, not ints
Sum()
, not sum()
.Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average()
which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double
:
double average = ((double) sum) / customerssalary.Length;
Use the astype
method.
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> x.astype(int)
array([[1, 2],
[1, 2]])
As you say, ordinal is a bit risky. Consider for example:
public enum Boolean {
TRUE, FALSE
}
public class BooleanTest {
@Test
public void testEnum() {
assertEquals(0, Boolean.TRUE.ordinal());
assertEquals(1, Boolean.FALSE.ordinal());
}
}
If you stored this as ordinals, you might have rows like:
> SELECT STATEMENT, TRUTH FROM CALL_MY_BLUFF
"Alice is a boy" 1
"Graham is a boy" 0
But what happens if you updated Boolean?
public enum Boolean {
TRUE, FILE_NOT_FOUND, FALSE
}
This means all your lies will become misinterpreted as 'file-not-found'
Better to just use a string representation
If for some reason you have null values you can use the F function like this:
from django.db.models import F
Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))
So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values
You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE
{% if variable is defined %}
works to check if something is undefined.
You can get away with using {% if not var1 %}
if you default your variables to False eg
class MainHandler(BaseHandler):
def get(self):
var1 = self.request.get('var1', False)
I found this works pretty well for IP addresses. It validates like the top answer but it also makes sure the ip is isolated so no text or more numbers/decimals are after or before the ip.
(?<!\S)(?:(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b|.\b){7}(?!\S)
if you have array that looks like this -
data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]
and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -
data_hash = Hash[data.map { |key| [key.shift, key] }]
#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}
You could return to the previous page by using ViewBag.ReturnUrl
property.
You can create an autofield. Here is the documentation for the same
Please remember Django won't allow to have more than one AutoField in a model, In your model you already have one for your primary key (which is default). So you'll have to override model's save method and will probably fetch the last inserted record from the table and accordingly increment the counter and add the new record.
Please make that code thread safe because in case of multiple requests you might end up trying to insert same value for different new records.
Yes you can. I've used it with Word and PowerPoint. You will need Office 2010 client apps and SharePoint 2010 foundation at least. You must also allow editing without checking out on the document library.
It's quite cool, you can mark regions as 'locked' so no-one can change them and you can see what other people have changed every time you save your changes to the server. You also get to see who's working on the document from the Office app. The merging happens on SharePoint 2010.
In Excel 2003 you should be able to create a formatting rule like:
=A1<>""
and then drag/copy this to other cells as needed.
If that doesn't work, try =Len(A1)>0
.
If there may be spaces in the cell which you will consider blank, then do:
=Len(Trim(A1))>0
Let me know if you can't get any of these to work. I have an old machine running XP and Office 2003, I can fire it up to troubleshoot if needed.
In any sql server version you could use a variable for the total of all grades like this:
declare @countOfAll decimal(18, 4)
select @countOfAll = COUNT(*) from Grades
select
Grade, COUNT(*) / @countOfAll * 100
from Grades
group by Grade
Using the example you gave:
<form>
<input type="text" name="field1" /><!-- Put your cursor in this field and press Enter -->
<input type="submit" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
<input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>
If you click on "Previous Page", only the value of "prev" will be submitted. If you click on "Next Page" only the value of "next" will be submitted.
If however, you press Enter somewhere on the form, neither "prev" nor "next" will be submitted.
So using pseudocode you could do the following:
If "prev" submitted then
Previous Page was click
Else If "next" submitted then
Next Page was click
Else
No button was click
a_list = []
b_list = []
for i in range(1,100):
a_list.append(random.randint(1,100))
for i in range(1,100):
a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]
=ADDRESS(ROW(),COLUMN())
=ADDRESS(ROW(),COLUMN(),1)
=ADDRESS(ROW(),COLUMN(),2)
=ADDRESS(ROW(),COLUMN(),3)
=ADDRESS(ROW(),COLUMN(),4)
git branch --set-upstream-to=origin/master<branch_name>
So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d
import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}
The command
pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06
where pd.Panel(d)[item] yields a dataframe
pd.Panel(d)['SPX Index']
2014-11-03 2014-11-04 2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33
You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.
pd.Panel(d).to_frame().reset_index()
major minor RAY Index SPX Index
PX_LAST 2014-11-03 1199.460 2017.81
PX_LAST 2014-11-04 1195.323 2012.10
PX_LAST 2014-11-05 1200.936 2023.57
PX_LAST 2014-11-06 1206.061 2031.21
PX_OPEN 2014-11-03 1200.140 2018.21
PX_OPEN 2014-11-04 1197.690 2015.81
PX_OPEN 2014-11-05 1195.320 2015.29
PX_OPEN 2014-11-06 1200.620 2023.33
Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html
Just as an example
pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major minor 2014-11-03 2014-11-04 2014-11-05 2014-11-06
RAY Index PX_LAST 1199.46 1195.323 1200.936 1206.061
RAY Index PX_OPEN 1200.14 1197.690 1195.320 1200.620
SPX Index PX_LAST 2017.81 2012.100 2023.570 2031.210
SPX Index PX_OPEN 2018.21 2015.810 2015.290 2023.330
Hope this helps.
You can also use debug(function)
, to break when function
is called.
Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.
Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.
This is the so-called simple way in PHP.
To well understand the behaviour, you can run this code:
#include <iostream>
class MyClass
{
public:
MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }
};
MyClass my_function()
{
std::cout << "run my_function()" << std::endl;
MyClass a;
std::cout << "my_function is going to return a..." << std::endl;
return a;
}
int main(int argc, char** argv)
{
MyClass b = my_function();
MyClass c;
c = my_function();
return 0;
}
The output is the following:
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
Note that this example was provided in C++03 context, it could be improved for C++ >= 11
You lookup the value of the data with findData()
and then use setCurrentIndex()
QComboBox* combo = new QComboBox;
combo->addItem("100",100.0); // 2nd parameter can be any Qt type
combo->addItem .....
float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
combo->setCurrentIndex(index);
}
It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760
To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.
You could use the random.sample
function from the standard library to select k elements from a population:
import random
random.sample(range(low, high), n)
In case of a rather large range of possible numbers, you could use itertools.islice
with an infinite random generator:
import itertools
import random
def random_gen(low, high):
while True:
yield random.randrange(low, high)
gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10)) # Take first 10 random elements
After the question update it is now clear that you need n distinct (unique) numbers.
import itertools
import random
def random_gen(low, high):
while True:
yield random.randrange(low, high)
gen = random_gen(1, 100)
items = set()
# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
items.add(x)
You can use WScript.ScriptFullName which will return the full path of the executing script.
You can then use string manipulation (jscript example) :
scriptdir = WScript.ScriptFullName.substring(0,WScript.ScriptFullName.lastIndexOf(WScript.ScriptName)-1)
Or get help from FileSystemObject, (vbscript example) :
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
This may be because you havent set noAuth=true in mongodb.conf
# Turn on/off security. Off is currently the default
noauth = true
#auth = true
After setting this restart the service using
service mongod restart
This code is equivalent, shorter, and more readable:
int8_t strcmp (const uint8_t* s1, const uint8_t* s2)
{
while( (*s1!='\0') && (*s1==*s2) ){
s1++;
s2++;
}
return (int8_t)*s1 - (int8_t)*s2;
}
We only need to test for end of s1, because if we reach the end of s2 before end of s1, the loop will terminate (since *s2 != *s1).
The return expression calculates the correct value in every case, provided we are only using 7-bit (pure ASCII) characters. Careful thought is needed to produce correct code for 8-bit characters, because of the risk of integer overflow.
I faced same issue for chrome build 61.0.3163.100
on MacOs Sierra with localhost
as server. Chrome started logging this message when I changed network speed configuration to 3G fast/ 3G slow and again back to Online.
Fix: When I tried selecting Offline mode and again Online mode, the logging issue disappeared. (This fix may no work on some devices or versions)
Update on 30th Jan 2018
I updated google chrome to Version 64.0.3282.119 (Official Build) (64-bit)
, it seems this bug is fixed now.
I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
Most likely to be npm registry cannot be reached by npm. Check npm proxy configuration
I had exactly the same issue on Windows Server 2008 R2. I suspected Internet Explorer's Enhanced Security Configuration at first but after turning that off with no success the issue turned out to be that npm was not configured to use my corporate proxy connection to the internet.
It turns out that npm does not use the proxy settings in effect via Internet Options > Connections tab > LAN settings where the server is set to 'Automatically detect settings'. Being set to automatically detect settings does not guarantee that a proxy is indeed being used, it just means that Windows will automatically configure proxy settings for Internet Explorer if it finds a special'wpad.dat' file at http://wpad.[yourdomain.com]/wpad.dat.
You can test whether a wpad.dat file is in use in your organisation by typing the following into a web browser.
http://wpad.[yourcompany.domain]/wpad.dat
If no file is available then it is likely you are not using an organization-wide proxy. If one does get returned to the browser then...
Toward the bottom of this file, you should see a line saying
PROXY <host:port>;
It might be repeated if you have multiple proxies available. The host and port are needed in order to tell npm to use the proxy settings like so:
npm config set proxy http://[host]:[port]
and
npm config set https-proxy http://[host]:[port]
For example if your proxy is at my.proxy.com on port 8080 then the npm commands would be:
npm config set proxy http://my.proxy.com:8080
npm config set https-proxy http://my.proxy.com:8080
Once I had told npm which proxy to use all started working in I was able to run the install commands without a problem.
Thanks to the following post for help with the wpad file discovery.
Before answering when to use which one, a little background:
edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.
JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.
In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:
myJSON = {"age" : 12,
"name" : "Danielle"}
The parser doesn't need to be intelligent enough to realise that 12
represents a number, (and Danielle
is a string like any other). So in javascript we can do:
anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False
In XML we'd have to do something like the following:
<person>
<age>12</age>
<name>Danielle</name>
</person>
(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:
myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True
Actually, a good parser might well type the age
for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name
. It might be more intuitive to form the XML like this:
<person name="Danielle" age="12" />
But we'd still have to do map lookups to access our data:
myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");
EDIT: Original:
In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).
This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.
If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.
As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.
Here's a C# method to return the angle (0-360) anticlockwise from the horizontal for a point on a circle.
public static double GetAngle(Point centre, Point point1)
{
// Thanks to Dave Hill
// Turn into a vector (from the origin)
double x = point1.X - centre.X;
double y = point1.Y - centre.Y;
// Dot product u dot v = mag u * mag v * cos theta
// Therefore theta = cos -1 ((u dot v) / (mag u * mag v))
// Horizontal v = (1, 0)
// therefore theta = cos -1 (u.x / mag u)
// nb, there are 2 possible angles and if u.y is positive then angle is in first quadrant, negative then second quadrant
double magnitude = Math.Sqrt(x * x + y * y);
double angle = 0;
if(magnitude > 0)
angle = Math.Acos(x / magnitude);
angle = angle * 180 / Math.PI;
if (y < 0)
angle = 360 - angle;
return angle;
}
Cheers, Paul
In my case Right Click on Virtual Directory and Select "Convert To Application" worked!
You can also do something much shorter:
SELECT FORMAT(2.3332232,'N2')
Use this
Facebook - "com.facebook.katana"
Twitter - "com.twitter.android"
Instagram - "com.instagram.android"
Pinterest - "com.pinterest"
SharingToSocialMedia("com.facebook.katana")
public void SharingToSocialMedia(String application) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, bmpUri);
boolean installed = checkAppInstall(application);
if (installed) {
intent.setPackage(application);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Installed application first", Toast.LENGTH_LONG).show();
}
}
private boolean checkAppInstall(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA
class ClassA {
public function getName() {
echo $this->name;
}
}
class ClassB extends ClassA {
public function getName() {
parent::getName();
}
}
Without inheritance or an instance method, you'd need ClassA to have a static method
class ClassA {
public static function getName() {
echo "Rawkode";
}
}
--- other file ---
echo ClassA::getName();
If you're just looking to call the method from an instance of the class:
class ClassA {
public function getName() {
echo "Rawkode";
}
}
--- other file ---
$a = new ClassA();
echo $a->getName();
Regardless of the solution you choose, require 'ClassA.php
is needed.
There is a tool localfont.com to help you download all font variants. It as well generates the corresponding CSS for implementation. deprecated
localfont is down. Instead, as Damir suggests, you can use google-webfonts-helper
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
In plt.colorbar(z1_plot,cax=ax1)
, use ax=
instead of cax=
, i.e. plt.colorbar(z1_plot,ax=ax1)
Or on an actual device you can go to Settings -> Mobile Networks -> Preferred network types and chose the slowest available... Of course this is very limited, but for some test- purposes it might be enough.
You could add
cd /some/directory/somewhere/named/Foo
to your .bashrc
file (or .profile
or whatever you call it) at the other host. That way, no matter what you do or where you ssh
from, whenever you log onto that server, it will cd
to the proper directory for you, and all you have to do is use ssh
like normal.
Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".
The message "DL is deprecated, please use Fiddle" is not an error; it's only a warning.
Solution:
You can ignore this in 3 simple steps.
Step 1. Goto C:\RailsInstaller\Ruby2.1.0\lib\ruby\2.1.0
Step 2. Then find dl.rb and open the file with any online editors like Aptana,sublime text etc
Step 3. Comment the line 8 with '#' ie # warn "DL is deprecated, please use Fiddle" .
That's it, Thank you.
I was having a similar issue. Things worked in IE6, Firefox, and IE8 running in IE7 compatibility mode; but not in 'normal' IE8. My solution was to put this code in the header
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
As to why jquery isn't working in IE8 I'm unclear.
I was facing the same issue with jenkins ssh slave 'jenkinsci/ssh-slave'. However, my case was a bit complicated because it was necessary to pass an argument which contained spaces. I've managed to do it like below (entrypoint in dockerfile is in exec form):
command: ["some argument with space which should be treated as one"]
this nsdate
used different format:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];
NSDate *parsed = [inFormat dateFromString:dateString];
For some reason config.timeout doesn't work for me. I used this approach:
let cancelRequest = $q.defer();_x000D_
let cancelPromise = cancelRequest.promise;_x000D_
_x000D_
let httpPromise = $http.get(...);_x000D_
_x000D_
$q.race({ cancelPromise, httpPromise })_x000D_
.then(function (result) {_x000D_
..._x000D_
});
_x000D_
And cancelRequest.resolve() to cancel. Actually it doesn't not cancel a request but you don't get unnecessary response at least.
Hope this helps.
There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.
You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:
Top level classes:
1 public class
0 private class
any number of default/protected classes
Inner classes:
any number of inner classes with any visibility (default, private, protected, public)
Please correct me if I am wrong.
I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.
Most of my work is done with database connectivity which means that my classes all have a unique identifier from the database. I always use the ID from the database to generate the hashcode.
// Unique ID from database
private int _id;
...
{
return _id.GetHashCode();
}
I think this will do:
$('#'+div_id+' .widget-head > span').text("new dialog title");
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser
which is doing most of the work. Where he puts req.body.name
, I believe he/she is using body-parser
to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring
which is a built-in Node module. See the answers in the link below for an example of how to use querystring
.
It might help to look at this answer, which is very similar to your quest.
Comparision:
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:
if(userProfile != null)
{
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
}
or shorter version:
if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
//your code
}
If the component is an EJB, then, there shouldn't be a problem injecting an EM.
But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.
This is probably the problem.
You could just use parameter expansion:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
So try this:
var=${DEPLOY_ENV:-default_value}
There's also the ${parameter-word} form, which substitutes the default value only when parameter is unset (but not when it's null).
To demonstrate the difference between the two:
$ unset DEPLOY_ENV
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' 'default_value'
$ DEPLOY_ENV=
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' ''
In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL
:
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
base64String]];
return [NSData dataWithContentsOfURL:URL];
Here is a solution with requests Response class. It is cleaner IMHO.
from unittest.mock import patch
from requests.models import Response
def mocked_request_get(*args, **kwargs):
response_content = None
request_url = kwargs.get('url', None)
if request_url == 'aurl':
response_content = json.dumps('a response')
elif request_url == 'burl':
response_content = json.dumps('b response')
elif request_url == 'curl':
response_content = json.dumps('c response')
response = Response()
response.status_code = 200
response._content = str.encode(response_content)
return response
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
response = call_your_view()
assert ...
Here's a possibile solution (in Python):
Let's say you have a notebook with a file name, call it Notebook.ipynb. You are currently working in that notebook, and want to access other folders and files around it. Here's it's path:
import os
notebook_path = os.path.abspath("Notebook.ipynb")
In other words, just use the os module, and get the absolute path of your notebook (it's a file, too!). From there, use the os module and your path to navigate.
For example, if your train.csv is in a folder called 'Datasets', and the notebook is sitting right next to that folder, you could get the data like this:
train_csv = os.path.join(os.path.dirname(notebook_path), "Datasets/train.csv")
with open(train_csv) as file:
#....etc
The takeaway is that the notebook has a file name, and as long as your language supports pathname manipulations (e.g. the os module in Python) you can likely use the notebook filename.
Lastly, the reason your code fails is probably because you're either trying to access local files (like your Mac's 'Downloads' folder) when you're working in an online Notebook (like Kaggle, which hosts your environment for you, online and away from your Mac), or you moved or deleted something in that path. This is what the os module in Python is meant to do; it will find the file's path whether it's on your Mac or in a Kaggle server.
If you are using Lotus Notes V9.X, it is better to drag the mail to desktop as .eml and then attach it to the mail. Safest way so far.
Try this only if you are ok with uninstalling python.
I uninstalled python using
brew uninstall python
then later installed using
brew install python
then it worked!
You have to set d[a]
to either an associative array, or an object:
d[a] = [];
d[a] = {};
Without setting, this is what's happening:
d[a] == undefined
, so you're doing undefined['greeting']=b;
and by definition, undefined has no properties. Thus, the error you received.
In window 10 there is already a path present in env as C:\>ProgramData\Oracle\Java\javapath
that holds symlinks to the executables.
When I install a new version and remove that from my environment variable, my all project start showing it.
I am using eclipse oxygen in window 10
To resolve it:-
I just remove path C:\>ProgramData\Oracle\Java\javapath
from environment variable and added new env as JAVA_HOME and %JAVA_HOME%/bin in path
I reinstall the jdk with admin privileges (delete the previous JRE folder)
My issue is resolved :) Hope it will help you :)
Repl Command to find the Nodejs Version
$node
>process.version
`v8.x`
I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:
public static string DescriptionAttr<T>(this T source)
{
FieldInfo fi = source.GetType().GetField(source.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) return attributes[0].Description;
else return source.ToString();
}
Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:
string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();
I needed a way to do this in an AJAX return, so I wrote this piece:
<p id="num_results">Number of results: <span></span></p>
<div id="results"></div>
<script type="text/javascript">
$(function(){
ajax();
})
//Function that makes Ajax call out to receive search results
var ajax = function() {
//Setup Ajax
$.ajax({
url: '/path/to/url', //URL to load
type: 'GET', //Type of Ajax call
dataType: 'html', //Type of data to be expected on return
success: function(data) { //Function that manipulates the returned AJAX'ed data
$('#results').html(data); //Load the data into a HTML holder
var $el = $('#results'); //jQuery Object that is holding the results
setTimeout(function(){ //Custom callback function to count the number of results
callBack($el);
});
}
});
}
//Custom Callback function to return the number of results
var callBack = function(el) {
var length = $('tr', $(el)).not('tr:first').length; //Count all TR DOM elements, except the first row (which contains the header information)
$('#num_results span').text(length); //Write the counted results to the DOM
}
</script>
Obviously this is a quick example, but it may be helpful.
You probably want the answer to "How to call an external command in Python".
The simplest approach is to use the os.system
function, e.g.:
import os
os.system("some_command &")
Basically, whatever you pass to the system
function will be executed the same as if you'd passed it to the shell in a script.
There's nothing deep happening here.. Basically, it's handy to test something to see if it's of a certain type (i.e. use 'as'). You would want to check the result of the 'as' call to see if the result is null.
When you expect a cast to work and you want the exception to be thrown, use the 'classic' method.
The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...
+----------------+-----------------+----------------+----------------+
| Command | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system() | Yes (as text) | Last line only | Yes |
| passthru() | Yes (raw) | No | Yes |
| exec() | No | Yes (array) | Yes |
| shell_exec() | No | Yes (string) | No |
| backticks (``) | No | Yes (string) | No |
+----------------+-----------------+----------------+----------------+
Other misc things to be aware of:
Assuming your df.index is sorted you can use:
df.loc[df.index.max() + 1] = None
It handles well different indexes and column types.
[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:
df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None
long example:
df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']],
columns=["timestamp", "speed", "text"],
index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11
Freq: L
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null int64
text 1 non-null object
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 32.0+ bytes
df.loc[df.index.max() + 1] = None
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null float64
text 1 non-null object
dtypes: datetime64[ns](1), float64(1), object(1)
memory usage: 64.0+ bytes
df.head()
timestamp speed text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423 23.0 text_field
2111-11-11 00:00:00.001 NaT NaN NaN
Part A: Configuring your Application Pool
Suppose the Application Pool is named 'MyPool' Go to 'Advanced Settings' of the Application Pool from the IIS Manager
Scroll down to 'Identity'. Trying to edit the value will bring up a dialog box. Select 'Built-In account' and under it, select 'ApplicationPoolIdentity'.
A few lines below 'Identity', you should find 'Load User Profile'. This value should be set to 'True'.
Part B: Configuring your website
Part C: Configuring your folder
The folder in question is C:\Whatever
You should now be able to use the browse the website
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
I did the following to add a role 'eSumit' on PostgreSQL 9.4.15 database and provide all permission to this role :
CREATE ROLE eSumit;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO eSumit;
GRANT ALL PRIVILEGES ON DATABASE "postgres" to eSumit;
ALTER USER eSumit WITH SUPERUSER;
Also checked the pg_table enteries via :
Make sure that the Object
s in your list have equals()
defined on them. Then
assertThat(generatedList, is(equalTo(expectedList)));
works.
In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation><operation name="create">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation>
</binding>
if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>
How to determine the SOAP version of the SOAP message?
but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.
1. checking the namespace of the soap message
SOAP 1.1 namespace : http://schemas.xmlsoap.org/soap/envelope
SOAP 1.2 namespace : http://www.w3.org/2003/05/soap-envelope
2. checking the transport binding information (http header information) of the soap message
SOAP 1.1 : user text/xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
SOAP 1.2 : user application/soap+xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: application/soap+xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
3. using SOAP fault information
The structure of a SOAP fault message between the two versions are different.
You have a constructor which takes 2 parameters. You should write something like:
new ErrorEventArg(errorMsv, lastQuery)
It's less code and easier to read.
EDIT
Or, in order for your way to work, you can try writing a default constructor for ErrorEventArg which would have no parameters, like this:
public ErrorEventArg() {}
Radu Simionescu - awesome work! and below Your solution for Swift lovers:
@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
var presentingVC = self.presentingViewController
self.dismissViewControllerAnimated(false, completion: { () -> Void in
presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
})
}
Elaborating to the answer of @Cephalopod, if you wanted all column names in a list you could use this oneliner:
List<String> columns =
Arrays.asList(MyClass.class.getFields())
.stream()
.filter(f -> f.getAnnotation(Column.class)!=null)
.map(f -> f.getAnnotation(Column.class).columnName())
.collect(Collectors.toList());
You need to specify correct Content-type, Content-encoding and charset like
data:image/jpeg;charset=utf-8;base64,
according to the syntax of the data URI scheme:
data:[<media type>][;charset=<character set>][;base64],<data>
for HTML5
The value must be unique amongst all the IDs in the element’s home subtree and must contain at least one character. The value must not contain any space characters.
At least one character, no spaces.
This opens the door for valid use cases such as using accented characters. It also gives us plenty of more ammo to shoot ourselves in the foot with, since you can now use id values that will cause problems with both CSS and JavaScript unless you’re really careful.
Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN
:
ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]
Note: unlike the sp_defaultdb
solution user and database names are provided without quotes. Brackets are needed if name had special chars (most common example will be domain user which is domain\username
and won't work without brackets).
Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)
Ok, this is not a very serious review, but here is what I can say:
I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:
#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis
import sys, time
stdout = sys.stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
class Iterator(object) :
def __init__(self):
print 'Rendering...'
for y in xrange(-39, 39):
stdout.write('\n')
for x in xrange(-39, 39):
if self.mandelbrot(x/40.0, y/40.0) :
stdout.write(' ')
else:
stdout.write('*')
def mandelbrot(self, x, y):
cr = y - 0.5
ci = x
zi = 0.0
zr = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
if zi2 + zr2 > BAILOUT:
return i
return 0
t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)
As a result:
PyChecker
is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.PyFlakes
is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.PyLint
has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).Strong points of PyLint
:
Cons of Pylint:
Corrected script (with lazy doc strings and variable names):
#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""
import time
from sys import stdout
BAILOUT = 16
MAX_ITERATIONS = 1000
def mandelbrot(dim_1, dim_2):
"""
function doc string
"""
cr1 = dim_1 - 0.5
ci1 = dim_2
zi1 = 0.0
zr1 = 0.0
for i in xrange(MAX_ITERATIONS) :
temp = zr1 * zi1
zr2 = zr1 * zr1
zi2 = zi1 * zi1
zr1 = zr2 - zi2 + cr1
zi1 = temp + temp + ci1
if zi2 + zr2 > BAILOUT:
return i
return 0
def execute() :
"""
func doc string
"""
print 'Rendering...'
for dim_1 in xrange(-39, 39):
stdout.write('\n')
for dim_2 in xrange(-39, 39):
if mandelbrot(dim_1/40.0, dim_2/40.0) :
stdout.write(' ')
else:
stdout.write('*')
START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)
Thanks to Rudiger Wolf, I discovered pep8
that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.
Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.
To give you a little idea of their output:
pep8:
./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3
Pylint:
************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C: 1: Missing docstring
C: 5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)
[...] and a very long report with useful stats like :
Duplication
-----------
+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+
I recently had to build something similar. You can check it out in the snippet below.
The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin
Basically, my code looks like this...
Run Code Snippet
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
runner = setInterval(function(){_x000D_
degrees++;_x000D_
rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
},50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
if (!rotate){_x000D_
rotate = true;_x000D_
start();_x000D_
} else {_x000D_
rotate = false;_x000D_
stop();_x000D_
}_x000D_
})
_x000D_
body {_x000D_
background: #1e1e1e;_x000D_
} _x000D_
_x000D_
.rocket {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
margin: 1em;_x000D_
border: 3px dashed teal;_x000D_
border-radius: 50%;_x000D_
background-color: rgba(128,128,128,0.5);_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.rocket h1 {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
font-size: .8em;_x000D_
color: skyblue;_x000D_
letter-spacing: 1em;_x000D_
text-shadow: 0 0 10px black;_x000D_
}_x000D_
_x000D_
.toggle {_x000D_
margin: 10px;_x000D_
background: #000;_x000D_
color: white;_x000D_
font-size: 1em;_x000D_
padding: .3em;_x000D_
border: 2px solid red;_x000D_
outline: none;_x000D_
letter-spacing: 3px;_x000D_
}
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
Use a return statement!
return;
or
if (condition) return;
You don't need to (and can't) specify any values, if your method returns void
.
It's possible to some extent but won't be really accurate, the idea is load image with a known file size then in its onload
event measure how much time passed until that event was triggered, and divide this time in the image file size.
Example can be found here: Calculate speed using javascript
Test case applying the fix suggested there:
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!_x000D_
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg"; _x000D_
var downloadSize = 4995374; //bytes_x000D_
_x000D_
function ShowProgressMessage(msg) {_x000D_
if (console) {_x000D_
if (typeof msg == "string") {_x000D_
console.log(msg);_x000D_
} else {_x000D_
for (var i = 0; i < msg.length; i++) {_x000D_
console.log(msg[i]);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var oProgress = document.getElementById("progress");_x000D_
if (oProgress) {_x000D_
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");_x000D_
oProgress.innerHTML = actualHTML;_x000D_
}_x000D_
}_x000D_
_x000D_
function InitiateSpeedDetection() {_x000D_
ShowProgressMessage("Loading the image, please wait...");_x000D_
window.setTimeout(MeasureConnectionSpeed, 1);_x000D_
}; _x000D_
_x000D_
if (window.addEventListener) {_x000D_
window.addEventListener('load', InitiateSpeedDetection, false);_x000D_
} else if (window.attachEvent) {_x000D_
window.attachEvent('onload', InitiateSpeedDetection);_x000D_
}_x000D_
_x000D_
function MeasureConnectionSpeed() {_x000D_
var startTime, endTime;_x000D_
var download = new Image();_x000D_
download.onload = function () {_x000D_
endTime = (new Date()).getTime();_x000D_
showResults();_x000D_
}_x000D_
_x000D_
download.onerror = function (err, msg) {_x000D_
ShowProgressMessage("Invalid image, or error downloading");_x000D_
}_x000D_
_x000D_
startTime = (new Date()).getTime();_x000D_
var cacheBuster = "?nnn=" + startTime;_x000D_
download.src = imageAddr + cacheBuster;_x000D_
_x000D_
function showResults() {_x000D_
var duration = (endTime - startTime) / 1000;_x000D_
var bitsLoaded = downloadSize * 8;_x000D_
var speedBps = (bitsLoaded / duration).toFixed(2);_x000D_
var speedKbps = (speedBps / 1024).toFixed(2);_x000D_
var speedMbps = (speedKbps / 1024).toFixed(2);_x000D_
ShowProgressMessage([_x000D_
"Your connection speed is:", _x000D_
speedBps + " bps", _x000D_
speedKbps + " kbps", _x000D_
speedMbps + " Mbps"_x000D_
]);_x000D_
}_x000D_
}
_x000D_
<h1 id="progress">JavaScript is turned off, or your browser is realllllly slow</h1>
_x000D_
Quick comparison with "real" speed test service showed small difference of 0.12 Mbps when using big picture.
To ensure the integrity of the test, you can run the code with Chrome dev tool throttling enabled and then see if the result matches the limitation. (credit goes to user284130 :))
Important things to keep in mind:
The image being used should be properly optimized and compressed. If it isn't, then default compression on connections by the web server might show speed bigger than it actually is. Another option is using uncompressible file format, e.g. jpg. (thanks Rauli Rajande for pointing this out and Fluxine for reminding me)
The cache buster mechanism described above might not work with some CDN servers, which can be configured to ignore query string parameters, hence better setting cache control headers on the image itself. (thanks orcaman for pointing this out))
I found below useful link to explore how and when to use HIVE and PIG.
http://www.hadoopwizard.com/when-to-use-pig-latin-versus-hive-sql/
Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorsky
Chmod chmod = new Chmod();
chmod.setProject(new Project());
FileSet mySet = new FileSet();
mySet.setDir(new File("/my/path"));
mySet.setIncludes("**");
chmod.addFileset(mySet);
chmod.setPerm("+w");
chmod.setType(new FileDirBoth());
chmod.execute();
Via Bootstrap Grid, you can easily get the cross browser compatible solution.
<div class="container">
<div class="row">
<div class="col-sm-6" style="background-color:lavender;">
Div1
</div>
<div class="col-sm-6" style="background-color:lavenderblush;">
Div2
</div>
</div>
</div>
jsfiddle: http://jsfiddle.net/DTcHh/4197/
You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.
You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).
You should convert the shortened array back to a string with .join(",")
and then use it for the new cookie instead of using old_cookie
which is not shortened.
You may also not be using .splice()
correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice()
here.
function my_url (base, opt)
{
var retval = ["" + base];
retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
return retval.join("");
}
my_url("?z=z", { page_name : "pageX" /* no table_name and optionResult */ } );
/* Returns:
?z=z&page_name=pageX
*/
This avoids using typeof whatever === "undefined"
. (Also, there isn't any string concatenation.)
There is no built-in way that I know of to do this so you will need to come up with a custom solution depending on how complicated your form is. You should read this post:
Convert HTML forms to read-only (Update: broken post link, archived link)
EDIT: Based on your update, why are you so worried about having it read-only? You can do it via client-side but if not you will have to add the required tag to each control or convert the data and display it as raw text with no controls. If you are trying to make it read-only so that the next post will be unmodified then you have a problem because anyone can mess with the post to produce whatever they want so when you do in fact finally receive the data you better be checking it again to make sure it is valid.
I had the same problem on two Arduinos (one Uno, and one Modern Device Freeduino/USB Host board) and the window between reset and the beginning of serial port usage was so small that it was impossible to upload.
I finally fixed the problem by purchasing another Arduino Uno and building an ISP cable per these instructions, and using it to flash the Bare Bones app from the examples into each inaccessible board, using Arduino IDE version 0023, following these instructions to change preferences.txt. (Be sure to save the original file before editing it so you can replace it after you've rescued your Arduino.)
It took one quick upload to fix each board. Such a fast fix after so much grief. You might not want to purchase another Arduino, but consider these benefits:
Type in the terminal as follows:
mysql.server start
If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc
This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array
import numpy as np
from sklearn.metrics import auc
dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)
print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))
both output the same area: 4607.5
the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
I want to give a different view of MONEY vs. NUMERICAL, largely based my own expertise and experience... My point of view here is MONEY, because I have worked with it for a considerable long time and never really used NUMERICAL much...
MONEY Pro:
Native Data Type. It uses a native data type (integer) as the same as a CPU register (32 or 64 bit), so the calculation doesn't need unnecessary overhead so it's smaller and faster... MONEY needs 8 bytes and NUMERICAL(19, 4) needs 9 bytes (12.5% bigger)...
MONEY is faster as long as it is used for it was meant to be (as money). How fast? My simple SUM
test on 1 million data shows that MONEY is 275 ms and NUMERIC 517 ms... That is almost twice as fast... Why SUM test? See next Pro point
MONEY Con:
money
doesn't need to be so precise and is meant to be used as money, not just a number...But... Big, but here is even your application involved real-money, but do not use it in lots of SUM operations, like in accounting. If you use lots of divisions and multiplications instead then you should not use MONEY...