How to prevent favicon.ico requests?
You can use .htaccess or server directives to deny access to favicon.ico, but the server will send an access denied reply to the browser and this still slows page access.
You can stop the browser requesting favicon.ico when a user returns to your site, by getting it to stay in the browser cache.
First, provide a small favicon.ico image, could be blank, but as small as possible. I made a black and white one under 200 bytes. Then, using .htaccess or server directives, set the file Expires header a month or two in the future. When the same user comes back to your site it will be loaded from the browser cache and no request will go to your site. No more 404's in the server logs too.
If you have control over a complete Apache server or maybe a virtual server you can do this:-
If the server document root is say /var/www/html then add this to /etc/httpd/conf/httpd.conf:-
Alias /favicon.ico "/var/www/html/favicon.ico"
<Directory "/var/www/html">
<Files favicon.ico>
ExpiresActive On
ExpiresDefault "access plus 1 month"
</Files>
</Directory>
Then a single favicon.ico will work for all the virtual hosted sites since you are aliasing it. It will be drawn from the browser cache for a month after the users visit.
For .htaccess this is reported to work (not checked by me):-
AddType image/x-icon .ico
ExpiresActive On
ExpiresByType image/x-icon "access plus 1 month"
Printing prime numbers from 1 through 100
I check if a number is prime or not with the following code( of course using sqrt ):
bool IsPrime(const unsigned int x)
{
const unsigned int TOP
= static_cast<int>(
std::sqrt( static_cast<double>( x ) )
) + 1;
for ( int i=2; i != TOP; ++i )
{
if (x % i == 0) return false;
}
return true;
}
I use this method to determine the primes:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cmath>
void initialize( unsigned int *, const unsigned int );
void show_list( const unsigned int *, const unsigned int );
void criba( unsigned int *, const unsigned int );
void setItem ( unsigned int *, const unsigned int, const unsigned int );
bool IsPrime(const unsigned int x)
{
const unsigned int TOP
= static_cast<int>(
std::sqrt( static_cast<double>( x ) )
) + 1;
for ( int i=2; i != TOP; ++i )
{
if (x % i == 0) return false;
}
return true;
}
int main()
{
unsigned int *l;
unsigned int n;
cout << "Ingrese tope de criba" << endl;
cin >> n;
l = new unsigned int[n];
initialize( l, n );
cout << "Esta es la lista" << endl;
show_list( l, n );
criba( l, n );
cout << "Estos son los primos" << endl;
show_list( l, n );
}
void initialize( unsigned int *l, const unsigned int n)
{
for( int i = 0; i < n - 1; i++ )
*( l + i ) = i + 2;
}
void show_list( const unsigned int *l, const unsigned int n)
{
for( int i = 0; i < n - 1; i++ )
{
if( *( l + i ) != 0)
cout << l[i] << " - ";
}
cout << endl;
}
void setItem( unsigned int *l, const unsigned int n, const unsigned int p)
{
unsigned int i = 2;
while( p * i <= n)
{
*( l + (i * p - 2) ) = 0;
i++;
}
}
void criba( unsigned int *l, const unsigned int n)
{
for( int i = 0; i * i <= n ; i++ )
if( IsPrime ( *( l + i) ) )
setItem( l, n, *(l + i) );
}
Eclipse executable launcher error: Unable to locate companion shared library
I encountered this error with the Eclipse 4.10 installer. We had failed to complete the install correctly due to platform security settings and attempted to uninstall but had to do it by hand since no uninstaller was introduced during the failed install. We suspected this corrupted the end result - even after re-installing.
The solution was to use the JVM to launch Eclipse and bypass the launcher executable entirely. The following command successfully launches Eclipse 4.10 (some parameters will change based on the version of Eclipse):
%JDK190%\bin\javaw.exe -jar C:\<fully_qualified_path_to_eclipse>\Eclipse410\plugins\org.eclipse.equinox.launcher_1.5.200.v20180922-1751.jar -clean -showsplash
After using this command/shortcut to launch Eclipse we had no further errors with Eclipse itself but we weren't able to use the EXE launcher in the future. Even after a year of using this version, the launcher continues to display this same error.
To be clear, you'll have to modify your javaw.exe
command to match your system specifications on MS Windows.
No Multiline Lambda in Python: Why not?
Here's a more interesting implementation of multi line lambdas. It's not possible to achieve because of how python use indents as a way to structure code.
But luckily for us, indent formatting can be disabled using arrays and parenthesis.
As some already pointed out, you can write your code as such:
lambda args: (expr1, expr2,... exprN)
In theory if you're guaranteed to have evaluation from left to right it would work but you still lose values being passed from one expression to an other.
One way to achieve that which is a bit more verbose is to have
lambda args: [lambda1, lambda2, ..., lambdaN]
Where each lambda receives arguments from the previous one.
def let(*funcs):
def wrap(args):
result = args
for func in funcs:
if not isinstance(result, tuple):
result = (result,)
result = func(*result)
return result
return wrap
This method let you write something that is a bit lisp/scheme like.
So you can write things like this:
let(lambda x, y: x+y)((1, 2))
A more complex method could be use to compute the hypotenuse
lst = [(1,2), (2,3)]
result = map(let(
lambda x, y: (x**2, y**2),
lambda x, y: (x + y) ** (1/2)
), lst)
This will return a list of scalar numbers so it can be used to reduce multiple values to one.
Having that many lambda is certainly not going to be very efficient but if you're constrained it can be a good way to get something done quickly then rewrite it as an actual function later.
Does Hive have a String split function?
Just a clarification on the answer given by Bkkbrad.
I tried this suggestion and it did not work for me.
For example,
split('aa|bb','\\|')
produced:
["","a","a","|","b","b",""]
But,
split('aa|bb','[|]')
produced the desired result:
["aa","bb"]
Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.
For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html
@synthesize vs @dynamic, what are the differences?
here is example of @dynamic
#import <Foundation/Foundation.h>
@interface Book : NSObject
{
NSMutableDictionary *data;
}
@property (retain) NSString *title;
@property (retain) NSString *author;
@end
@implementation Book
@dynamic title, author;
- (id)init
{
if ((self = [super init])) {
data = [[NSMutableDictionary alloc] init];
[data setObject:@"Tom Sawyer" forKey:@"title"];
[data setObject:@"Mark Twain" forKey:@"author"];
}
return self;
}
- (void)dealloc
{
[data release];
[super dealloc];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
NSString *sel = NSStringFromSelector(selector);
if ([sel rangeOfString:@"set"].location == 0) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
} else {
return [NSMethodSignature signatureWithObjCTypes:"@@:"];
}
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
NSString *key = NSStringFromSelector([invocation selector]);
if ([key rangeOfString:@"set"].location == 0) {
key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
NSString *obj;
[invocation getArgument:&obj atIndex:2];
[data setObject:obj forKey:key];
} else {
NSString *obj = [data objectForKey:key];
[invocation setReturnValue:&obj];
}
}
@end
int main(int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Book *book = [[Book alloc] init];
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
book.title = @"1984";
book.author = @"George Orwell";
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]);
[book release];
[pool release];
return 0;
}
Is it possible to format an HTML tooltip (title attribute)?
No. But there are other options out there like Overlib, and jQuery that allow you this freedom.
Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).
How can I style even and odd elements?
<ul class="names" id="names_list">
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="1">Ashwin Nair</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="2">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="3">Chirag</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="4">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="15">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="16">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="17">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="18">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="19">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="188">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="111">Bhavesh</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="122">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="133">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="144">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="199">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="156">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="174">Ashwin</li></a>
</ul>
$(document).ready(function(){
var a=0;
var ac;
var ac2;
$(".names li").click(function(){
var b=0;
if(a==0)
{
var accc="#"+ac2;
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
$(this).css({
"background":"#d3b730",
"color":"#000",
});
ac=$(this).attr('class');
ac2=$(this).attr('id');
a=1;
}
else{
var accc="#"+ac2;
//alert(accc);
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
a=0;
ac=$(this).attr('class');
ac2=$(this).attr('id');
$(this).css({
"background":"#d3b730",
"color":"#000",
});
}
});
Deploying my application at the root in Tomcat
Adding to @Dima's answer, if you're using maven
to build your package, you can tell it to set your WAR file name to ROOT
in pom.xml
:
<build>
<finalName>ROOT</finalName>
</build>
By default, tomcat
will deploy ROOT.war
webapp into root context (/
).
How to get the selected index of a RadioGroup in Android
Here is a Kotlin extension to get the correct position even if your group contains a TextView or any non-RadioButton.
fun RadioGroup.getCheckedRadioButtonPosition(): Int {
val radioButtonId = checkedRadioButtonId
return children.filter { it is RadioButton }
.mapIndexed { index: Int, view: View ->
index to view
}.firstOrNull {
it.second.id == radioButtonId
}?.first ?: -1
}
How do I use hexadecimal color strings in Flutter?
You can use this package from_css_color to get Color
out of a hex string. It supports both three and six digit RGB hex notation.
Color color = fromCSSColor('#ff00aa')
For optimisation sake create Color instance once for each color and store it somewhere for later usage.
How to apply Hovering on html area tag?
What I did was to create a canvas element that I then position in front of the image map. Then, whenever an area is moused-over, I call a func that gets the coord string for that shape and the shape-type. If it's a poly I use the coords to draw an outline on the canvas. If it's a rect I draw a rect outline. You could easily add code to deal with circles.
You could also set the opacity of the canvas to less than 100% before filling the poly/rect/circle. You could also change the reliance on a global for the canvas's context - this would mean you could deal with more than 1 image-map on the same page.
<!DOCTYPE html>
<html>
<head>
<script>
// stores the device context of the canvas we use to draw the outlines
// initialized in myInit, used in myHover and myLeave
var hdc;
// shorthand func
function byId(e){return document.getElementById(e);}
// takes a string that contains coords eg - "227,307,261,309, 339,354, 328,371, 240,331"
// draws a line from each co-ord pair to the next - assumes starting point needs to be repeated as ending point.
function drawPoly(coOrdStr)
{
var mCoords = coOrdStr.split(',');
var i, n;
n = mCoords.length;
hdc.beginPath();
hdc.moveTo(mCoords[0], mCoords[1]);
for (i=2; i<n; i+=2)
{
hdc.lineTo(mCoords[i], mCoords[i+1]);
}
hdc.lineTo(mCoords[0], mCoords[1]);
hdc.stroke();
}
function drawRect(coOrdStr)
{
var mCoords = coOrdStr.split(',');
var top, left, bot, right;
left = mCoords[0];
top = mCoords[1];
right = mCoords[2];
bot = mCoords[3];
hdc.strokeRect(left,top,right-left,bot-top);
}
function myHover(element)
{
var hoveredElement = element;
var coordStr = element.getAttribute('coords');
var areaType = element.getAttribute('shape');
switch (areaType)
{
case 'polygon':
case 'poly':
drawPoly(coordStr);
break;
case 'rect':
drawRect(coordStr);
}
}
function myLeave()
{
var canvas = byId('myCanvas');
hdc.clearRect(0, 0, canvas.width, canvas.height);
}
function myInit()
{
// get the target image
var img = byId('img-imgmap201293016112');
var x,y, w,h;
// get it's position and width+height
x = img.offsetLeft;
y = img.offsetTop;
w = img.clientWidth;
h = img.clientHeight;
// move the canvas, so it's contained by the same parent as the image
var imgParent = img.parentNode;
var can = byId('myCanvas');
imgParent.appendChild(can);
// place the canvas in front of the image
can.style.zIndex = 1;
// position it over the image
can.style.left = x+'px';
can.style.top = y+'px';
// make same size as the image
can.setAttribute('width', w+'px');
can.setAttribute('height', h+'px');
// get it's context
hdc = can.getContext('2d');
// set the 'default' values for the colour/width of fill/stroke operations
hdc.fillStyle = 'red';
hdc.strokeStyle = 'red';
hdc.lineWidth = 2;
}
</script>
<style>
body
{
background-color: gray;
}
canvas
{
pointer-events: none; /* make the canvas transparent to the mouse - needed since canvas is position infront of image */
position: absolute;
}
</style>
<title></title>
</head>
<body onload='myInit()'>
<canvas id='myCanvas'></canvas> <!-- gets re-positioned in myInit(); -->
<center>
<img src='http://dailyaeen.com.pk/epaper/wp-content/uploads/2012/09/27+Sep+2012-1.jpg?1349003469874' usemap='#imgmap_css_container_imgmap201293016112' class='imgmap_css_container' title='imgmap201293016112' alt='imgmap201293016112' id='img-imgmap201293016112' />
<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
<area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
<area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
<area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
<area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
<area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
<area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
<area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>
</center>
</body>
</html>
Comparing two joda DateTime instances
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
How to split a comma-separated value to columns
This function is most fast:
CREATE FUNCTION dbo.F_ExtractSubString
(
@String VARCHAR(MAX),
@NroSubString INT,
@Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @St INT = 0, @End INT = 0, @Ret VARCHAR(MAX)
SET @String = @String + @Separator
WHILE CHARINDEX(@Separator, @String, @End + 1) > 0 AND @NroSubString > 0
BEGIN
SET @St = @End + 1
SET @End = CHARINDEX(@Separator, @String, @End + 1)
SET @NroSubString = @NroSubString - 1
END
IF @NroSubString > 0
SET @Ret = ''
ELSE
SET @Ret = SUBSTRING(@String, @St, @End - @St)
RETURN @Ret
END
GO
Example usage:
SELECT dbo.F_ExtractSubString(COLUMN, 1, ', '),
dbo.F_ExtractSubString(COLUMN, 2, ', '),
dbo.F_ExtractSubString(COLUMN, 3, ', ')
FROM TABLE
VBA: Counting rows in a table (list object)
You can use this:
Range("MyTable[#Data]").Rows.Count
You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases.
Use this to test for an empty table:
If WorksheetFunction.CountA(Range("MyTable[#Data]"))
Android Whatsapp/Chat Examples
If you are looking to create an instant messenger for Android, this code should get you started somewhere.
Excerpt from the source :
This is a simple IM application runs on Android, application makes
http request to a server, implemented in php and mysql, to
authenticate, to register and to get the other friends' status and
data, then it communicates with other applications in other devices by
socket interface.
EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.
There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!
*UPDATE : * Scringo services will be closed down on 15 February, 2015.
Apply style to parent if it has child with css
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
Move an array element from one array position to another
Array.prototype.moveUp = function (value, by) {
var index = this.indexOf(value),
newPos = index - (by || 1);
if (index === -1)
throw new Error("Element not found in array");
if (newPos < 0)
newPos = 0;
this.splice(index, 1);
this.splice(newPos, 0, value);
};
Array.prototype.moveDown = function (value, by) {
var index = this.indexOf(value),
newPos = index + (by || 1);
if (index === -1)
throw new Error("Element not found in array");
if (newPos >= this.length)
newPos = this.length;
this.splice(index, 1);
this.splice(newPos, 0, value);
};
var arr = ['banana', 'curyWurst', 'pc', 'remembaHaruMembaru'];
alert('withiout changes= '+arr[0]+' ||| '+arr[1]+' ||| '+arr[2]+' ||| '+arr[3]);
arr.moveDown(arr[2]);
alert('third word moved down= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
arr.moveUp(arr[2]);
alert('third word moved up= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
http://plnkr.co/edit/JaiAaO7FQcdPGPY6G337?p=preview
Python 2.6: Class inside a Class?
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
Change the Textbox height?
So after having the same issue with not being able to adjust height in text box, Width adjustment is fine but height never adjusted with the above suggestions (at least for me), I was finally able to take make it happen. As mentioned above, the issue appeared to be centered around a default font size setting in my text box and the behavior of the text box auto sizing around it. The default font size was tiny. Hence why trying to force the height or even turn off autosizing failed to fix the issue for me.
Set the Font properties to the size of your liking and then height change will kick in around the FONT size, automatically. You can still manually set your text box width. Below is snippet I added that worked for me.
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(60,300)
$textBox.Size = New-Object System.Drawing.Size(600,80)
$textBox.Font = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$textBox.Form.Font = $textbox.Font
Please note the Height value in '$textBox.Size = New-Object System.Drawing.Size(600,80)' is being ignored and the FONT size is actually controlling the height of the text box by autosizing around that font size.
Generating (pseudo)random alpha-numeric strings
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
$str = bin2hex(random_bytes(32)); // 64 character string returned
How to simulate a button click using code?
Starting with API15, you can use also callOnClick()
that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.
link button property to open in new tab?
try by Adding following onClientClick event.
OnClientClick="aspnetForm.target ='_blank';"
so on click it will call Javascript function an will open respective link in News tab.
<asp:LinkButton id="lbnkVidTtile1" OnClientClick="aspnetForm.target ='_blank';" runat="Server" CssClass="bodytext" Text='<%# Eval("newvideotitle") %>' />
PHP How to find the time elapsed since a date time?
Most of the answers seem focused around converting the date from a string to time. It seems you're mostly thinking about getting the date into the '5 days ago' format, etc.. right?
This is how I'd go about doing that:
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
I haven't tested that, but it should work.
The result would look like
event happened 4 days ago
or
event happened 1 minute ago
cheers
Can scrapy be used to scrape dynamic content from websites that are using AJAX?
how can scrapy be used to scrape this dynamic data so that I can use
it?
I wonder why no one has posted the solution using Scrapy only.
Check out the blog post from Scrapy team SCRAPING INFINITE SCROLLING PAGES
. The example scraps http://spidyquotes.herokuapp.com/scroll website which uses infinite scrolling.
The idea is to use Developer Tools of your browser and notice the AJAX requests, then based on that information create the requests for Scrapy.
import json
import scrapy
class SpidyQuotesSpider(scrapy.Spider):
name = 'spidyquotes'
quotes_base_url = 'http://spidyquotes.herokuapp.com/api/quotes?page=%s'
start_urls = [quotes_base_url % 1]
download_delay = 1.5
def parse(self, response):
data = json.loads(response.body)
for item in data.get('quotes', []):
yield {
'text': item.get('text'),
'author': item.get('author', {}).get('name'),
'tags': item.get('tags'),
}
if data['has_next']:
next_page = data['page'] + 1
yield scrapy.Request(self.quotes_base_url % next_page)
Can lambda functions be templated?
C++11 lambdas can't be templated as stated in other answers but decltype()
seems to help when using a lambda within a templated class or function.
#include <iostream>
#include <string>
using namespace std;
template<typename T>
void boring_template_fn(T t){
auto identity = [](decltype(t) t){ return t;};
std::cout << identity(t) << std::endl;
}
int main(int argc, char *argv[]) {
std::string s("My string");
boring_template_fn(s);
boring_template_fn(1024);
boring_template_fn(true);
}
Prints:
My string
1024
1
I've found this technique is helps when working with templated code but realize it still means lambdas themselves can't be templated.
Add CSS3 transition expand/collapse
OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.
<script>
function dostuff() {
if (document.getElementById('MyBox').style.height == "0px") {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;");
}
else {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;");
}
}
</script>
<div id="MyBox" style="height: 0px; width: 0px;">
</div>
<input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
IOS 7 Navigation Bar text and arrow color
Vin's answer worked great for me. Here is the same solution for C# developers using Xamarin.iOS/MonoTouch:
var navigationBar = NavigationController.NavigationBar; //or another reference
navigationBar.BarTintColor = UIColor.Blue;
navigationBar.TintColor = UIColor.White;
navigationBar.SetTitleTextAttributes(new UITextAttributes() { TextColor = UIColor.White });
navigationBar.Translucent = false;
How do I concatenate strings?
To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.
The nicest I have seen is using the join
method on an array:
fn main() {
let a = "Hello";
let b = "world";
let result = [a, b].join("\n");
print!("{}", result);
}
Depending on your use case you might also prefer more control:
fn main() {
let a = "Hello";
let b = "world";
let result = format!("{}\n{}", a, b);
print!("{}", result);
}
There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.
What is the use of the JavaScript 'bind' method?
A bind implementation might look something like so:
Function.prototype.bind = function () {
const self = this;
const args = [...arguments];
const context = args.shift();
return function () {
return self.apply(context, args.concat([...arguments]));
};
};
The bind function can take any number of arguments and return a new function.
The new function will call the original function using the JS Function.prototype.apply
method.
The apply
method will use the first argument passed to the target function as its context (this
), and the second array argument of the apply
method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).
An example can look something like so:
_x000D_
_x000D_
function Fruit(emoji) {_x000D_
this.emoji = emoji;_x000D_
}_x000D_
_x000D_
Fruit.prototype.show = function () {_x000D_
console.log(this.emoji);_x000D_
};_x000D_
_x000D_
const apple = new Fruit('');_x000D_
const orange = new Fruit('');_x000D_
_x000D_
apple.show(); // _x000D_
orange.show(); // _x000D_
_x000D_
const fruit1 = apple.show;_x000D_
const fruit2 = apple.show.bind();_x000D_
const fruit3 = apple.show.bind(apple);_x000D_
const fruit4 = apple.show.bind(orange);_x000D_
_x000D_
fruit1(); // undefined_x000D_
fruit2(); // undefined_x000D_
fruit3(); // _x000D_
fruit4(); //
_x000D_
_x000D_
_x000D_
Make a dictionary in Python from input values
n = int(input()) #n is the number of items you want to enter
d ={}
for i in range(n):
text = input().split() #split the input text based on space & store in the list 'text'
d[text[0]] = text[1] #assign the 1st item to key and 2nd item to value of the dictionary
print(d)
INPUT:
3
A1023 CRT
A1029 Regulator
A1030 Therm
NOTE: I have added an extra line for each input for getting each input on individual lines on this site. As placing without an extra line creates a single line.
OUTPUT:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
Listview Scroll to the end of the list after updating the list
To get this in a ListFragment:
getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
getListView().setStackFromBottom(true);`
Added this answer because if someone do a google search for same problem with ListFragment he just finds this..
Regards
Check if value exists in the array (AngularJS)
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
What is the difference between a strongly typed language and a statically typed language?
One does not imply the other. For a language to be statically typed it means that the types of all variables are known or inferred at compile time.
A strongly typed language does not allow you to use one type as another. C is a weakly typed language and is a good example of what strongly typed languages don't allow. In C you can pass a data element of the wrong type and it will not complain. In strongly typed languages you cannot.
TempData keep() vs peek()
TempData is also a dictionary object that stays for the time of an
HTTP Request. So, TempData can be used to maintain data between one
controller action to the other controller action.
TempData is used to check the null values each time. TempData contain
two method keep() and peek() for maintain data state from one
controller action to others.
When TempDataDictionary object is read, At the end of request marks
as deletion to current read object.
The keep() and peek() method is used to read the data without deletion
the current read object.
You can use Peek() when you always want to hold/prevent the value for
another request. You can use Keep() when prevent/hold the value
depends on additional logic.
Overloading in TempData.Peek() & TempData.Keep() as given below.
TempData.Keep() have 2 overloaded methods.
void keep() : That menace all the data not deleted on current request completion.
void keep(string key) : persist the specific item in TempData with help of name.
TempData.Peek() no overloaded methods.
- object peek(string key) : return an object that contain items with specific key without making key for deletion.
Example for return type of TempData.Keep() & TempData.Peek() methods as given below.
public void Keep(string key) {
_retainedKeys.Add(key); }
public object Peek(string key) {
object value = values;
return value; }
How do you fix the "element not interactable" exception?
For the html code:
test.html
<button class="dismiss" onclick="alert('hello')">
<string for="exit">Dismiss</string>
</button>
the below python code worked for me. You can just try it.
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()
How to remove underline from a name on hover
You can assign an id to the specific link and add CSS. See the steps below:
1.Add an id of your choice (must be a unique name; can only start with text, not a number):
<a href="/abc/xyz" id="smallLinkButton">def</a>
Then add the necessary CSS as follows:
#smallLinkButton:hover,active,visited{
text-decoration: none;
}
PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers
In My Aws Windows I Solved it
and steps are
- Open "C:\ProgramData\MySQL\MySQL Server 8.0"
- Open My.ini
- Find "[mysql]"
- After "no-beep=" Brake Line and insert "default-character-set=utf8"
- Find "[mysqld]"
- Insert "collation-server = utf8_unicode_ci"
- Insert "character-set-server = utf8"
example
...
# socket=MYSQL
port=3306
[mysql]
no-beep=
default-character-set=utf8
# default-character-set=
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.=
#
# server_type=2
[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
# The next three options are mutually exclusive to SERVER_PORT below.
# skip-networking=
# enable-named-pipe=
# shared-memory=
...
Python Progress Bar
A very simple approach:
def progbar(count: int) -> None:
for i in range(count):
print(f"[{i*'#'}{(count-1-i)*' '}] - {i+1}/{count}", end="\r")
yield i
print('\n')
And the usage:
from time import sleep
for i in progbar(10):
sleep(0.2) #whatever task you need to do
Android Studio - Emulator - eglSurfaceAttrib not implemented
I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!
How to append something to an array?
If arr
is an array, and val
is the value you wish to add use:
arr.push(val);
E.g.
_x000D_
_x000D_
var arr = ['a', 'b', 'c'];_x000D_
arr.push('d');_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_
How to change font size in a textbox in html
To actually do it in HTML with inline CSS (not with an external CSS style sheet)
<input type="text" style="font-size: 44pt">
A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html>
or <body>
tag, and such is appropriate there.
Build not visible in itunes connect
I have faced the same issue, once I upload build is not showing in AppStore Connect
even I did not get any issue mail from apple. So I just wait for a day and that build begins visible on AppStore Connect
after a day. It is a weird issue apple team have to look into it.
Happy coding. :)
How to load local html file into UIWebView
In Swift 2.0, @user478681's answer might look like this:
let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
let HTMLString: NSString?
do {
HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!, encoding: NSUTF8StringEncoding)
} catch {
HTMLString = nil
}
myWebView.loadHTMLString(HTMLString as! String, baseURL: nil)
Append a tuple to a list - what's the difference between two ways?
It has nothing to do with append
. tuple(3, 4)
all by itself raises that error.
The reason is that, as the error message says, tuple
expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.
Just do (3, 4)
to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.
How to properly use jsPDF library
first, you have to create a handler.
var specialElementHandlers = {
'#editor': function(element, renderer){
return true;
}
};
then write this code in click event:
doc.fromHTML($('body').get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
var pdfOutput = doc.output();
console.log(">>>"+pdfOutput );
assuming you've already declared doc variable.
And Then you have save this pdf file using File-Plugin.
how to download file in react js
Triggering browser download from front-end is not reliable.
What you should do is, create an endpoint that when called, will provide the correct response headers, thus triggering the browser download.
Front-end code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser.
The response headers you need to look at are probably Content-Type
and Content-Disposition
. You should check this answer for more detailed explanation.
How to get the dimensions of a tensor (in TensorFlow) at graph construction time?
I see most people confused about tf.shape(tensor)
and tensor.get_shape()
Let's make it clear:
tf.shape
tf.shape
is used for dynamic shape. If your tensor's shape is changable, use it.
An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:
new_height = tf.shape(image)[0] / 2
tensor.get_shape
tensor.get_shape
is used for fixed shapes, which means the tensor's shape can be deduced in the graph.
Conclusion:
tf.shape
can be used almost anywhere, but t.get_shape
only for shapes can be deduced from graph.
How can I get a list of Git branches, ordered by most recent commit?
I had the same problem, so I wrote a Ruby gem called Twig. It lists branches in chronological order (newest first), and can also let you set a max age so that you don't list all branches (if you have a lot of them). For example:
$ twig
issue status todo branch
----- ------ ---- ------
2013-01-26 18:00:21 (7m ago) 486 In progress Rebase optimize-all-the-things
2013-01-26 16:49:21 (2h ago) 268 In progress - whitespace-all-the-things
2013-01-23 18:35:21 (3d ago) 159 Shipped Test in prod * refactor-all-the-things
2013-01-22 17:12:09 (4d ago) - - - development
2013-01-20 19:45:42 (6d ago) - - - master
It also lets you store custom properties for each branch, e.g., ticket id, status, todos, and filter the list of branches according to these properties. More info: http://rondevera.github.io/twig/
Extract matrix column values by matrix column name
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")
> myMatrix
A B C D E
A 1 3 5 7 9
B 2 4 6 8 10
> myMatrix["A", "A"]
[1] 1
> myMatrix["A", ]
A B C D E
1 3 5 7 9
> myMatrix[, "A"]
A B
1 2
How do I style a <select> dropdown with only CSS?
label {
position: relative;
display: inline-block;
}
select {
display: inline-block;
padding: 4px 3px 5px 5px;
width: 150px;
outline: none;
color: black;
border: 1px solid #C8BFC4;
border-radius: 4px;
box-shadow: inset 1px 1px 2px #ddd8dc;
background-color: lightblue;
}
This uses a background color for select elements and I removed the image..
Usage of MySQL's "IF EXISTS"
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
Function in JavaScript that can be called only once
Tossing my hat in the ring for fun, added advantage of memoizing
const callOnce = (fn, i=0, memo) => () => i++ ? memo : (memo = fn());
// usage
const myExpensiveFunction = () => { return console.log('joe'),5; }
const memoed = callOnce(myExpensiveFunction);
memoed(); //logs "joe", returns 5
memoed(); // returns 5
memoed(); // returns 5
...
JQuery get data from JSON array
try this
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
Pylint "unresolved import" error in Visual Studio Code
If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py
How do I convert a PDF document to a preview image in PHP?
For those who don't have ImageMagick for whatever reason, GD functions will also work, in conjunction with GhostScript. Run the ghostscript command with exec()
to convert a PDF to JPG, and manipulate the resulting file with imagecreatefromjpeg()
.
Run the ghostscript command:
exec('gs -dSAFER -dBATCH -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r300 -sOutputFile=whatever.jpg input.pdf')
To manipulate, create a new placeholder image, $newimage = imagecreatetruecolor(...)
, and bring in the current image. $image = imagecreatefromjpeg('whatever.jpg')
, and then you can use imagecopyresampled()
to change the size, or any number of other built-in, non-imagemagick
commands
Working with a List of Lists in Java
The example provided by @tster shows how to create a list of list. I will provide an example for iterating over such a list.
Iterator<List<String>> iter = listOlist.iterator();
while(iter.hasNext()){
Iterator<String> siter = iter.next().iterator();
while(siter.hasNext()){
String s = siter.next();
System.out.println(s);
}
}
Stratified Train/Test-split in scikit-learn
#train_size is 1 - tst_size - vld_size
tst_size=0.15
vld_size=0.15
X_train_test, X_valid, y_train_test, y_valid = train_test_split(df.drop(y, axis=1), df.y, test_size = vld_size, random_state=13903)
X_train_test_V=pd.DataFrame(X_train_test)
X_valid=pd.DataFrame(X_valid)
X_train, X_test, y_train, y_test = train_test_split(X_train_test, y_train_test, test_size=tst_size, random_state=13903)
Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87
In addition to installing the repository and the SDK packages one should be aware that the version number changes periodically. A simple solution at this point is to replace the specific version number with a plus (+) symbol.
compile 'com.google.android.gms:play-services:+'
Google instructions indicate that one should be sure to upgrade the version numbers, however adding the plus deals with the changes in versioning. Also note that when building in Android Studio a message will appear in the status line when a new version is available.
One can view the available versions of play services by drilling down on the correct repository path:
References
This site also has instructions for Eclipse, and other IDE's.
Leave menu bar fixed on top when scrolled
In this example, you may show your menu centered.
HTML
<div id="main-menu-container">
<div id="main-menu">
//your menu
</div>
</div>
CSS
.f-nav{ /* To fix main menu container */
z-index: 9999;
position: fixed;
left: 0;
top: 0;
width: 100%;
}
#main-menu-container {
text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
display: inline-block;
width: 1024px; /* Your menu's width */
}
JS
$("document").ready(function($){
var nav = $('#main-menu-container');
$(window).scroll(function () {
if ($(this).scrollTop() > 125) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
});
Eclipse error: "The import XXX cannot be resolved"
I didn't understand the reasoning behind this but this solved the same problem I was facing. You may require these steps before executing steps mentioned in above solutions (Clean all projects and Build automatically).
right click project -> Properties -> Project Facets -> select Java -> Apply
How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"
Look in HTML output for actual client ID
You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id
as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.
Note: if it happens to contain iteration index like :0:
, :1:
, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.
Memorize NamingContainer
components and always give them a fixed ID
If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer
parent, then just reference its own ID.
<h:form id="form">
<p:commandLink update="result"> <!-- OK! -->
<h:panelGroup id="result" />
</h:form>
If it's not inside the same NamingContainer
, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer
separator character, which is by default :
.
<h:form id="form">
<p:commandLink update="result"> <!-- FAIL! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
<p:commandLink update=":result"> <!-- OK! -->
</h:form>
<h:panelGroup id="result" />
<h:form id="form">
<p:commandLink update=":result"> <!-- FAIL! -->
</h:form>
<h:form id="otherform">
<h:panelGroup id="result" />
</h:form>
<h:form id="form">
<p:commandLink update=":otherform:result"> <!-- OK! -->
</h:form>
<h:form id="otherform">
<h:panelGroup id="result" />
</h:form>
NamingContainer
components are for example <h:form>
, <h:dataTable>
, <p:tabView>
, <cc:implementation>
(thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX
format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler
may be helpful in this during development.
If you know to find the javadoc of the UIComponent
in question, then you can also just check in there whether it implements the NamingContainer
interface or not. For example, the HtmlForm
(the UIComponent
behind <h:form>
tag) shows it implements NamingContainer
, but the HtmlPanelGroup
(the UIComponent
behind <h:panelGroup>
tag) does not show it, so it does not implement NamingContainer
. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.
Solving your problem
So in your case of:
<p:tabView id="tabs"><!-- This is a NamingContainer -->
<p:tab id="search"><!-- This is NOT a NamingContainer -->
<h:form id="insTable"><!-- This is a NamingContainer -->
<p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
<h:panelGrid id="display">
The generated HTML output of <h:panelGrid id="display">
looks like this:
<table id="tabs:insTable:display">
You need to take exactly that id
as client ID and then prefix with :
for usage in update
:
<p:commandLink update=":tabs:insTable:display">
Referencing outside include/tagfile/composite
If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer()
like so:
<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">
Or, if this command link is inside a composite component and the target is outside it:
<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">
Or, if both the command link and target are inside same composite component:
<p:commandLink update=":#{cc.clientId}:display">
See also Get id of parent naming container in template for in render / update attribute
How does it work under the covers
This all is specified as "search expression" in the UIComponent#findComponent()
javadoc:
A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent
, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar
character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:
- Identify the
UIComponent
that will be the base for searching, by stopping as soon as one of the following conditions is met:
- If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root
UIComponent
of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
- Otherwise, if this
UIComponent
is a NamingContainer
it will serve as the basis.
- Otherwise, search up the parents of this component. If a
NamingContainer
is encountered, it will be the base.
- Otherwise (if no
NamingContainer
is encountered) the root UIComponent
will be the base.
- The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
- If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base
UIComponent
(except that if a descendant NamingContainer
is found, its own facets and children are not searched).
- If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a
NamingContainer
by the rules in the previous bullet point. Then, the findComponent()
method of this NamingContainer
will be called, passing the remainder of the search expression.
Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".
"reRender" uses UIComponent.findComponent()
algorithm (with some additional exceptions) to find the component in the component tree.
Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :
) are not only searched in the context of the closest parent NamingContainer
, but also in all other NamingContainer
components in the same view (which is a relatively expensive job by the way).
Never use prependId="false"
If this all still doesn't work, then verify if you aren't using <h:form prependId="false">
. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.
Referencing specific iteration round of iterating components
It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat>
and <h:dataTable>
like so:
<h:form id="form">
<ui:repeat id="list" value="#{['one','two','three']}" var="item">
<h:outputText id="item" value="#{item}" /><br/>
</ui:repeat>
<h:commandButton value="Update second item">
<f:ajax render=":form:list:1:item" />
</h:commandButton>
</h:form>
However, since Mojarra 2.2.5 the <f:ajax>
started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).
This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>
.
When using PrimeFaces, consider Search Expressions or Selectors
PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:
@this
: current component
@form
: parent UIForm
@all
: entire document
@none
: nothing
PrimeFaces has enhanced this with new keywords and composite expression support:
@parent
: parent component
@namingcontainer
: parent UINamingContainer
@widgetVar(name)
: component as identified by given widgetVar
You can also mix those keywords in composite expressions such as @form:@parent
, @this:@parent:@parent
, etc.
PrimeFaces Selectors (PFS) as in @(.someclass)
allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="@(.myClass)" work?
Databound drop down list - initial value
To select a value from the dropdown use the index like this:
if we have the
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
you would use :
DropDownList1.Items[DropDownList1.SelectedIndex].Value
this would return the value for the selected index.
C++: constructor initializer for arrays
There is no way. You need a default constructor for array members and it will be called, afterwards, you can do any initialization you want in the constructor.
Adding Multiple Values in ArrayList at a single index
You can pass an object which is refering to all the values at a particular index.
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<connect> a=new ArrayList<connect>();
a.add(new connect(100,100,100,100,100));
System.out.println(a.get(0).p1);
System.out.println(a.get(0).p2);
System.out.println(a.get(0).p3);
}
}
class connect
{
int p1,p2,p3,p4,p5;
connect(int a,int b,int c,int d,int e)
{
this.p1=a;
this.p2=b;
this.p3=c;
this.p4=d;
this.p5=e;
}
}
Later to get a particular value at a specific index, you can do this:
a.get(0).p1;
a.get(0).p2;
a.get(0).p3;.............
and so on.
<Django object > is not JSON serializable
First I added a to_dict method to my model ;
def to_dict(self):
return {"name": self.woo, "title": self.foo}
Then I have this;
class DjangoJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, models.Model):
return obj.to_dict()
return JSONEncoder.default(self, obj)
dumps = curry(dumps, cls=DjangoJSONEncoder)
and at last use this class to serialize my queryset.
def render_to_response(self, context, **response_kwargs):
return HttpResponse(dumps(self.get_queryset()))
This works quite well
private final static attribute vs private final attribute
A static
variable stays in the memory for the entire lifetime of the application, and is initialised during class loading. A non-static
variable is being initialised each time you construct a new
object. It's generally better to use:
private static final int NUMBER = 10;
Why? This reduces the memory footprint per instance. It possibly is also favourable for cache hits. And it just makes sense: static
should be used for things that are shared across all instances (a.k.a. objects) of a certain type (a.k.a. class
).
How to make a <svg> element expand or contract to its parent container?
@robertc has it right, but you also need to notice that svg, #container
causes the svg to be scaled exponentially for anything but 100% (once for #container
and once for svg
).
In other words, if I applied 50% h/w to both elements, it's actually 50% of 50%, or .5 * .5, which equals .25, or 25% scale.
One selector works fine when used as @robertc suggests.
svg {
width:50%;
height:50%;
}
MySQL Error: #1142 - SELECT command denied to user
This error happened on my server when I imported a view with an invalid definer.
Removing the faulty view fixed the error.
The error message didn't say anything about the view in question, but was "complaining" about one of the tables, that was used in the view.
How to Solve Max Connection Pool Error
Here's what u can also try....
run your application....while it is still running launch your command prompt
while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.
Suggestions to fix it:
- Add a connection pool to your connection string.
If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)
- Run regedit from your run command. In the registry editor look for this registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters:
Modify the settings so they read:
MaxUserPort = dword:00004e20 (10,000 decimal)
TcpTimedWaitDelay = dword:0000001e (30 decimal)
This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.
Only use suggestion 2 if 1 fails.
Thank you.
CSS border less than 1px
A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).
Here is a test to prove this point:
_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }
div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_
Output
Which gives the illusion that the last DIV
has a smaller border width, because the blue border blends more with the white background.
Edit: Alternate solution
Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.
_x000D_
_x000D_
.container {
border-style: solid;
border-width: 1px;
margin-bottom: 10px;
}
.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_
jQuery `.is(":visible")` not working in Chrome
There is a weird case where if the element is set to display: inline
the jQuery check for visibility fails.
Example:
CSS
#myspan {display: inline;}
jQuery
$('#myspan').show(); // Our element is `inline` instead of `block`
$('#myspan').is(":visible"); // This is false
To fix it you can hide the element in jQuery and than show/hide
or toggle()
should work fine.
$('#myspan').hide()
$('#otherElement').on('click', function() {
$('#myspan').toggle();
});
vb.net get file names in directory?
Dim fileEntries As String() = Directory.GetFiles("YourPath", "*.txt")
' Process the list of .txt files found in the directory. '
Dim fileName As String
For Each fileName In fileEntries
If (System.IO.File.Exists(fileName)) Then
'Read File and Print Result if its true
ReadFile(fileName)
End If
TransfereFile(fileName, 1)
Next
HashSet vs. List performance
You can use a HybridDictionary which automaticly detects the breaking point, and accepts null-values, making it essentialy the same as a HashSet.
Do Git tags only apply to the current branch?
If you create a tag by e.g.
git tag v1.0
the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.
You can also just refer to the other branch while tagging,
git tag v1.0 name_of_other_branch
which will create the tag to the most recent commit of the other branch.
Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit
git tag v1.0 <sha1>
How to efficiently calculate a running standard deviation?
Here's a "one-liner", spread over multiple lines, in functional programming style:
def variance(data, opt=0):
return (lambda (m2, i, _): m2 / (opt + i - 1))(
reduce(
lambda (m2, i, avg), x:
(
m2 + (x - avg) ** 2 * i / (i + 1),
i + 1,
avg + (x - avg) / (i + 1)
),
data,
(0, 0, 0)))
C error: undefined reference to function, but it IS defined
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
vbscript output to console
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
Technically what is the main difference between Oracle JDK and OpenJDK?
Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)
They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.
How to convert an enum type variable to a string?
There are a lot of good answers here, but I thought some people might find mine useful. I like it because the interface that you use to define the macro is about as simple as it can get. It's also handy because you don't have to include any extra libraries - it all comes with C++ and it doesn't even require a really late version. I pulled pieces from various places online so I can't take credit for all of it, but I think it's unique enough to warrant a new answer.
First make a header file... call it EnumMacros.h or something like that, and put this in it:
// Search and remove whitespace from both ends of the string
static std::string TrimEnumString(const std::string &s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && isspace(*it)) { it++; }
std::string::const_reverse_iterator rit = s.rbegin();
while (rit.base() != it && isspace(*rit)) { rit++; }
return std::string(it, rit.base());
}
static void SplitEnumArgs(const char* szArgs, std::string Array[], int nMax)
{
std::stringstream ss(szArgs);
std::string strSub;
int nIdx = 0;
while (ss.good() && (nIdx < nMax)) {
getline(ss, strSub, ',');
Array[nIdx] = TrimEnumString(strSub);
nIdx++;
}
};
// This will to define an enum that is wrapped in a namespace of the same name along with ToString(), FromString(), and COUNT
#define DECLARE_ENUM(ename, ...) \
namespace ename { \
enum ename { __VA_ARGS__, COUNT }; \
static std::string _Strings[COUNT]; \
static const char* ToString(ename e) { \
if (_Strings[0].empty()) { SplitEnumArgs(#__VA_ARGS__, _Strings, COUNT); } \
return _Strings[e].c_str(); \
} \
static ename FromString(const std::string& strEnum) { \
if (_Strings[0].empty()) { SplitEnumArgs(#__VA_ARGS__, _Strings, COUNT); } \
for (int i = 0; i < COUNT; i++) { if (_Strings[i] == strEnum) { return (ename)i; } } \
return COUNT; \
} \
}
Then, in your main program you can do this...
#include "EnumMacros.h"
DECLARE_ENUM(OsType, Windows, Linux, Apple)
void main() {
OsType::OsType MyOs = OSType::Apple;
printf("The value of '%s' is: %d of %d\n", OsType::ToString(MyOs), (int)OsType::FromString("Apple"), OsType::COUNT);
}
Where the output would be >> The value of 'Apple' is: 2 of 4
Enjoy!
Online PHP syntax checker / validator
To expand on my comment.
You can validate on the command line using php -l [filename]
, which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.
Here's an example of the output when run on a file containing:
<?php
echo no quotes or semicolon
Results in:
PHP Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Errors parsing badfile.php
I suggested you build your own validator.
A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l
and echos the output.
Note: this is not a security risk it does not execute the file, just checks for syntax errors.
Here's a really basic example of creating your own:
<?php
if (isset($_FILES['file'])) {
echo '<pre>';
passthru('php -l '.$_FILES['file']['tmp_name']);
echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
async at console app in C#?
As a quick and very scoped solution:
Task.Result
Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.
When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.
notasync
Excel VBA select range at last row and column
Another simple way:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select
Selection.EntireRow.Delete
or simpler:
ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete
Simple DateTime sql query
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.
Node.js fs.readdir recursive directory search
Check out the final-fs library. It provides a readdirRecursive
function:
ffs.readdirRecursive(dirPath, true, 'my/initial/path')
.then(function (files) {
// in the `files` variable you've got all the files
})
.otherwise(function (err) {
// something went wrong
});
HttpContext.Current.Session is null when routing requests
runAllManagedModulesForAllRequests=true
is actually a real bad solution. This increased the load time of my application by 200%. The better solution is to manually remove and add the session object and to avoid the run all managed modules attribute all together.
The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception
As "M.A. Hanin" said above, it can caused by an InnerException
like this:
"Unrecognized configuration section userSettings. (C:\Users\Pourakbar.h\AppData\Local\Accounting\Accounting.vshost.exe_Url_a4h1gnabohiu4wgiejk0d21rc2kbwr4g\1.0.0.0\user.config line 3)"
and I deleted the folder: C:\Users\Pourakbar.h\AppData\Local\Accounting\Accounting.vshost.exe_Url_a4h1gnabohiu4wgiejk0d21rc2kbwr4g
from my computer and that worked for me!
Error: getaddrinfo ENOTFOUND in nodejs for get call
Check host file which like this
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
How to call webmethod in Asp.net C#
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click
or any other html control event
you can call to the javascript
method with the parameter which in turn calls to the webmethod
to get the value in json
format.
How to get a Char from an ASCII Character Code in c#
You can simply write:
char c = (char) 2;
or
char c = Convert.ToChar(2);
or more complex option for ASCII encoding only
char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];
How do I login and authenticate to Postgresql after a fresh install?
The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.
Login with postgres user
$ psql -U postgres
Creation and login with another user
# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q
$ psql -h localhost -d dbtest -U usertest -p 5432
GL
Source
How to create Temp table with SELECT * INTO tempTable FROM CTE Query
How to Use TempTable in Stored Procedure?
Here are the steps:
CREATE TEMP TABLE
-- CREATE TEMP TABLE
Create Table #MyTempTable (
EmployeeID int
);
INSERT TEMP SELECT DATA INTO TEMP TABLE
-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100
SELECT TEMP TABLE (You can now use this select query)
Select EmployeeID from #MyTempTable
FINAL STEP DROP THE TABLE
Drop Table #MyTempTable
I hope this will help. Simple and Clear :)
print variable and a string in python
If you are using python 3.6 and newer then you can use f-strings to do the task like this.
print(f"I have {card.price}")
just include f in front of your string and add the variable inside curly braces { }.
Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.
Make a nav bar stick
Give headercss position fixed.
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
top:0
}
Then give the content container a 320px padding-top, so it doesn't get behind the header.
SQL to LINQ Tool
Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
Make Vim show ALL white spaces as a character
:match CursorLine /\s\+/
avoids the "you have to search for spaces to get them to show up" bit but afaict can't be configured to do non-hilighting things to the spaces. CursorLine can be any hilighting group and in the default theme it's a plain underline.
Is not an enclosing class Java
What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.
Example :
class Outer
{
class Inner
{
//...
}
}
So, in such case, you can do something like:
Outer o = new Outer();
Outer.Inner obj = o.new Inner();
How to insert a blob into a database using sql server management studio
Ok... this took me way too long. The sql-management studio tool is just not up to simple things like this (which I've noticed before when looking for where to set the timeout on queries, and it was done in 4 different locations)
I downloaded some other sql editor package (sql maestro in my case). And behold it includes a blob editor where you can look at blobs, and load new blobs into these field.
thanks for the input!
Manually map column names with class properties
This works fine:
var sql = @"select top 1 person_id PersonId, first_name FirstName, last_name LastName from Person";
using (var conn = ConnectionFactory.GetConnection())
{
var person = conn.Query<Person>(sql).ToList();
return person;
}
Dapper has no facility that allows you to specify a Column Attribute, I am not against adding support for it, providing we do not pull in the dependency.
How to make child divs always fit inside parent div?
I think I have the solution to your question, assuming you can use flexbox in your project. What you want to do is make #one
a flexbox using display: flex
and use flex-direction: column
to make it a column alignment.
_x000D_
_x000D_
html,_x000D_
body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.border {_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.margin {_x000D_
margin: 5px;_x000D_
}_x000D_
_x000D_
#one {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
#two {_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
#three {_x000D_
width: 100px;_x000D_
height: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="one" class="border">_x000D_
<div id="two" class="border margin"></div>_x000D_
<div id="three" class="border margin"></div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_
Store JSON object in data attribute in HTML jQuery
This is how it worked for me.
Object
var my_object ={"Super Hero":["Iron Man", "Super Man"]};
Set
Encode the stringified object with encodeURIComponent() and set as attribute:
var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);
Get
To get the value as an object, parse the decoded, with decodeURIComponent(), attribute value:
var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));
Getting "project" nuget configuration is invalid error
NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.
Updating Visual Studio to 'Update 2' got it working again.
Tools -> Extensions and Updates ->Visual Studio Update 2
As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.
Swift add icon/image in UITextField
Why don't you go for the easiest approach. For most cases you want to add icons like font awesome... Just use font awesome library and it would be as easy to add an icon to an text field as this:
myTextField.setLeftViewFAIcon(icon: .FAPlus, leftViewMode: .always, textColor: .red, backgroundColor: .clear, size: nil)
You would need to install first this swift library:
https://github.com/Vaberer/Font-Awesome-Swift
Creating a Shopping Cart using only HTML/JavaScript
I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)
I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.
You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm
You can try following approach:
//create array that will hold all ordered products
var shoppingCart = [];
//this function manipulates DOM and displays content of our shopping cart
function displayShoppingCart(){
var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
//ensure we delete all previously added rows from ordered products table
while(orderedProductsTblBody.rows.length>0) {
orderedProductsTblBody.deleteRow(0);
}
//variable to hold total price of shopping cart
var cart_total_price=0;
//iterate over array of objects
for(var product in shoppingCart){
//add new row
var row=orderedProductsTblBody.insertRow();
//create three cells for product properties
var cellName = row.insertCell(0);
var cellDescription = row.insertCell(1);
var cellPrice = row.insertCell(2);
cellPrice.align="right";
//fill cells with values from current product object of our array
cellName.innerHTML = shoppingCart[product].Name;
cellDescription.innerHTML = shoppingCart[product].Description;
cellPrice.innerHTML = shoppingCart[product].Price;
cart_total_price+=shoppingCart[product].Price;
}
//fill total cost of our shopping cart
document.getElementById("cart_total").innerHTML=cart_total_price;
}
function AddtoCart(name,description,price){
//Below we create JavaScript Object that will hold three properties you have mentioned: Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name=name;
singleProduct.Description=description;
singleProduct.Price=price;
//Add newly created product to our shopping cart
shoppingCart.push(singleProduct);
//call display function to show on screen
displayShoppingCart();
}
//Add some products to our shopping cart via code or you can create a button with onclick event
//AddtoCart("Table","Big red table",50);
//AddtoCart("Door","Big yellow door",150);
//AddtoCart("Car","Ferrari S23",150000);
<table cellpadding="4" cellspacing="4" border="1">
<tr>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="0">
<thead>
<tr>
<td colspan="2">
Products for sale
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
Table
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
</td>
</tr>
<tr>
<td>
Door
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
</td>
</tr>
<tr>
<td>
Car
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
</td>
</tr>
</tbody>
</table>
</td>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
<thead>
<tr>
<td>
Name
</td>
<td>
Description
</td>
<td>
Price
</td>
</tr>
</thead>
<tbody id="orderedProductsTblBody">
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right" id="cart_total">
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</table>
Please have a look at following free client-side shopping cart:
SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.
Documentation
http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html
Hope you will find it useful.
How to have multiple colors in a Windows batch file?
If you have a modern Windows (that has powershell installed), the following may work fine as well
call :PrintBright Something Something
(do actual batch stuff here)
call :PrintBright Done!
goto :eof
:PrintBright
powershell -Command Write-Host "%*" -foreground "White"
Adjust the color as you see fit.
How line ending conversions work with git core.autocrlf between different operating systems
Did some tests both on linux and windows. I use a test file containing lines ending in LF and also lines ending in CRLF.
File is committed , removed and then checked out.
The value of core.autocrlf is set before commit and also before checkout.
The result is below.
commit core.autocrlf false, remove, checkout core.autocrlf false: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf input: LF=>LF CRLF=>CRLF
commit core.autocrlf false, remove, checkout core.autocrlf true : LF=>LF CRLF=>CRLF
commit core.autocrlf input, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf input, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
commit core.autocrlf true, remove, checkout core.autocrlf false: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf input: LF=>LF CRLF=>LF
commit core.autocrlf true, remove, checkout core.autocrlf true : LF=>CRLF CRLF=>CRLF
How do I pass command line arguments to a Node.js program?
There's an app for that. Well, module. Well, more than one, probably hundreds.
Yargs is one of the fun ones, its docs are cool to read.
Here's an example from the github/npm page:
#!/usr/bin/env node
var argv = require('yargs').argv;
console.log('(%d,%d)', argv.x, argv.y);
console.log(argv._);
Output is here (it reads options with dashes etc, short and long, numeric etc).
$ ./nonopt.js -x 6.82 -y 3.35 rum
(6.82,3.35)
[ 'rum' ]
$ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
(0.54,1.12)
[ 'me hearties', 'yo', 'ho' ]
ALTER TABLE to add a composite primary key
ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);
If a primary key already exists then you want to do this
ALTER TABLE provider DROP PRIMARY KEY, ADD PRIMARY KEY(person, place, thing);
How to create separate AngularJS controller files?
For brevity, here's an ES2015 sample that doesn't rely on global variables
// controllers/example-controller.js
export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
// something...
}
// controllers/another-controller.js
export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
// functionality...
}
// app.js
import angular from "angular";
import {
ExampleControllerName,
ExampleController
} = "./controllers/example-controller";
import {
AnotherControllerName,
AnotherController
} = "./controllers/another-controller";
angular.module("myApp", [/* deps */])
.controller(ExampleControllerName, ExampleController)
.controller(AnotherControllerName, AnotherController)
React Native android build failed. SDK location not found
You must write correct full path.
Don't use '~/Library/Android/sdk'
vi ~/.bashrc
export ANDROID_HOME=/Users/{UserName}/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools
export PATH=${PATH}:${ANDROID_HOME}/platform-tools
source ~/.bashrc
How to get a list of MySQL views?
Try moving that mysql.bak
directory out of /var/lib/mysql
to say /root/
or something. It seems like mysql is finding that and it may be causing that ERROR 1102 (42000): Incorrect database name 'mysql.bak'
error.
Check if the number is integer
I am not sure what you are trying to accomplish. But here are some thoughts:
1. Convert to integer:
num = as.integer(123.2342)
2. Check if a variable is an integer:
is.integer(num)
typeof(num)=="integer"
Nested Recycler view height doesn't wrap its content
As @yigit mentioned, you need to override onMeasure(). Both @user2302510 and @DenisNek have good answers but if you want to support ItemDecoration you can use this custom layout manager.
And other answers cannot scroll when there are more items than can be displayed on the screen though. This one is using default implemantation of onMeasure() when there are more items than screen size.
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
// If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
if (height < heightSize && width < widthSize) {
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(recycler, state, widthSpec, heightSpec);
}
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
// For adding Item Decor Insets to view
super.measureChildWithMargins(view, 0, 0);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom() + getPaddingBottom() + getDecoratedBottom(view) , p.height);
view.measure(childWidthSpec, childHeightSpec);
// Get decorated measurements
measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
And if you want to use it with GridLayoutManager just extends it from GridLayoutManager and change
for (int i = 0; i < getItemCount(); i++)
to
for (int i = 0; i < getItemCount(); i = i + getSpanCount())
C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?
For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.
Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.
Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How do I enable EF migrations for multiple contexts to separate databases?
I just bumped into the same problem and I used the following solution (all from Package Manager Console)
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyProject.Models.ContextA
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextB" -ContextTypeName MyProject.Models.ContextB
This will create 2 separate folders in the Migrations folder. Each will contain the generated Configuration.cs
file. Unfortunately you still have to rename those Configuration.cs
files otherwise there will be complaints about having two of them. I renamed my files to ConfigA.cs
and ConfigB.cs
EDIT: (courtesy Kevin McPheat) Remember when renaming the Configuration.cs files, also rename the class names and constructors /EDIT
With this structure you can simply do
PM> Add-Migration -ConfigurationTypeName ConfigA
PM> Add-Migration -ConfigurationTypeName ConfigB
Which will create the code files for the migration inside the folder next to the config files (this is nice to keep those files together)
PM> Update-Database -ConfigurationTypeName ConfigA
PM> Update-Database -ConfigurationTypeName ConfigB
And last but not least those two commands will apply the correct migrations to their corrseponding databases.
EDIT 08 Feb, 2016:
I have done a little testing with EF7 version 7.0.0-rc1-16348
I could not get the -o|--outputDir option to work. It kept on giving Microsoft.Dnx.Runtime.Common.Commandline.CommandParsingException: Unrecognized command or argument
However it looks like the first time an migration is added it is added into the Migrations folder, and a subsequent migration for another context is automatically put into a subdolder of migrations.
The original names ContextA
seems to violate some naming conventions so I now use ContextAContext
and ContextBContext
. Using these names you could use the following commands:
(note that my dnx still works from the package manager console and I do not like to open a separate CMD window to do migrations)
PM> dnx ef migrations add Initial -c "ContextAContext"
PM> dnx ef migrations add Initial -c "ContextBContext"
This will create a model snapshot and a initial migration in the Migrations
folder for ContextAContext
. It will create a folder named ContextB
containing these files for ContextBContext
I manually added a ContextA
folder and moved the migration files from ContextAContext
into that folder. Then I renamed the namespace inside those files (snapshot file, initial migration and note that there is a third file under the initial migration file ... designer.cs). I had to add .ContextA
to the namespace, and from there the framework handles it automatically again.
Using the following commands would create a new migration for each context
PM> dnx ef migrations add Update1 -c "ContextAContext"
PM> dnx ef migrations add Update1 -c "ContextBContext"
and the generated files are put in the correct folders.
Calculate difference between 2 date / times in Oracle SQL
Calculate age from HIREDATE to system date of your computer
SELECT HIREDATE||' '||SYSDATE||' ' ||
TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12) ||' YEARS '||
TRUNC((MONTHS_BETWEEN(SYSDATE,HIREDATE))-(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12)*12))||
'MONTHS' AS "AGE " FROM EMP;
How do I get a computer's name and IP address using VB.NET?
Private Function GetIPv4Address() As String
GetIPv4Address = String.Empty
Dim strHostName As String = System.Net.Dns.GetHostName()
Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
For Each ipheal As System.Net.IPAddress In iphe.AddressList
If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
GetIPv4Address = ipheal.ToString()
End If
Next
End Function
How to set character limit on the_content() and the_excerpt() in wordpress
Or even easier and without the need to create a filter: use PHP's mb_strimwidth
to truncate a string to a certain width (length). Just make sure you use one of the get_
syntaxes.
For example with the content:
<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>
This will cut the string at 400 characters and close it with ...
.
Just add a "read more"-link to the end by pointing to the permalink with get_permalink()
.
<a href="<?php the_permalink() ?>">Read more </a>
Of course you could also build the read more
in the first line. Than just replace '...'
with '<a href="' . get_permalink() . '">[Read more]</a>'
Modifying list while iterating
The general rule of thumb is that you don't modify a collection/array/list while iterating over it.
Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.
Enforcing the type of the indexed members of a Typescript object?
A quick update: since Typescript 2.1 there is a built in type Record<T, K>
that acts like a dictionary.
In this case you could declare stuff like so:
var stuff: Record<string, any> = {};
You could also limit/specify potential keys by unioning literal types:
var stuff: Record<'a'|'b'|'c', string|boolean> = {};
Here's a more generic example using the record type from the docs:
// For every properties K of type T, transform it to U
function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>
const names = { foo: "hello", bar: "world", baz: "bye" };
const lengths = mapObject(names, s => s.length); // { foo: number, bar: number, baz: number }
TypeScript 2.1 Documentation on Record<T, K>
The only disadvantage I see to using this over {[key: T]: K}
is that you can encode useful info on what sort of key you are using in place of "key" e.g. if your object only had prime keys you could hint at that like so: {[prime: number]: yourType}
.
Here's a regex I wrote to help with these conversions. This will only convert cases where the label is "key". To convert other labels simply change the first capturing group:
Find: \{\s*\[(key)\s*(+\s*:\s*(\w+)\s*\]\s*:\s*([^\}]+?)\s*;?\s*\}
Replace: Record<$2, $3>
Angular ForEach in Angular4/Typescript?
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
Microsoft.ACE.OLEDB.12.0 provider is not registered
Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:
1) ensure that the 2007 database engine is installed, this can be downloaded at:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.
3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.
4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).
5) done, and your error message will go away.
How to run a function in jquery
I would do it this way:
(function($) {
jQuery.fn.doSomething = function() {
return this.each(function() {
var $this = $(this);
$this.click(function(event) {
event.preventDefault();
// Your function goes here
});
});
};
})(jQuery);
Then on document ready you can do stuff like this:
$(document).ready(function() {
$('#div1').doSomething();
$('#div2').doSomething();
});
What is http multipart request?
A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding
Hy,
In my case this error appeared because the Application pool of the webservice had the wrong 32/64 bit setting. So this error needed the following fix: you go to the IIS, select the site of the webservice , go to Advanced setting and get the application pool. Then go to Application pools, select it, go to "Advanced settings..." , select the "Enable 32 bit applications" and make it Enable or Disable, according to the 32/64 bit type of your webservice.
If the setting is True, it means that it only allows 32 bit applications, so for 64 bit apps you have to make it "Disable" (default).
Initialize a byte array to a certain value, other than the default null?
This function is way faster than a for loop for filling an array.
The Array.Copy command is a very fast memory copy function. This function takes advantage of that by repeatedly calling the Array.Copy command and doubling the size of what we copy until the array is full.
I discuss this on my blog at https://grax32.com/2013/06/fast-array-fill-function-revisited.html (Link updated 12/16/2019). Also see Nuget package that provides this extension method. http://sites.grax32.com/ArrayExtensions/
Note that this would be easy to make into an extension method by just adding the word "this" to the method declarations i.e. public static void ArrayFill<T>(this T[] arrayToFill ...
public static void ArrayFill<T>(T[] arrayToFill, T fillValue)
{
// if called with a single value, wrap the value in an array and call the main function
ArrayFill(arrayToFill, new T[] { fillValue });
}
public static void ArrayFill<T>(T[] arrayToFill, T[] fillValue)
{
if (fillValue.Length >= arrayToFill.Length)
{
throw new ArgumentException("fillValue array length must be smaller than length of arrayToFill");
}
// set the initial array value
Array.Copy(fillValue, arrayToFill, fillValue.Length);
int arrayToFillHalfLength = arrayToFill.Length / 2;
for (int i = fillValue.Length; i < arrayToFill.Length; i *= 2)
{
int copyLength = i;
if (i > arrayToFillHalfLength)
{
copyLength = arrayToFill.Length - i;
}
Array.Copy(arrayToFill, 0, arrayToFill, i, copyLength);
}
}
How can I get query string values in JavaScript?
I did a small URL library for my needs here: https://github.com/Mikhus/jsurl
It's a more common way of manipulating the URLs in JavaScript. Meanwhile it's really lightweight (minified and gzipped < 1 KB) and has a very simple and clean API. And it does not need any other library to work.
Regarding the initial question, it's very simple to do:
var u = new Url; // Current document URL
// or
var u = new Url('http://user:[email protected]:8080/some/path?foo=bar&bar=baz#anchor');
// Looking for query string parameters
alert( u.query.bar);
alert( u.query.foo);
// Modifying query string parameters
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']
alert(u.query.foo);
alert(u.query.woo);
alert(u);
How can I easily view the contents of a datatable or dataview in the immediate window
The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.
To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.
Determine file creation date in Java
I've solved this problem using JDK 7 with this code:
package FileCreationDate;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Main
{
public static void main(String[] args) {
File file = new File("c:\\1.txt");
Path filePath = file.toPath();
BasicFileAttributes attributes = null;
try
{
attributes =
Files.readAttributes(filePath, BasicFileAttributes.class);
}
catch (IOException exception)
{
System.out.println("Exception handled when trying to get file " +
"attributes: " + exception.getMessage());
}
long milliseconds = attributes.creationTime().to(TimeUnit.MILLISECONDS);
if((milliseconds > Long.MIN_VALUE) && (milliseconds < Long.MAX_VALUE))
{
Date creationDate =
new Date(attributes.creationTime().to(TimeUnit.MILLISECONDS));
System.out.println("File " + filePath.toString() + " created " +
creationDate.getDate() + "/" +
(creationDate.getMonth() + 1) + "/" +
(creationDate.getYear() + 1900));
}
}
}
Plotting 4 curves in a single plot, with 3 y-axes
I know of plotyy that allows you to have two y-axes, but no "plotyyy"!
Perhaps you can normalize the y values to have the same scale (min/max normalization, zscore standardization, etc..), then you can just easily plot them using normal plot, hold
sequence.
Here's an example:
%# random data
x=1:20;
y = [randn(20,1)*1 + 0 , randn(20,1)*5 + 10 , randn(20,1)*0.3 + 50];
%# plotyy
plotyy(x,y(:,1), x,y(:,3))
%# orginial
figure
subplot(221), plot(x,y(:,1), x,y(:,2), x,y(:,3))
title('original'), legend({'y1' 'y2' 'y3'})
%# normalize: (y-min)/(max-min) ==> [0,1]
yy = bsxfun(@times, bsxfun(@minus,y,min(y)), 1./range(y));
subplot(222), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('minmax')
%# standarize: (y - mean) / std ==> N(0,1)
yy = zscore(y);
subplot(223), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('zscore')
%# softmax normalization with logistic sigmoid ==> [0,1]
yy = 1 ./ ( 1 + exp( -zscore(y) ) );
subplot(224), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))
title('softmax')
Clear android application user data
The command pm clear com.android.browser
requires root permission.
So, run su
first.
Here is the sample code:
private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();
p.waitFor();
String result = stdoutReader.getResult();
The class StreamReader
:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
@Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}
How do I delete all the duplicate records in a MySQL table without temp tables
Add Unique Index on your table:
ALTER IGNORE TABLE `TableA`
ADD UNIQUE INDEX (`member_id`, `quiz_num`, `question_num`, `answer_num`);
Another way to do this would be:
Add primary key in your table then you can easily remove duplicates from your table using the following query:
DELETE FROM member
WHERE id IN (SELECT *
FROM (SELECT id FROM member
GROUP BY member_id, quiz_num, question_num, answer_num HAVING (COUNT(*) > 1)
) AS A
);
How can I capture the right-click event in JavaScript?
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
What is the difference between children and childNodes in JavaScript?
Pick one depends on the method you are looking for!?
I will go with ParentNode.children:
As it provides namedItem
method that allows me directly to get one of the children elements without looping through all children or avoiding to use getElementById
etc.
e.g.
ParentNode.children.namedItem('ChildElement-ID'); // JS
ref.current.children.namedItem('ChildElement-ID'); // React
this.$refs.ref.children.namedItem('ChildElement-ID'); // Vue
I will go with Node.childNodes:
As it provides forEach
method when I work with window.IntersectionObserver
e.g.
nodeList.forEach((node) => { observer.observe(node) })
// IE11 does not support forEach on nodeList, but easy to be polyfilled.
On Chrome 83
Node.childNodes provides entries
, forEach
, item
, keys
, length
and values
ParentNode.children provides item
, length
and namedItem