The pack
method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize
or setBounds
(which also sets the frame location). In general, using pack is preferable to calling setSize
, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.
From Java tutorial
You should also refer to Javadocs any time you need additional information on any Java API
Both i++
and ++i
are short-hand for i = i + 1
.
In addition to changing the value of i, they also return the value of i, either before adding one (i++
) or after adding one (++i
).
In a loop the third component is a piece of code that is executed after each iteration.
for (int i=0; i<10; i++)
The value of that part is not used, so the above is just the same as
for(int i=0; i<10; i = i+1)
or
for(int i=0; i<10; ++i)
Where it makes a difference (between i++
and ++i
)is in these cases
while(i++ < 10)
for (int i=0; i++ < 10; )
you can test if have exactly some values, by example:
for(MyBoolean b : MyBoolean.values()) {
switch(b) {
case TRUE:
break;
case FALSE:
break;
default:
throw new IllegalArgumentException(b.toString());
}
for(String s : new String[]{"TRUE", "FALSE" }) {
MyBoolean.valueOf(s);
}
If someone removes or adds a value, some of test fails.
You have to update the php.ini config file with in your host provider's server, trust me on this, more than likely there is nothing wrong with your code. It took me almost a month and a half to realize that most hosting servers are not up to date on php.ini files, eg. php 5.5 or later, I believe.
While you do the following, technically speaking:
<button ng-click="doSomething($event)"></button>
// In controller:
$scope.doSomething = function($event) {
//reference to the button that triggered the function:
$event.target
};
This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.
You might check this answer for more info: https://stackoverflow.com/a/12431211/1418796
PHP has a built-in function implode to assign array values to string. Use it like this:
$str = implode(",", $array);
James K, I'm sorry I was wrong in a fair portion of what I said. The test I did was the following:
@ECHO OFF
(
:: But
: neither
:: does
: this
:: also.
)
This meets your description of alternating but fails with a ") was unexpected at this time." error message.
I did some farther testing today and found that alternating isn't the key but it appears the key is having an even number of lines, not having any two lines in a row starting with double colons (::) and not ending in double colons. Consider the following:
@ECHO OFF
(
: But
: neither
: does
: this
: cause
: problems.
)
This works!
But also consider this:
@ECHO OFF
(
: Test1
: Test2
: Test3
: Test4
: Test5
ECHO.
)
The rule of having an even number of comments doesn't seems to apply when ending in a command.
Unfortunately this is just squirrelly enough that I'm not sure I want to use it.
Really, the best solution, and the safest that I can think of, is if a program like Notepad++ would read REM as double colons and then would write double colons back as REM statements when the file is saved. But I'm not aware of such a program and I'm not aware of any plugins for Notepad++ that does that either.
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
<div class="row">
<div class="col-md-4" ng-repeat="remainder in [0,1,2]">
<ul>
<li ng-repeat="item in items" ng-if="$index % 3 == remainder">{{item}}</li>
</ul>
</div>
</div>
It is better if you find quotation marks by using the indexof()
method and then add a string behind that index.
string s="hai";
int s=s.indexof(""");
Collating possible solutions from the answers:
For IN: df[df['A'].isin([3, 6])]
For NOT IN:
df[-df["A"].isin([3, 6])]
df[~df["A"].isin([3, 6])]
df[df["A"].isin([3, 6]) == False]
df[np.logical_not(df["A"].isin([3, 6]))]
This method uses "object", it also has "embed". Either method works:
<div id="pdf">
<object id="pdf_content" width="100%" height="1500px" type="application/pdf" trusted="yes" application="yes" title="Assembly" data="Assembly.pdf?#zoom=100&scrollbar=1&toolbar=1&navpanes=1">
<!-- <embed src="Assembly.pdf" width="100%" height="100%" type="application/x-pdf" trusted="yes" application="yes" title="Assembly">
</embed> -->
<p>System Error - This PDF cannot be displayed, please contact IT.</p>
</object>
</div>
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill
To fetch a pail of water.
Jack fell down and broke his crown,
And Jill came tumbling after.
</div>
For 2d array, to determine the i, j position of nearest element:
import numpy as np
def find_nearest(a, a0):
idx = (np.abs(a - a0)).argmin()
w = a.shape[1]
i = idx // w
j = idx - i * w
return a[i,j], i, j
You forgot to declare double as a return type
public double diameter()
{
double d = radius * 2;
return d;
}
THE SHORT ANSWER:
Disable Microsoft Defender Application Guard
None of the answers helped me. Also, most of the answers here were addressed elsewhere online. I spent hours trying to solve this problem. After much hesitation, I decided to go on a hunch. I was suspicious about msinfo32.exe showing a Hypervisor was running, but it would not provide additional detail. I went into the services manager. I saw an instance of a hypervisor service was running, I went to disable it. Before disabling, I was asked if I am sure and was informed that a couple of other services would stop. One of the other services was Microsoft Defender Application Guard for Internet Explorer. I disabled this and FINALLY after hours of research on this topic was able to install Intel HAXM for Android Studio on my i5-4430 with Z87 chipset.
It was not enough to merely disable Hyper V and Windows Hypervisor Platform.
In iOS 13 you can use .darkContent
UIStatusBarStyle
property to display dark status bar
It's now possible with new chrome update for version 47 for 2016 , you can see it through developer tools on the resources tab, select cookies and look for your cookie expiration date under "Expires/Max-age"
After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..
quirksmode has a good description of the 'text-overflow' property, but you may need to apply some additional properties like 'white-space: nowrap'
Whilst I'm not 100% how this will behave in a select object, it could be worth trying this first:
The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.
Try this link to see an example of the output (this is in json, output is also available in XML)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
typedef
defines a new data type. So you can have:
typedef char* my_string;
typedef struct{
int member1;
int member2;
} my_struct;
So now you can declare variables with these new data types
my_string s;
my_struct x;
s = "welcome";
x.member1 = 10;
For enum
, things are a bit different - consider the following examples:
enum Ranks {FIRST, SECOND};
int main()
{
int data = 20;
if (data == FIRST)
{
//do something
}
}
using typedef enum
creates an alias for a type:
typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
Order data = (Order)20; // Must cast to defined type to prevent error
if (data == FIRST)
{
//do something
}
}
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
Office 2007
Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.
An easy one as an extension method
public static class Extensions
{
public static Stream ConvertToBase64(this Stream stream)
{
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
string base64 = Convert.ToBase64String(bytes);
return new MemoryStream(Encoding.UTF8.GetBytes(base64));
}
}
<?php
$data = 'My data';
$menugen = function() use ($data) {
echo "[ $data ]";
};
$menugen();
?>
You can also simplify
echo "[" . $data . "]"
to
echo "[$data]"
To force image that fit in a exact size, you don't need to write too many codes. It's so simple
img{_x000D_
width: 200px;_x000D_
height: auto;_x000D_
object-fit: contain; /* Fit logo in the image size */_x000D_
-o-object-fit: contain; /* Fit logo fro opera browser */_x000D_
object-position: top; /* Set logo position */_x000D_
-o-object-position: top; /* Logo position for opera browser */_x000D_
}
_x000D_
<img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">
_x000D_
Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden
as well, e.g.:
<div style="overflow: hidden">
<div style="overflow: hidden">some text that should not overflow<div>
</div>
Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)
If you absolutely have to have the field disabled and pass the data you could use a javascript to input the same data into a hidden field (or just set the hidden field too). This would allow you to have it disabled but still post the data even though you'd be posting to another page.
I am just building on Abdennour TOUMI's answer. here are the reasons why:
1.) I agree with Brad, I do not think it is a good idea to extend object that we did not create.
2.) array.length
is exactly reliable in javascript, I prefer Array.reduce
beacuse a=[1,3];a[1000]=5;
, now a.length
would return 1001
.
function getAverage(arry){
// check if array
if(!(Object.prototype.toString.call(arry) === '[object Array]')){
return 0;
}
var sum = 0, count = 0;
sum = arry.reduce(function(previousValue, currentValue, index, array) {
if(isFinite(currentValue)){
count++;
return previousValue+ parseFloat(currentValue);
}
return previousValue;
}, sum);
return count ? sum / count : 0;
};
Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.
From @Ben Bolker:
[T]his has nothing specifically to do with dplyr::filter()
From @Marat Talipov:
[A]ny comparison with NA, including NA==NA, will return NA
From a related answer by @farnsy:
The == operator does not treat NA's as you would expect it to.
Think of NA as meaning "I don't know what's there". The correct answer to 3 > NA is obviously NA because we don't know if the missing value is larger than 3 or not. Well, it's the same for NA == NA. They are both missing values but the true values could be quite different, so the correct answer is "I don't know."
R doesn't know what you are doing in your analysis, so instead of potentially introducing bugs that would later end up being published an embarrassing you, it doesn't allow comparison operators to think NA is a value.
What is the best way to implement Singleton in Java, in a multithreaded environment?
Refer to this post for best way to implement Singleton.
What is an efficient way to implement a singleton pattern in Java?
What happens when multiple threads try to access getInstance() method at the same time?
It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.
Refer to this question for more details:
Why is volatile used in this example of double checked locking
Can we make singleton's getInstance() synchronized?
Is synchronization really needed, when using Singleton classes?
Not required if you implement the Singleton in below ways
Refer to this question fore more details
I guess you want to do this in i line. It is possible (a bit of juggling though =^)
new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()
tadaa, one line -> the result you want (if you split on " - " (space minus space) instead of only "-" (minus) you will loose the annoying space before the partition too =^) so "Günnewig Uebachs" instead of " Günnewig Uebachs" (with a space as first character)
Nice extra -> no need for extra JAR files in the lib folder so you can keep your application light weight.
The BOOLEAN data type is a PL/SQL data type. Oracle does not provide an equivalent SQL data type (...) you can create a wrapper function which maps a SQL type to the BOOLEAN type.
Check this: http://forums.datadirect.com/ddforums/thread.jspa?threadID=1771&tstart=0&messageID=5284
This optimized method create (or update an existing) array of pointers in *result and returns the number of elements in *count.
Use "max" to indicate the maximum number of strings you expect (when you specify an existing array or any other reaseon), else set it to 0
To compare against a list of delimiters, define delim as a char* and replace the line:
if (str[i]==delim) {
with the two following lines:
char *c=delim; while(*c && *c!=str[i]) c++;
if (*c) {
Enjoy
#include <stdlib.h>
#include <string.h>
char **split(char *str, size_t len, char delim, char ***result, unsigned long *count, unsigned long max) {
size_t i;
char **_result;
// there is at least one string returned
*count=1;
_result= *result;
// when the result array is specified, fill it during the first pass
if (_result) {
_result[0]=str;
}
// scan the string for delimiter, up to specified length
for (i=0; i<len; ++i) {
// to compare against a list of delimiters,
// define delim as a string and replace
// the next line:
// if (str[i]==delim) {
//
// with the two following lines:
// char *c=delim; while(*c && *c!=str[i]) c++;
// if (*c) {
//
if (str[i]==delim) {
// replace delimiter with zero
str[i]=0;
// when result array is specified, fill it during the first pass
if (_result) {
_result[*count]=str+i+1;
}
// increment count for each separator found
++(*count);
// if max is specified, dont go further
if (max && *count==max) {
break;
}
}
}
// when result array is specified, we are done here
if (_result) {
return _result;
}
// else allocate memory for result
// and fill the result array
*result=malloc((*count)*sizeof(char*));
if (!*result) {
return NULL;
}
_result=*result;
// add first string to result
_result[0]=str;
// if theres more strings
for (i=1; i<*count; ++i) {
// find next string
while(*str) ++str;
++str;
// add next string to result
_result[i]=str;
}
return _result;
}
Usage example:
#include <stdio.h>
int main(int argc, char **argv) {
char *str="JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char **result=malloc(6*sizeof(char*));
char **result2=0;
unsigned long count;
unsigned long count2;
unsigned long i;
split(strdup(str),strlen(str),',',&result,&count,6);
split(strdup(str),strlen(str),',',&result2,&count2,0);
if (result)
for (i=0; i<count; ++i) {
printf("%s\n",result[i]);
}
printf("\n");
if (result2)
for (i=0; i<count2; ++i) {
printf("%s\n", result2[i]);
}
return 0;
}
Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:
public static void main(final String[] args) {
// Create some maps
final Map<Integer, String> map1 = new HashMap<Integer, String>();
map1.put(1, "Hello");
map1.put(2, "There");
final Map<Integer, String> map2 = new HashMap<Integer, String>();
map2.put(2, "There");
map2.put(3, "is");
map2.put(4, "a");
map2.put(5, "bird");
// Add everything in map1 not in map2 to map2
map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}
My solutions in one of my own sites, with a table:
$.getJSON("sections/view_numbers_update.php", function(data) {
$.each(data, function(index, objNumber) {
$('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
$('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
$('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
$('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
});
});
sections/view_numbers_update.php Returns something like:
[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]
HTML table:
<table id="table_numbers">
<tr>
<th>[...]</th>
<th>[...]</th>
<th>[...]</th>
<th>Last Call</th>
<th>Status</th>
<th>Duration</th>
<th>Human?</th>
<th>[...]</th>
</tr>
<tr id="tr_123456">
[...]
</tr>
</table>
This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.
The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.
For me it also was problem with path, but I had percentage sign in the root folder.
After I replaced %20 with space, it started to work :)
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
You can use either:
ActiveCell.Interior.ColorIndex = 28
or
ActiveCell.Interior.Color = RGB(255,0,0)
First of all, you should never use the money datatype. If you do any calculations you will get truncated results. Run the following to see what I mean
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)
SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000
SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3
SELECT @mon4 AS moneyresult,
@num4 AS numericresult
Output: 2949.0000 2949.8525
Now to answer your question (it was a little vague), the money datatype always has two places after the decimal point. Use the integer datatype if you don't want the fractional part or convert to int.
Perhaps you want to use the decimal or numeric datatype?
In my case I found once I rebuild the app it worked.
I had imported the HttpClientModule
as specified in the previous posts but I was still getting the error. I stopped the server, rebuilt the app (ng serve
) and it worked.
In case of Java 8 we can also use IntStream
to reverse the array of integers as:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]
Do simple compare > and <.
if (dateA>dateB && dateA<dateC)
//do something
If you care only on time:
if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
//do something
I had a similar requirement on my system and this was my solution:
In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like
C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m
Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.
Example
A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.
import sys
def squared(x):
y = x * x
return y
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
Then in MATLAB
>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>
EDIT : Works with design library upto 23.0.1 but doesn't work on 23.1.0
In main layout xml you will have NavigationView
defined, in that use app:headerLayout
to set the header view.
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_drawer_header"
app:menu="@menu/navigation_drawer_menu" />
And the @layout/nav_drawer_header
will be the place holder of the image and texts.
nav_drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/headerRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="@drawable/background" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/action_bar_size"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#40000000"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="16dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="35dp"
android:orientation="vertical"
android:weightSum="2">
<TextView
android:id="@+id/navHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/navHeaderSubTitle"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@android:color/white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
And in your main class, you can take handle of Imageview
and TextView
as like normal other views.
TextView navHeaderTitle = (TextView) findViewById(R.id.navHeaderTitle);
navHeaderTitle.setText("Application Name");
TextView navHeaderSubTitle = (TextView) findViewById(R.id.navHeaderSubTitle);
navHeaderSubTitle.setText("Application Caption");
Hope this helps.
In addition to all the great answers here already, I've also used it to walk an item through a series of transformation steps.
If a transformation is implemented as a Func<T,T>
, you can add several transformations to a List<Func<T,T>>
and use Aggregate
to walk an instance of T
through each step.
You want to take a string
value, and walk it through a series of text transformations that could be built programatically.
var transformationPipeLine = new List<Func<string, string>>();
transformationPipeLine.Add((input) => input.Trim());
transformationPipeLine.Add((input) => input.Substring(1));
transformationPipeLine.Add((input) => input.Substring(0, input.Length - 1));
transformationPipeLine.Add((input) => input.ToUpper());
var text = " cat ";
var output = transformationPipeLine.Aggregate(text, (input, transform)=> transform(input));
Console.WriteLine(output);
This will create a chain of transformations: Remove leading and trailing spaces -> remove first character -> remove last character -> convert to upper-case. Steps in this chain can be added, removed, or reordered as needed, to create whatever kind of transformation pipeline is required.
The end result of this specific pipeline, is that " cat "
becomes "A"
.
This can become very powerful once you realize that T
can be anything. This could be used for image transformations, like filters, using BitMap
as an example;
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
As a programmer often on the client-end, I prefer the query argument. Also, for me, it separates the URL path from the parameters, adds to clarity, and offers more extensibility. It also allows me to have separate logic between the URL/URI building and the parameter builder.
I do like what manuel aldana said about the other option if there's some sort of tree involved. I can see user-specific parts being treed off like that.
I'm looking into this as well, and while I don't have a good solution for you I did manage to dig up SIPDroid's video code:
http://code.google.com/p/sipdroid/source/browse/trunk/src/org/sipdroid/sipua/ui/VideoCamera.java
My preferred method is not to do that at all. The age of constants pretty much died when Java 5 introduced typesafe enums. And even before then Josh Bloch published a (slightly more wordy) version of that, which worked on Java 1.4 (and earlier).
Unless you need interoperability with some legacy code there's really no reason to use named String/integer constants anymore.
gcc -I/path -L/path
-I /path
path to include, gcc will find .h files in this path
-L /path
contains library files, .a
, .s
o
You can't mix in stored procedures with ordinary SQL, whilst with stored function you can.
e.g. SELECT get_foo(myColumn) FROM mytable
is not valid if get_foo()
is a procedure, but you can do that if get_foo()
is a function. The price is that functions have more limitations than a procedure.
Use the Font-property on the gridview. See MSDN for details and samples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx
You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:
> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCollection("test").ensureIndex ({"a" : 1}, {unique: true})
> db.getCollection("test").insert({a:2, b:12, c:13}) # This works
> db.getCollection("test").insert({a:1, b:12, c:13}) # This fails
E11000 duplicate key error index: foo.test.$a_1 dup key: { : 1.0 }
Make sure the file you're using ('C:\Users\Michael\workspace\pydb\data\andrew.out.txt'
) is on the SQL server machine and not the client machine running MSSMS.
In one line, using a lambda
:
timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)
Passing a function to list.sort
:
def foo(x):
return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]
timestamps.sort(key=foo, reverse=True)
A bit more modern way to do it:
const selectedValues = $('input[name="locationthemes"]:checked').map( function () {
return $(this).val();
})
.get()
.join(', ');
We first find all the selected checkboxes with the given name, and then jQuery's map() iterates through each of them, calling the callback on it to get the value, and returning the result as a new jQuery collection that now holds the checkbox values. We then call get() on it to get an array of values, and then join() to concatenate them into a single string - which is then assigned to the constant selectedValues.
You can use apache Range API. https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/Range.html
You need to
#include <string>
<iostream>
declares cout
, cin
, not string
.
Check this useful method:
URLUtil.guessUrl(urlString)
It makes google.com -> http://google.com
You can use code as below when
using Image as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
using Text as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.
Definition here
$(document).ready(function() {
$('#div_one').bind('click', function() {
$('#div_two').addClass('large');
});
});
If I understood your question.
Or you can modify css directly:
var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');
let leng = yourString.split(' ').filter(a => a.trim().length > 0).length
Darin Dimitrov's solution worked for me with one exception. When I submitted the partial view with (intentional) validation errors, I ended up with duplicate forms being returned in the dialog:
To fix this I had to wrap the Html.BeginForm in a div:
<div id="myForm">
@using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
{
//form contents
}
</div>
When the form was submitted, I cleared the div in the success function and output the validated form:
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myForm').html('');
$('#result').html(result);
}
});
}
return false;
});
});
My solution is based on @Martijn Pieters' comment:
register_namespace
only influences serialisation, not search.
So the trick here is to use different dictionaries for serialization and for searching.
namespaces = {
'': 'http://www.example.com/default-schema',
'spec': 'http://www.example.com/specialized-schema',
}
Now, register all namespaces for parsing and writing:
for name, value in namespaces.iteritems():
ET.register_namespace(name, value)
For searching (find()
, findall()
, iterfind()
) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).
self.namespaces['default'] = self.namespaces['']
Now, the functions from the find()
family can be used with the default
prefix:
print root.find('default:myelem', namespaces)
but
tree.write(destination)
does not use any prefixes for elements in the default namespace.
I wasn't able to use the answers here as-is. For starters, as noted, the Travis help document on running jobs locally has been taken down. All of the blog entries and articles I found are based on that. The new "debug" mode doesn't appeal to me because I want to avoid the queue times and the Travis infrastructure until I've got some confidence I have gotten somewhere with my changes.
In my case I'm updating a Puppet module and I'm not an expert in Puppet, nor particularly experienced in Ruby, Travis, or their ecosystems. But I managed to build a workable test image out of tips and ideas in this article and elsewhere, and by examining the Travis CI build logs pretty closely.
I was unable to find recent images matching the names in the CI logs (for example, I could find travisci/ci-sardonyx, but could not find anything with "xenial" or with the same build name). From the logs it appears images are now transferred via AMQP instead of a mechanism more familiar to me.
I was able to find an image travsci/ubuntu-ruby:16.04
which matches the OS I'm targeting for my particular case. It does not have all the components used in the Travis CI, so I built a new one based on this, with some components added to the image and others added in the container at runtime depending on the need.
So I can't offer a clear procedure, sorry. But what I did, essentially boiled down:
Find a recent Travis CI image in Docker Hub matching your target OS as closely as possible.
Clone the repository to a build directory, and launch the container with the build directory mounted as a volume, with the working directory set to the target volume
Now the hard work: go through the Travis build log and set up the environment. In my case, this meant setting up RVM, and then using bundle
to install the project's dependencies. RVM appeared to be already present in the Travis environment but I had to install it; everything else came from reproducing the commands in the build log.
Run the tests.
If the results don't match what you saw in the Travis CI logs, go back to (3) and see where to go.
Optionally, create a reusable image.
Dev and test locally and then push and hopefully your Travis results will be as expected.
I know this is not concrete and may be obvious, and your mileage will definitely vary, but hopefully this is of some use to somebody. The Dockerfile and a README for my image are on GitHub for reference.
As others have said, you can't reliably detect an invalid pointer. Consider some of the forms an invalid pointer might take:
You could have a null pointer. That's one you could easily check for and do something about.
You could have a pointer to somewhere outside of valid memory. What constitutes valid memory varies depending on how the run-time environment of your system sets up the address space. On Unix systems, it is usually a virtual address space starting at 0 and going to some large number of megabytes. On embedded systems, it could be quite small. It might not start at 0, in any case. If your app happens to be running in supervisor mode or the equivalent, then your pointer might reference a real address, which may or may not be backed up with real memory.
You could have a pointer to somewhere inside your valid memory, even inside your data segment, bss, stack or heap, but not pointing at a valid object. A variant of this is a pointer that used to point to a valid object, before something bad happened to the object. Bad things in this context include deallocation, memory corruption, or pointer corruption.
You could have a flat-out illegal pointer, such as a pointer with illegal alignment for the thing being referenced.
The problem gets even worse when you consider segment/offset based architectures and other odd pointer implementations. This sort of thing is normally hidden from the developer by good compilers and judicious use of types, but if you want to pierce the veil and try to outsmart the operating system and compiler developers, well, you can, but there is not one generic way to do it that will handle all of the issues you might run into.
The best thing you can do is allow the crash and put out some good diagnostic information.
I'm running phonegap 3.1.0-0.15.0, since iOS7 changed the resolution to 120x120px I just added a file with those dimensions to the project then changed the info.plist file.
More info can be found here: http://www.digifloor.com/missing-recommended-icon-file-error-ios-app-13
To fix the splash screen in iOS i just pasted in new files with the same dimensions and same filenames, overwriting the old ones. Just remember to go to Product>Clean in the menu bar in Xcode (shortcut Shift+Command+K) and it should work fine! :)
Late answer but finger
also shows more information on user
sudo apt-get finger
finger "$username"
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval
... which you don't).
var myBool = myString == "true";
Put double quotes around the path that has spaces like this:
REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"
You can always try Manage Docker as a non-root user
paragraph in the https://docs.docker.com/install/linux/linux-postinstall/ docs.
After doing this also if the problem persists then you can run the following command to solve it:
sudo chmod 666 /var/run/docker.sock
Use http instead of https; it will give warning message and redirect to https, get cloned without any issues.
$ git clone http://github.com/karthikeyana/currency-note-classifier-counter.git
Cloning into 'currency-note-classifier-counter'...
warning: redirecting to https://github.com/karthikeyana/currency-note-classifier-counter.git
remote: Enumerating objects: 533, done.
remote: Total 533 (delta 0), reused 0 (delta 0), pack-reused 533
Receiving objects: 100% (533/533), 608.96 KiB | 29.00 KiB/s, done.
Resolving deltas: 100% (295/295), done.
RST is sent by the side doing the active close because it is the side which sends the last ACK. So if it receives FIN from the side doing the passive close in a wrong state, it sends a RST packet which indicates other side that an error has occured.
The only way I've seen it done is if you do this:
for /f "delims=" %a in ('ver') do @set foobar=%a
ver
is the version command for Windows and on my system it produces:
Microsoft Windows [Version 6.0.6001]
For people looking to do if statements with multiple 'or' values.
<div ng-if="::(a || b || c || d || e || f)"><div>
/**
* Get JSONP data for cross-domain AJAX requests
* @private
* @link http://cameronspear.com/blog/exactly-what-is-jsonp/
* @param {String} url The URL of the JSON request
* @param {String} callback The name of the callback to run on load
*/
var loadJSONP = function ( url, callback ) {
// Create script with url and callback (if specified)
var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
var script = window.document.createElement( 'script' );
script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;
// Insert script tag into the DOM (append to <head>)
ref.parentNode.insertBefore( script, ref );
// After the script is loaded (and executed), remove it
script.onload = function () {
this.remove();
};
};
/**
* Example
*/
// Function to run on success
var logAPI = function ( data ) {
console.log( data );
}
// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );
If you put set directory=""
in your exrc file, you will turn off the swap file. However, doing so will disable recovery.
More info here.
It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:
class RThread : public wxThread {
public:
RThread()
: wxThread(wxTHREAD_JOINABLE){
}
private:
RThread(const RThread ©);
public:
void *Entry(void){
//Do...
return 0;
}
};
wxThread *CreateThread() {
//Create thread
wxThread *_hThread = new RThread();
//Start thread
_hThread->Create();
_hThread->Run();
return _hThread;
}
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it. More info here: wxThread documentation
First let's create the dataframe you had, I'll ignore columns B and C as they are not relevant.
df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6,5]})
And the mapping that you desire:
mapping = dict(enumerate([2,5,6,8,12,16,26,32]))
df['D'] = df['A'].map(mapping)
Done!
print df
Output:
A D
0 0 2
1 4 12
2 5 16
3 6 26
4 7 32
5 7 32
6 6 26
7 5 16
Since there is no php.ini file in your /public_html directory......create a new file as phpinfo.php in /public_html directory
-Type this code in phpinfo.php and save it:
<?php
phpinfo();
?>
-Then type yourdomain.com/phpinfo.php...you will see all the details of your configuration
-To edit that config, create another file as php.ini in /public_html directory and paste this code:
memory_limit=512M
post_max_size=200M
upload_max_filesize=200M
-And then refresh yourdomain.com/phpinfo.php and see the changes,it will be done.
Using Datatables 1.9.4 I've disabled the sorting for the first column with this code:
/* Table initialisation */
$(document).ready(function() {
$('#rules').dataTable({
"sDom" : "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
"sPaginationType" : "bootstrap",
"oLanguage" : {
"sLengthMenu" : "_MENU_ records per page"
},
// Disable sorting on the first column
"aoColumnDefs" : [ {
'bSortable' : false,
'aTargets' : [ 0 ]
} ]
});
});
EDIT:
You can disable even by using the no-sort
class on your <th>
,
and use this initialization code:
// Disable sorting on the no-sort class
"aoColumnDefs" : [ {
"bSortable" : false,
"aTargets" : [ "no-sort" ]
} ]
EDIT 2
In this example I'm using Datables with Bootstrap, following an old blog post. Now there is one link with updated material about styling Datatables with bootstrap.
I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.
Thanks, Max S. conda-forge worked for me as well.
Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:
First, check available the packages with versions
conda list
It will show packages and their installed versions in the output:
scikit-learn 0.19.1 py36hedc7406_0
Upgrade to 0.19.2 July 2018 release.
conda config --append channels conda-forge
conda install scikit-learn=0.19.2
Now check the version installed correctly or not?
conda list
Output is:
scikit-learn 0.19.2 py36_blas_openblasha84fab4_201 [blas_openblas] conda-forge
I tried following commands:
!conda update conda
!pip install -U scikit-learn
It will install the required packages also will show in the conda list
but when try to import that package it will not work.
On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.
Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()? What is its purpose?
OK, as my first answer was pretty long I won't extend it further so let's try this...
public DriveToWorkActivity extends Activity
implements onReachedGroceryStoreListener {
}
public GroceryStoreActivity extends Activity {}
PLEASE NOTE: I've deliberately left out the calls to things like super.onCreate(...)
etc. This is pseudo-code so give me some artistic licence here. ;)
The methods for DriveToWorkActivity
follow...
protected void onCreate(...) {
openGarageDoor();
unlockCarAndGetIn();
closeCarDoorAndPutOnSeatBelt();
putKeyInIgnition();
}
protected void onStart() {
startEngine();
changeRadioStation();
switchOnLightsIfNeeded();
switchOnWipersIfNeeded();
}
protected void onResume() {
applyFootbrake();
releaseHandbrake();
putCarInGear();
drive();
}
protected void onPause() {
putCarInNeutral();
applyHandbrake();
}
protected void onStop() {
switchEveryThingOff();
turnOffEngine();
removeSeatBeltAndGetOutOfCar();
lockCar();
}
protected void onDestroy() {
enterOfficeBuilding();
}
protected void onReachedGroceryStore(...) {
Intent i = new Intent(ACTION_GET_GROCERIES, ..., this, GroceryStoreActivity.class);
}
protected void onRestart() {
unlockCarAndGetIn();
closeDoorAndPutOnSeatBelt();
putKeyInIgnition();
}
OK, so it's another long one (sorry folks). But here's my explanation...
onResume()
is when I start driving and onPause()
is when I come to a temporary stop. So I drive then reach a red light so I pause...the light goes green and I resume. Another red light and I pause, then green so I resume. The onPause() -> onResume() -> onPause() -> onResume()
loop is a tight one and occurs many times through my journey.
The loop from being stopped back through a restart (preparing to carry on my journey) to starting again is perhaps less common. In one case, I spot the Grocery Store and the GroceryStoreActivity
is started (forcing my DriveToWorkActivity
to the point of onStop()
). When I return from the store, I go through onRestart()
and onStart()
then resume my journey.
I could put the code that's in onStart()
into both onCreate()
and onRestart()
and not bother to override onStart()
at all but the more that needs to be done between onCreate() -> onResume()
and onRestart() -> onResume()
, the more I'm duplicating things.
So, to requote once more...
Why can't it be the onResume() is invoked after onRestart() and onCreate() methods just excluding onStart()?
If you don't override onStart()
then this is effectively what happens. Although the onStart()
method of Activity
will be called implicitly, the effect in your code is effectively onCreate() -> onResume()
or onRestart() -> onResume()
.
I'm used it and worked perfectly...
startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
because Finish() use for 2 activities, not for multiple activities
Another way to do it:
MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/'
MEDIA_URL = '/static/media/'
This would require you to move your media folder to a sub directory of a static folder.
Then in your template you can use:
<img class="scale-with-grid" src="{{object.photo.url}}"/>
You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.
Download WinSCP .NET assembly.
The latest package as of now is WinSCP-5.17.10-Automation.zip
;
Extract the .zip
archive along your script;
Use a code like this (based on the official PowerShell upload example):
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload
$session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
You can have WinSCP generate the PowerShell script for the upload for you:
You will get a code like above with all session and transfer settings filled in.
(I'm the author of WinSCP)
If you're looking for something more straight forward to implement (and it doesn't include pie/donut charts) then I recommend WilliamChart. Specially if motion takes an important role in your app design. In other hand if you want featured charts, then go for MPAndroidChart.
You can also use String.valueOf((Object) nullableString)
like
switch (String.valueOf((Object) nullableString)) {
case "someCase"
//...
break;
...
case "null": // or default:
//...
break;
}
See interesting SO Q/A: Why does String.valueOf(null) throw a NullPointerException
Options:
data.Seek
as suggested by ken2kUse the somewhat simpler Position
property:
data.Position = 0;
Use the ToArray
call in MemoryStream
to make your life simpler to start with:
byte[] buf = data.ToArray();
The third option would be my preferred approach.
Note that you should have a using
statement to close the file stream automatically (and optionally for the MemoryStream
), and I'd add a using directive for System.IO
to make your code cleaner:
byte[] buf;
using (MemoryStream data = new MemoryStream())
{
using (Stream file = TestStream())
{
file.CopyTo(data);
buf = data.ToArray();
}
}
// Use buf
You might also want to create an extension method on Stream
to do this for you in one place, e.g.
public static byte[] CopyToArray(this Stream input)
{
using (MemoryStream memoryStream = new MemoryStream())
{
input.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Note that this doesn't close the input stream.
The "good node.js /event driven" way of doing this is to not wait.
Like almost everything else when working with event driven systems like node, your function should accept a callback parameter that will be invoked when then computation is complete. The caller should not wait for the value to be "returned" in the normal sense, but rather send the routine that will handle the resulting value:
function(query, callback) {
myApi.exec('SomeCommand', function(response) {
// other stuff here...
// bla bla..
callback(response); // this will "return" your value to the original caller
});
}
So you dont use it like this:
var returnValue = myFunction(query);
But like this:
myFunction(query, function(returnValue) {
// use the return value here instead of like a regular (non-evented) return value
});
I believe you're looking for...
import config.logging_settings # @UnusedImport
Note the double space before the comment to avoid hitting other formatting warnings.
Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport
).
you just make a list of lists like so:
List<List<string>> results = new List<List<string>>();
and then it's just a matter of using the functionality you want
results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list
This actually sums it up pretty nicely.
API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).
Choosing an API level for an application development should take at least two thing into account:
Android API levels can be divided to five main groups (not scientific, but what the heck):
The ally.js accessibility library provides an unofficial, test-based list here:
https://allyjs.io/data-tables/focusable.html
(NB: Their page doesn't say how often tests were performed.)
Vim's <leader>
key is a way of creating a namespace for commands you want to define. Vim already maps most keys and combinations of Ctrl + (some key), so <leader>(some key)
is where you (or plugins) can add custom behavior.
For example, if you find yourself frequently deleting exactly 3 words and 7 characters, you might find it convenient to map a command via nmap <leader>d 3dw7x
so that pressing the leader key followed by d will delete 3 words and 7 characters. Because it uses the leader key as a prefix, you can be (relatively) assured that you're not stomping on any pre-existing behavior.
The default key for <leader>
is \
, but you can use the command :let mapleader = ","
to remap it to another key (,
in this case).
Usevim's page on the leader key has more information.
This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:
Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)
kudos to https://php.quicoto.com/create-loop-inside-react-jsx/
this query will auto-update the nulls
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) DEFAULT 'whatever' NOT NULL;
You can also use z algorithm to find similarity in the string. Click here https://teakrunch.com/2020/05/09/string-similarity-hackerrank-challenge/
As an alternative, one can rely on the cartesian product provided by itertools: itertools.product
, which avoids creating a temporary key or modifying the index:
import numpy as np
import pandas as pd
import itertools
def cartesian(df1, df2):
rows = itertools.product(df1.iterrows(), df2.iterrows())
df = pd.DataFrame(left.append(right) for (_, left), (_, right) in rows)
return df.reset_index(drop=True)
Quick test:
In [46]: a = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
In [47]: b = pd.DataFrame(np.random.rand(5, 3), columns=["d", "e", "f"])
In [48]: cartesian(a,b)
Out[48]:
a b c d e f
0 0.436480 0.068491 0.260292 0.991311 0.064167 0.715142
1 0.436480 0.068491 0.260292 0.101777 0.840464 0.760616
2 0.436480 0.068491 0.260292 0.655391 0.289537 0.391893
3 0.436480 0.068491 0.260292 0.383729 0.061811 0.773627
4 0.436480 0.068491 0.260292 0.575711 0.995151 0.804567
5 0.469578 0.052932 0.633394 0.991311 0.064167 0.715142
6 0.469578 0.052932 0.633394 0.101777 0.840464 0.760616
7 0.469578 0.052932 0.633394 0.655391 0.289537 0.391893
8 0.469578 0.052932 0.633394 0.383729 0.061811 0.773627
9 0.469578 0.052932 0.633394 0.575711 0.995151 0.804567
10 0.466813 0.224062 0.218994 0.991311 0.064167 0.715142
11 0.466813 0.224062 0.218994 0.101777 0.840464 0.760616
12 0.466813 0.224062 0.218994 0.655391 0.289537 0.391893
13 0.466813 0.224062 0.218994 0.383729 0.061811 0.773627
14 0.466813 0.224062 0.218994 0.575711 0.995151 0.804567
15 0.831365 0.273890 0.130410 0.991311 0.064167 0.715142
16 0.831365 0.273890 0.130410 0.101777 0.840464 0.760616
17 0.831365 0.273890 0.130410 0.655391 0.289537 0.391893
18 0.831365 0.273890 0.130410 0.383729 0.061811 0.773627
19 0.831365 0.273890 0.130410 0.575711 0.995151 0.804567
20 0.447640 0.848283 0.627224 0.991311 0.064167 0.715142
21 0.447640 0.848283 0.627224 0.101777 0.840464 0.760616
22 0.447640 0.848283 0.627224 0.655391 0.289537 0.391893
23 0.447640 0.848283 0.627224 0.383729 0.061811 0.773627
24 0.447640 0.848283 0.627224 0.575711 0.995151 0.804567
Probably you just needed this CSS rule:
table {
border-spacing: 0px;
}
A file object is an instance of Blob but a blob object is not an instance of File
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
file.arrayBuffer().then((arrayBuffer) => {
let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
console.log(blob);
});
If your environment supports async/await you can use a one-liner like below
let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));
A Re-Introduction to Javascript by the Mozilla team (they make Firefox) should explain it.
You don't need to call ValidateForm()
twice, as you are above. You can just do
if(!ValidateForm()){
..
} else ...
I think that will solve the issue as above it looks like your comparing true/false
to the string equivalent 'false'
.
Here another method but it is little worse compare to other.
List<int> i=original.Take(original.count).ToList();
Bootstrap 4 to hide whole content use this class '.d-none' it will be hide everything regardless of breakpoints same like previous bootstrap version class '.hidden'
You need to indicate JAVA_HOME
in mvn.ini
(it's in the Maven folder /bin
), and your problem will disappear.
Here is the solution.
When you are receiving array from your database. and you are storing array data inside a variable but the variable defined as object. This time you will get the error.
I am receiving array from database and I'm stroing that array inside a variable 'bannersliders'. 'bannersliders' type is now 'any' but if you write 'bannersliders' is an object. Like bannersliders:any={}. So this time you are storing array data inside object type variable. So you find that error.
So you have to write variable like 'bannersliders:any;' or 'bannersliders:any=[]'.
Here I am giving an example.
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
bannersliders:any;
getallbanner(){
this.bannerService.getallbanner().subscribe(data=>{
this.bannersliders =data;
})
}
_x000D_
You can use the function RESHAPE:
B = reshape(A.',1,[]);
Add your multiple columns with comma separations:
UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'
However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?
Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.
You have installed the library in a non-standard location ($HOME/zlib/
). That means the compiler will not know where your header files are and you need to tell the compiler that.
You can add a path to the list that the compiler uses to search for header files by using the -I
(upper-case i) option.
Also note that the LD_LIBRARY_PATH
is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L
option.
All-together the command line should look like
$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz
There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.
For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.
I like to use
Example:
Properties props = new Properties();
props.setProperty("displayName", "Jim Wilson"); // (key, value)
String name = props.getProperty("displayName"); // => Jim Wilson
String acctNum = props.getProperty("accountNumber"); // => null
String nextPosition = props.getProperty("position", "1"); // => 1
If you are familiar with a hash table you will be pretty familiar with this already
By default Spring OAuth requires basic HTTP authentication. If you want to switch it off with Java based configuration, you have to allow form authentication for clients like this:
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients();
}
}
I had the same problem. I solved it by adding my OAuth redirect URI as a argument to the getAccessToken function call:
$redirectLoginHelper->getAccessToken("https://www.example.com/myfacebookcallback")
If no argument is sent into that function the SDK generates the redirect URI by itself which should work but in my case it didn't.
Hope this helps someone.
Here's a clear picture:
Assuming we have branch-A and branch-B
We want to merge branch-B into branch-A
on branch-B -> A: switch to branch-A
on branch-A: git merge branch-B
The solution that work for me in windows 64bits is the following
git config --system http.sslverify false
You could try using £
or £
instead of embedding the character directly; if you embed it directly, you're more likely to run into encoding issues in which your editor saves the file is ISO-8859-1 but it's interpreted as UTF-8, or vice versa.
If you want to embed it (or other Unicode characters) directly, make sure you actually save your file as UTF-8, and set the encoding as you did with the Content-Type
header. Make sure when you get the file from the server that the header is present and correct, and that the file hasn't been transcoded by the web server.
A edited version of @jfriend000 version:
/**
* Generates a random string
*
* @param int length_
* @return string
*/
function randomString(length_) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (typeof length_ !== "number") {
length_ = Math.floor(Math.random() * chars.length_);
}
var str = '';
for (var i = 0; i < length_; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
There are basically two major pitfalls people stumble in with floating-point numbers.
The problem of scale. Each FP number has an exponent which determines the overall “scale” of the number so you can represent either really small values or really larges ones, though the number of digits you can devote for that is limited. Adding two numbers of different scale will sometimes result in the smaller one being “eaten” since there is no way to fit it into the larger scale.
PS> $a = 1; $b = 0.0000000000000000000000001
PS> Write-Host a=$a b=$b
a=1 b=1E-25
PS> $a + $b
1
As an analogy for this case you could picture a large swimming pool and a teaspoon of water. Both are of very different sizes, but individually you can easily grasp how much they roughly are. Pouring the teaspoon into the swimming pool, however, will leave you still with roughly a swimming pool full of water.
(If the people learning this have trouble with exponential notation, one can also use the values 1
and 100000000000000000000
or so.)
Then there is the problem of binary vs. decimal representation. A number like 0.1
can't be represented exactly with a limited amount of binary digits. Some languages mask this, though:
PS> "{0:N50}" -f 0.1
0.10000000000000000000000000000000000000000000000000
But you can “amplify” the representation error by repeatedly adding the numbers together:
PS> $sum = 0; for ($i = 0; $i -lt 100; $i++) { $sum += 0.1 }; $sum
9,99999999999998
I can't think of a nice analogy to properly explain this, though. It's basically the same problem why you can represent 1/3 only approximately in decimal because to get the exact value you need to repeat the 3 indefinitely at the end of the decimal fraction.
Similarly, binary fractions are good for representing halves, quarters, eighths, etc. but things like a tenth will yield an infinitely repeating stream of binary digits.
Then there is another problem, though most people don't stumble into that, unless they're doing huge amounts of numerical stuff. But then, those already know about the problem. Since many floating-point numbers are merely approximations of the exact value this means that for a given approximation f of a real number r there can be infinitely many more real numbers r1, r2, ... which map to exactly the same approximation. Those numbers lie in a certain interval. Let's say that rmin is the minimum possible value of r that results in f and rmax the maximum possible value of r for which this holds, then you got an interval [rmin, rmax] where any number in that interval can be your actual number r.
Now, if you perform calculations on that number—adding, subtracting, multiplying, etc.—you lose precision. Every number is just an approximation, therefore you're actually performing calculations with intervals. The result is an interval too and the approximation error only ever gets larger, thereby widening the interval. You may get back a single number from that calculation. But that's merely one number from the interval of possible results, taking into account precision of your original operands and the precision loss due to the calculation.
That sort of thing is called Interval arithmetic and at least for me it was part of our math course at the university.
Please keep in mind that only a few elements can be self-closing, most others have to be closed through adding an explicit end tag. In the above case, the first script tag was not closed properly, the end script tag of the second script then closed the script section, causing only the first script to be loaded as external script source and ignoring the second script.
More info about which tags can be self-closed, have a look at the W3C drafts for HTML5 (although the definition was no different in earlier HTML-versions):
http://www.w3.org/TR/html5/syntax.html#end-tags (8.1.2.1, Point 6)
This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.
Create an XML file Create XML file
Add the following code on the new XML file you created Add base-config
Add this on AndroidManifest.xml Add this code line
Try this...
update [table_name] set [field_name] =
replace([field_name],'[string_to_find]','[string_to_replace]');
I assume you called a function with an argument which was defined without taking any.
def f()
puts "hello world"
end
f(1) # <= wrong number of arguments (1 for 0)
The problem is that your <label>
is inside of an <h2>
tag, and header tags have a margin
set by the default stylesheet.
I'm not actually suggesting that you do this, as the UNIQUE
index as suggested by Piskvor and others is a far better way to do it, but you can actually do what you were attempting:
CREATE TABLE `table_listnames` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`tele` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Insert a record:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
+----+--------+-----------+------+
Try to insert the same record again:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
+----+--------+-----------+------+
Insert a different record:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+--------+-----------+------+
| id | name | address | tele |
+----+--------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
+----+--------+-----------+------+
And so on...
Update:
To prevent #1060 - Duplicate column name
error in case two values may equal, you must name the columns of the inner SELECT:
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+---------+-----------+------+
| id | name | address | tele |
+----+---------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
| 3 | Unknown | Unknown | 022 |
+----+---------+-----------+------+
Everyone else has already answered it, but I think I still have something else to add.
Namedtuple could be intuitively deemed as a shortcut to define a class.
See a cumbersome and conventional way to define a class
.
class Duck:
def __init__(self, color, weight):
self.color = color
self.weight = weight
red_duck = Duck('red', '10')
In [50]: red_duck
Out[50]: <__main__.Duck at 0x1068e4e10>
In [51]: red_duck.color
Out[51]: 'red'
As for namedtuple
from collections import namedtuple
Duck = namedtuple('Duck', ['color', 'weight'])
red_duck = Duck('red', '10')
In [54]: red_duck
Out[54]: Duck(color='red', weight='10')
In [55]: red_duck.color
Out[55]: 'red'
A SOAP document is sent per request. Say we were a book store, and had a remote server we queried to learn the current price of a particular book. Say we needed to pass the Book's title, number of pages and ISBN number to the server.
Whenever we wanted to know the price, we'd send a unique SOAP message. It'd look something like this;
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:GetBookPrice xmlns:m="http://namespaces.my-example-book-info.com">
<ISBN>978-0451524935</ISBN>
<Title>1984</Title>
<NumPages>328</NumPages>
</m:GetBookPrice>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
And we expect to get a SOAP response message back like;
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:GetBookPriceResponse xmlns:m="http://namespaces.my-example-book-info.com">
<CurrentPrice>8.99</CurrentPrice>
<Currency>USD</Currency>
</m:GetBookPriceResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The WSDL then describes how to handle/process this message when a server receives it. In our case, it describes what types the Title, NumPages & ISBN would be, whether we should expect a response from the GetBookPrice message and what that response should look like.
The types would look like this;
<wsdl:types>
<!-- all type declarations are in a chunk of xsd -->
<xsd:schema targetNamespace="http://namespaces.my-example-book-info.com"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<xsd:element name="GetBookPrice">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ISBN" type="string"/>
<xsd:element name="Title" type="string"/>
<xsd:element name="NumPages" type="integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="GetBookPriceResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="CurrentPrice" type="decimal" />
<xsd:element name="Currency" type="string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</wsdl:types>
But the WSDL also contains more information, about which functions link together to make operations, and what operations are avaliable in the service, and whereabouts on a network you can access the service/operations.
See also W3 Annotated WSDL Examples
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
filter(lambda v: v==v, x)
works both for lists and numpy array since v!=v only for NaN
Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.
As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful
ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.
The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.
Make sure to check your machine.config files in both locations
C:\Windows\Microsoft.NET\Framework[version]\Config C:\Windows\Microsoft.NET\Framework64[version]\Config
I found out after trying all the solutions on this page.
String strOut = str.substring(0, 8) + "...";
You can hide the "Watch Later" Button by using "Youtube-nocookie" (this will not hide the share Button)
Adding controls=0
will also remove the video control bar at the bottom of the screen and using modestbranding=1
will remove the youtube logo at bottom right of the screen
However using them both doesn't works as expected (it only hides the video control bar)
<iframe width="100%" height="100%" src="https://www.youtube-nocookie.com/embed/fNb-DTEb43M?controls=0" frameborder="0" allowfullscreen></iframe>
The -fpermissive
flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
Use regular expressions. In this case, you can use gsub
:
gsub("^.*?_","_","ATGAS_1121")
[1] "_1121"
This regular expression matches the beginning of the string (^), any character (.) repeated zero or more times (*), and underscore (_). The ? makes the match "lazy" so that it only matches are far as the first underscore. That match is replaced with just an underscore. See ?regex
for more details and references
I was facing the same problem! I've added the code below in wp-config.php file (in any line) and it's working now!
define('FS_METHOD', 'direct');
you can use numpy.argsort
or you can do:
test = [2,3,1,4,5]
idxs = list(zip(*sorted([(val, i) for i, val in enumerate(test)])))[1]
zip
will rearange the list so that the first element is test
and the second is the idxs
.
Go here and find the version you want to install and then download the correct msi file and run the installer. You cannot install node by running this command, also the error you receive is stating that npm is not on your path which suggests machine doesn't currently have node installed on it
If you have Apache add this to the .htaccess
file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
I use this method as told by one of the user: This is what I did for Installing Anaconda Python 3.6 version and Tensorflow on Window 10 64bit.And It was success!
Go to https://www.continuum.io/downloads to download Anaconda Python 3.6 version for Window 64bit. Create a conda environment named tensorflow by invoking the following command:
C:> conda create -n tensorflow Activate the conda environment by issuing the following command:
C:> activate tensorflow (tensorflow)C:> # Your prompt should change Go to http://www.lfd.uci.edu/~gohlke/pythonlibs/enter code here download “tensorflow-1.0.1-cp36-cp36m-win_amd64.whl”. (For my case, the file will be located in “C:\Users\Joshua\Downloads” once after downloaded) Install the Tensorflow by using following command:
(tensorflow)C:>pip install C:\Users\Joshua\Downloads\ tensorflow-1.0.1-cp36-cp36m-win_amd64.whl
but nothing happens in the prompt. It starts from the new line with the tensorflow as if nothing was written. Whats the problem?
try this one
$(function () {
setTimeout(function () {
if ($(".alert").is(":visible")){
//you may add animate.css class for fancy fadeout
$(".alert").fadeOut("fast");
}
}, 3000)
});
For small number, and you know how many decimals you want, you can use toFixed and then use a regexp to remove the trailing zeros.
Number(1e-7).toFixed(8).replace(/\.?0+$/,"") //0.000
I will try to explain how to remove the focus (flashing cursor) from EditText view with some more details and understanding. Usually this line of code should work
editText.clearFocus()
but it could be situation when the editText still has the focus, and this is happening because clearFocus() method is trying to set the focus back to the first focusable view in the activity/fragment layout.
So if you have only one view in the activity which is focusable, and this usually will be your EditText view, then clearFocus() will set the focus again to that view, and for you it will look that clearFocus() is not working. Remember that EditText views are focusable(true) by default so if you have only one EditText view inside your layout it will aways get the focus on the screen. In this case your solution will be to find the parent view(some layout , ex LinearLayout, Framelayout) inside your layout file and set to it this xml code
android:focusable="true"
android:focusableInTouchMode="true"
After that when you execute editText.clearFocus() the parent view inside your layout will accept the focus and your editText will be clear of the focus.
I hope this will help somebody to understand how clearFocus() is working.
another way, this will scan the table only once instead of twice if you use a subquery
only sql server 2005 and up
select Date, User, Status, Notes
from (
select m.*, row_number() over (partition by user order by Date desc) as rn
from [SOMETABLE] m
) m2
where m2.rn = 1;
Try this on the PowerShell command line:
. .\MyFunctions.ps1
A1
The dot operator is used for script include.
All of the answers so far are good, and get at different aspects of how a hashtable works. Here is a simple example that might be helpful. Lets say we want to store some items with lower case alphabetic strings as a keys.
As simon explained, the hash function is used to map from a large space to a small space. A simple, naive implementation of a hash function for our example could take the first letter of the string, and map it to an integer, so "alligator" has a hash code of 0, "bee" has a hash code of 1, "zebra" would be 25, etc.
Next we have an array of 26 buckets (could be ArrayLists in Java), and we put the item in the bucket that matches the hash code of our key. If we have more than one item that has a key that begins with the same letter, they will have the same hash code, so would all go in the bucket for that hash code so a linear search would have to be made in the bucket to find a particular item.
In our example, if we just had a few dozen items with keys spanning the alphabet, it would work very well. However, if we had a million items or all the keys all started with 'a' or 'b', then our hash table would not be ideal. To get better performance, we would need a different hash function and/or more buckets.
Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.
Old answer:
Here is angular2-cookie which is the exact implementation of Angular 1 $cookies
service (plus a removeAll()
method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.
You can inject it as a service in the components providers
array:
import {CookieService} from 'angular2-cookie/core';
@Component({
selector: 'my-very-cool-app',
template: '<h1>My Angular2 App with Cookies</h1>',
providers: [CookieService]
})
After that, define it in the consturctur as usual and start using:
export class AppComponent {
constructor(private _cookieService:CookieService){}
getCookie(key: string){
return this._cookieService.get(key);
}
}
You can get it via npm:
npm install angular2-cookie --save
TruckClass
sounds like it were a class of Truck
, I think that recommended solution is to add Impl
suffix. In my opinion the best solution is to contain within implementation name some information, what's going on in that particular implementation (like we have with List
interface and implementations: ArrayList
or LinkedList
), but sometimes you have just one implementation and have to have interface due to remote usage (for example), then (as mentioned at the beginning) Impl
is the solution.
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
Install mysql via homebrew, then you can install mysql python via pip.
pip install MySQL-python
It works for me.
You can use VBSedit software to convert your VBS code to .exe file. You can download free version from Internet and installtion vbsedit applilcation on your system and convert the files to exe format.
Vbsedit is a good application for VBscripter's
Dashboard -> [your app] -> [View Details] -> Settings -> Basic
Try using the TimeRange object in C# to complete your goal.
TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");
bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);
The two functions do vastly different things!
The resize()
method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect the size()
, iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[]
.
The reserve()
method only allocates memory, but leaves it uninitialized. It only affects capacity()
, but size()
will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.
So it depends on what you want. If you want an array of 1000 default items, use resize()
. If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, use reserve()
.
EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where reserve()
makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.
EDIT2: Ad question edit: If you have initial estimate, then reserve()
that estimate. If it turns out to be not enough, just let the vector do it's thing.
If you are on a Mac, the Chrome dev team recommend the 'Network Link Conditioner Tool'
Either:
Xcode > Open Developer Tool > More Developer Tools > Hardware IO Tools for Xcode
Or if you don't want to install Xcode:
Go to the Apple Download Center and search for Hardware IO Tools
You have writer.close();
in your code. So bash receives EOF on its stdin
and exits. Then you get Broken pipe
when trying to read from the stdout
of the defunct bash.
Since you are writing for Python 3.x, you'll want to begin your script with:
#!/usr/bin/env python3
If you use:
#!/usr/bin/env python
It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #! (aka the shebang).
If your scripts just start with:
#! python
Then you can change it to:
#! python3
Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.
The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.
Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.
(function () {
'use strict';
angular.module('app')
.directive('placeholder', function () {
return {
restrict: 'A',
link: function (scope, element, attributes) {
if (element.prop('nodeName') === 'TEXTAREA') {
var placeholderText = attributes.placeholder.trim();
if (placeholderText.length) {
// support for both '\n' symbol and an actual newline in the placeholder element
var placeholderLines = Array.prototype.concat
.apply([], placeholderText.split('\n').map(line => line.split('\\n')))
.map(line => line.trim());
if (placeholderLines.length > 1) {
element.watermark(placeholderLines.join('<br>\n'));
}
}
}
}
};
});
}());
also, you can clone your modal before open ;)
$('#myModal')
.clone()
.modal()
.on('hidden.bs.modal', function(e) {
$(this).remove();
});
This is how I handle it:
class MyComponent extends React.Component{
constructor(props){
super(props);
this._initState = {
a: 1,
b: 2
}
this.state = this._initState;
}
_resetState(){
this.setState(this._initState);
}
}
Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.
Here is how you do it:
$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
.then(function (response) { /* */ })...
Angular takes care of encoding the parameters.
Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData}
is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).
I believe you are having the same problem here.
The sheet must be active before you can select a range on it.
Also, don't omit the sheet name qualifier:
Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select
Or,
With Sheets("BxWsn Simulation")
.Select
.Range("Result").Select
End WIth
which is the same.
The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.
The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.
Usage example:
var config = {
sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
interval: 200, // number = milliseconds for onMouseOver polling interval
over: makeTall, // function = onMouseOver callback (REQUIRED)
timeout: 500, // number = milliseconds delay before onMouseOut
out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )
Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055
To get the content of a url:
try: # Try importing requests first.
import requests
except ImportError:
try: # Try importing Python3 urllib
import urllib.request
except AttributeError: # Now importing Python2 urllib
import urllib
def get_content(url):
try: # Using requests.
return requests.get(url).content # Returns requests.models.Response.
except NameError:
try: # Using Python3 urllib.
with urllib.request.urlopen(index_url) as response:
return response.read() # Returns http.client.HTTPResponse.
except AttributeError: # Using Python3 urllib.
return urllib.urlopen(url).read() # Returns an instance.
It's hard to write Python2 and Python3 and request
dependencies code for the responses because they urlopen()
functions and requests.get()
function return different types:
urllib.request.urlopen()
returns a http.client.HTTPResponse
urllib.urlopen(url)
returns an instance
request.get(url)
returns a requests.models.Response
As far as I understand, you create a Movie class:
class Movie
{
private:
std::string _title;
std::string _director;
int _year;
int _rating;
std::vector<std::string> actors;
};
and having such class, you create a vector instance:
std::vector<Movie*> movies;
so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:
std::vector<shared_ptr<Movie>> movies;
I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.
class enumSeason():
Spring = 0
Summer = 1
Fall = 2
Winter = 3
def __init__(self, Type):
self.value = Type
def __str__(self):
if self.value == enumSeason.Spring:
return 'Spring'
if self.value == enumSeason.Summer:
return 'Summer'
if self.value == enumSeason.Fall:
return 'Fall'
if self.value == enumSeason.Winter:
return 'Winter'
def __eq__(self,y):
return self.value==y.value
Usage:
>>> s = enumSeason(enumSeason.Spring)
>>> print(s)
Spring
Most easy way..
//div[@class="Test"]
Assuming you want to find <div class="Test">
as described.
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
But its still giving an error message in Query Builder. I am using SqlServerCe 2008.
SELECT Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount,
Order_Details.TotalPrice
FROM Order_Products INNER JOIN
Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))
I replaced WHERE with HAVING as said by @powerlord. But still showing an error.
Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]
I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])
It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.
<array>
is the array to look through, <element>
is the value you are looking for, and [fromIndex]
is the index to start from (defaults to 0).
I hope this helps reduce the size of your code!
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
I search the source code inside of Github Repositories with the free Sourcegraph Chrome Extension ... But I Downloaded Chrome First, I knew other browsers support it though, such as - and maybe just only - Firefox.
I skimmed through SourceForge's Chrome Extension Docs and then also I looked at just what I needed for searching for directory names with Github's Search Engine itself, by reading some of Github's Codebase Searching Doc
It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.
For example create a helper method (or class JsonUtils
with static methods) in json_utils.py
:
def get_attribute(data, attribute, default_value):
return data.get(attribute) or default_value
and then use it in your project:
from json_utils import get_attribute
def my_cool_iteration_func(data):
data_to = get_attribute(data, 'to', None)
if not data_to:
return
data_to_data = get_attribute(data_to, 'data', [])
for item in data_to_data:
print('The id is: %s' % get_attribute(item, 'id', 'null'))
IMPORTANT NOTE:
There is a reason I am using data.get(attribute) or default_value
instead of simply data.get(attribute, default_value)
:
{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'
In my applications getting attribute with value 'null' is the same as not getting the attribute at all. If your usage is different, you need to change this.
Use VIEW. The same classes can be mapped to different tables/views using entity name, so you won't even have much of a duplication. Being there, done that, works OK.
Plain JDBC has another hidden problem: it's unaware of Hibernate session cache, so if something got cached till the end of the transaction and not flushed from Hibernate session, JDBC query won't find it. Could be very puzzling sometimes.
When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:
Cannot create an instance of OLE DB provider "(OLEDB provider name)"...
The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."
The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.
This MSDN blog post describes the reason:
MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.
The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.
While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,
Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.
The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.
To make it into a one liner you can try something like:
svn status | cut -d ' ' -f 8 | xargs svn revert
Here's how I got it working:
Include your URL in IE Trusted Sites
run gpedit.msc
(as Admin) and enable the following setting:
gpedit->Local->Computer->Windows Comp->ActiveX Installer->ActiveX installation policy for sites in Trusted Zones
Enabled + Silently,Silently,Prompt
Run gpupdate
Relaunch your Browser
NOTES: Windows 10 EDGE don't have trusted sites, so you have to use IE 11. Lots of folk moaning about that!
When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy()
command.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject
Need to convert it in base64.
JS have btoa() function for it.
For example:
var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);
But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.
Update:
Need to write simple hex to base64 converter:
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
And use it:
img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');
See working example with your hex data on jsfiddle
Try This:)
before:-
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
After:-
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>operation.TestServlet</servlet-class>
</servlet>
You also need to change the DataSource
of the connection string. KELVIN-PC
is the name of your local machine and the sql server is running on the default instance.
If you are sure the the server is running as the default instance, you can always use .
in the DataSource, eg.
connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"
otherwise, you need to specify the name of the instance of the server,
connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"
This feature is called designated initializers. It is an addition to the C99 standard. However, this feature was left out of the C++11. According to The C++ Programming Language, 4th edition, Section 44.3.3.2 (C Features Not Adopted by C++):
A few additions to C99 (compared with C89) were deliberately not adopted in C++:
[1] Variable-length arrays (VLAs); use vector or some form of dynamic array
[2] Designated initializers; use constructors
The C99 grammar has the designated initializers [See ISO/IEC 9899:2011, N1570 Committee Draft - April 12, 2011]
6.7.9 Initialization
initializer:
assignment-expression
{ initializer-list }
{ initializer-list , }
initializer-list:
designation_opt initializer
initializer-list , designationopt initializer
designation:
designator-list =
designator-list:
designator
designator-list designator
designator:
[ constant-expression ]
. identifier
On the other hand, the C++11 does not have the designated initializers [See ISO/IEC 14882:2011, N3690 Committee Draft - May 15, 2013]
8.5 Initializers
initializer:
brace-or-equal-initializer
( expression-list )
brace-or-equal-initializer:
= initializer-clause
braced-init-list
initializer-clause:
assignment-expression
braced-init-list
initializer-list:
initializer-clause ...opt
initializer-list , initializer-clause ...opt
braced-init-list:
{ initializer-list ,opt }
{ }
In order to achieve the same effect, use constructors or initializer lists:
Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.
Personally, I wouldn't use the LIKE
string comparison on the ID field or any other numeric field. It doesn't make sense for a search for ID# "216" to return 16216, 21651, 3216087, 5321668..., and so on and so forth; likewise with salary.
Also, if you want to use prepared statements to prevent SQL injections, you would use a query string like:
SELECT * FROM job WHERE `position` LIKE CONCAT('%', ? ,'%') OR ...
You can use .delay()
before an animation, like this:
$("#myElem").show().delay(5000).fadeOut();
If it's not an animation, use setTimeout()
directly, like this:
$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);
You do the second because .hide()
wouldn't normally be on the animation (fx
) queue without a duration, it's just an instant effect.
Or, another option is to use .delay()
and .queue()
yourself, like this:
$("#myElem").show().delay(5000).queue(function(n) {
$(this).hide(); n();
});
FragmentActivity
is part of the support library, while Activity
is the framework's default class. They are functionally equivalent.
You should always use FragmentActivity
and android.support.v4.app.Fragment
instead of the platform default Activity
and android.app.Fragment
classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
@{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two Pass Through ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three pass through model
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
Try this:
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField textField = new JTextField();
textField.addKeyListener(new Keychecker());
JFrame jframe = new JFrame();
jframe.add(textField);
jframe.setSize(400, 350);
jframe.setVisible(true);
}
class Keychecker extends KeyAdapter {
@Override
public void keyPressed(KeyEvent event) {
char ch = event.getKeyChar();
System.out.println(event.getKeyChar());
}
}
Using plain javascript
var isEmpty = document.getElementById('cartContent').innerHTML === "";
And if you are using jquery it can be done like
var isEmpty = $("#cartContent").html() === "";
A bit OFF-TOPIC, but may help someone for a cleaner HTML... CSS
.common_table{
display:table;
border-collapse:collapse;
border:1px solid grey;
}
.common_table DIV{
display:table-row;
border:1px solid grey;
}
.common_table DIV DIV{
display:table-cell;
}
HTML
<DIV class="common_table">
<DIV><DIV>this is a cell</DIV></DIV>
<DIV><DIV>this is a cell</DIV></DIV>
</DIV>
Works on Chrome and Firefox